SalN85
SalN85

Reputation: 465

Setting X-limit for subplots

I am new to data visualization and have a simple question regarding x-limit range. Since I have 4 different plots, I am using 2x2 grid, using add_subplot method. Here is what I have done so far:

fig = plt.figure()
ax = fig.add_subplot(221, facecolor='lightgrey')
weeks = []
for weekNum in df.WeekNum:
    weeks.append(weekNum)
maxNumber = max(weeks)
sixWeekList = list(range(maxNumber-6, maxNumber))
ax.set_title('Photo', fontsize = 14)
ax.set_xlabel('Week Number')
ax.set_xlim(sixWeekList)
ax.set_ylabel('Percentage')
ax.set_ylim([0,100])
fig.tight_layout()

My aim to bar plot the latest 6 weeks, every time I run the script. However, when I run the above program, it shows the following error, and doesn't let me set the range for x-axis. However, if I just put [30, 35] in ax.set_xlim(), it runs smoothly, ex: ax.set_xlim([30,35])

**ValueError**                    Traceback (most recent call last)
<ipython-input-165-cbbb1eabca92> in <module>()

---> ax.set_xlim(tmp)
ValueError: too many values to unpack (expected 2)

Any alternate way to resolve this?

Upvotes: 0

Views: 84

Answers (1)

johnchase
johnchase

Reputation: 13705

Try specifying the x limits with the max and min directly rather than a list, which is what it is failing.

For example:

fig = plt.figure()
ax = fig.add_subplot(221, facecolor='lightgrey')
weeks = []
for weekNum in df.WeekNum:
    weeks.append(weekNum)
maxNumber = max(weeks)
sixWeekList = list(range(maxNumber-6, maxNumber))
ax.set_title('Photo', fontsize = 14)
ax.set_xlabel('Week Number')

#just pass max and min here
ax.set_xlim(maxNumber-6, maxNumber)

ax.set_ylabel('Percentage')
ax.set_ylim([0,100])

Upvotes: 1

Related Questions