Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding extra axis ticks using matplotlib

I have a simple plot code as

plt.plot(x,y) plt.show() 

I want to add some extra ticks on the x-axis in addition to the current ones, let's say at

extraticks=[2.1, 3, 7.6] 

As you see I do not have a pattern for ticks so I do not want to increase the tick frequency for the whole axis; just keep the original ones and add those extras...

Is it possible, at all?

Regards

like image 986
ahmethungari Avatar asked Feb 05 '13 20:02

ahmethungari


People also ask

How do I get more ticks in MatPlotLib?

Setting Figure-Level Tick Frequency in Matplotlib You can use the xticks() and yticks() functions and pass in an array denoting the actual ticks. On the X-axis, this array starts on 0 and ends at the length of the x array. On the Y-axis, it starts at 0 and ends at the max value of y .

How do I increase axis labels in MatPlotLib?

If we want to change the font size of the axis labels, we can use the parameter “fontsize” and set it your desired number.


2 Answers

Yes, you can try something like:

plt.xticks(list(plt.xticks()[0]) + extraticks) 

The function to use is xticks(). When called without arguments, it returns the current ticks. Calling it with arguments, you can set the tick positions and, optionally, labels.

like image 79
Lev Levitsky Avatar answered Sep 19 '22 14:09

Lev Levitsky


For the sake of completeness, I would like to give the OO version of @Lev-Levitsky's great answer:

lines = plt.plot(x,y) ax = lines[0].axes ax.set_xticks(list(ax.get_xticks()) + extraticks) 

Here we use the Axes object extracted from the Lines2D sequence returned by plot. Normally if you are using the OO interface you would already have a reference to the Axes up front and you would call plot on that instead of on pyplot.

Corner Caveat

If for some reason you have modified your axis limits (e.g, by programatically zooming in to a portion of the data), you will need to restore them after this operation:

lim = ax.get_xlim() ax.set_xticks(list(ax.get_xticks()) + extraticks) ax.set_xlim(lim) 

Otherwise, the plot will make the x-axis show all the available ticks on the axis.

like image 40
Mad Physicist Avatar answered Sep 19 '22 14:09

Mad Physicist