问题
If I have a subplot how can I change its NUMBER of ticks? I don't know the maximum and the minimum of the data.
my code is:
azal = rif.add_subplot(111)
azal.plot(eels*(10**9), averspe, label='data')
azal.plot(eels*(10**9), beck, label='fit')
azal.set_yscale('log')
azal.set_xscale('log')
h2 = azal.axvline(x = p2*(10**9), color='r')
azal.legend(bbox_to_anchor=(1.05, 1), loc=4, fontsize='xx-large', borderaxespad=0.)
rif.canvas.draw()
回答1:
You can use the matplotlib.ticker.MaxNLocator to automatically choose a maximum of N
nicely spaced ticks.
A toy example is given below for the y-axis only, you can use it for the x-axis by replacing ax.yaxis.set_major_locator
with ax.xaxis.set_major_locator
.
If you've got a log plot then you can use matplotlib.ticker.LogLocator with the numticks
keyword argument. In which case you'd replace the line defining yticks
with yticks = ticker.LogLocator(numticks=M)
.
import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np
N = 10
x = np.arange(N)
y = np.random.randn(N)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
# Create your ticker object with M ticks
M = 3
yticks = ticker.MaxNLocator(M)
# Set the yaxis major locator using your ticker object. You can also choose the minor
# tick positions with set_minor_locator.
ax.yaxis.set_major_locator(yticks)
plt.show()

来源:https://stackoverflow.com/questions/27425974/change-ticks-number-on-a-subplot