Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force pyplot to show axis limits

My x and y axis normally range from 0 to 300 and 0 to 60, respectively.

I want to show only values from 5 <= x <= 300, however, so I do

ax.set_xlim(left=5)

after which the graph does indeed start at 5, but there is nothing to indicate that. My first tick on the x-axis is at 50, and then 100, 150... the y-axis has ticks labeled 0, 20, 40, 60, which will easily mislead the viewer into thinking that the lower limit of 0 for the y-axis also represents the lower limit of 0 for the x-axis.

How can I force pyplot to display an extra tick at x=5 so that the viewer is told explicitly that both axes do not have the same lower bound of 0?

like image 867
wrongusername Avatar asked Dec 02 '25 15:12

wrongusername


1 Answers

You can use xticks to set the ticks of the x axis. This is an ipython session:

In [18]: l = [random.randint(0, 10) for i in range(300)]

In [19]: plot(l)
Out[19]: [<matplotlib.lines.Line2D at 0x9241f60>]

In [20]: plt.xlim(xmin=5)       # I set to start at 5. No label is draw
Out[20]: (5, 300.0)

In [21]: plt.xticks(arange(5, 301, 50))  # this makes the first xtick at left to be 5
                                         # note the max range is 301, otherwise you will never
                                         # get 300 even if you set the appropriate step

Note that now, at the right side of the xaxis, there is no label. Last label is 255 (the same problem you had at the left side). You can get this label modifying the step of the arange in order to max - min / step to be (or be very close to) an integer value (the number of ticks).

This makes it (although the decimal numbers are ugly):

In [38]: plt.xticks(arange(5, 301, 29.5)) 
like image 186
joaquin Avatar answered Dec 04 '25 07:12

joaquin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!