Home > Mobile >  How to set a maximum number of x-ticks in matplotlib
How to set a maximum number of x-ticks in matplotlib

Time:10-25

I am trying to plot two long time series in matplotlib. Since I am not going to need any subplot, I did not use the figure.add_subplot() method.

fig = plt.figure()
plt.plot(series1)
plt.plot(series2)
plt.xlabel('Date')
plt.ylabel("Values")
plt.legend(loc='best')
plt.title(Plot title)
fig.autofmt_xdate()
plt.savefig("fig.png", format="png")

However, the above format works well with some short series, while with long ones the x-ticks overlap quite a bit even if they are rotated with the autofmt_xdate() command. I am aware of the ax.set_major_locator() solution when using subplots but I was not able to find a similar solution when working with plt.figure().

CodePudding user response:

You can get an instance of the axis using the following:

ax = plt.gca()

Then, you can use the methods you normally use on the axis:

ax.xaxis.set_major_locator(....)
  • Related