Dan
Dan

Reputation: 12675

Why is set_xlim() not setting the x-limits in my figure?

I'm plotting some data with matplotlib. I want the plot to focus on a specific range of x-values, so I'm using set_xlim().

Roughly, my code looks like this:

fig=plt.figure()
ax=fig.add_subplot(111)
for ydata in ydatalist:
    ax.plot(x_data,y_data[0],label=ydata[1])
ax.set_xlim(left=0.0,right=1000)
plt.savefig(filename)

When I look at the plot, the x range ends up being from 0 to 12000. This occurs whether set_xlim() occurs before or after plot(). Why is set_xlim() not working in this situation?

Upvotes: 39

Views: 72372

Answers (5)

Nicouh
Nicouh

Reputation: 109

The same thing occurred to me today. My issue was that the data was not in the right format, i.e. not floats. The limits I set (itself floats) became meaningless compared to e.g. strings. After putting float() around the data, everything worked as expected.

Upvotes: 4

Andrej Kružliak
Andrej Kružliak

Reputation: 95

I have struggled a lot with the ax.set_xlim() and couldn't get it to work properly and I found out why exactly. After setting the xlim I was setting the xticks and xticklabels (those are the vertical lines on the x-axis and their labels) and this somehow elongated the axis to the needed extent. So if the last tick was at 300 and my xlim was set at 100, it again widened the axis to the 300 just to place the tick there. So the solution was to put it just after the troublesome code:

ax.set_xlabel(label)
ax.set_xticks(xticks)
ax.set_xticklabels(xticks, rotation=60)

ax.set_xlim(xmin=0.0, xmax=100.0)

Upvotes: 2

wander95
wander95

Reputation: 1366

In my case the following solutions alone did not work:

ax.set_xlim([0, 5.00])
ax.set_xbound(lower=0.0, upper=5.00)

However, setting the aspect using set_aspect worked, i.e:

ax.set_aspect('auto')
ax.set_xlim([0, 5.00])
ax.set_xbound(lower=0.0, upper=5.00)

Upvotes: 9

esmit
esmit

Reputation: 1797

Out of curiosity, what about switching in the old xmin and xmax?

fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x_data,y_data)
ax.set_xlim(xmin=0.0, xmax=1000)
plt.savefig(filename)

Upvotes: 19

Dan
Dan

Reputation: 12675

The text of this answer was taken from an answer that was deleted almost immediately after it was posted.

set_xlim() limits the data that is displayed on the plot.

In order to change the bounds of the axis, use set_xbound().

fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x_data,y_data)
ax.set_xbound(lower=0.0, upper=1000)
plt.savefig(filename)

Upvotes: 17

Related Questions