更改子图上的刻度号 [英] change ticks number on a subplot
问题描述
如果我有一个子图,如何更改它的NUMBER刻度?我不知道数据的最大值和最小值.
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.
我的代码是:
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()
推荐答案
You can use the matplotlib.ticker.MaxNLocator
to automatically choose a maximum of N
nicely spaced ticks.
下面给出了一个仅用于y轴的玩具示例,您可以通过将ax.yaxis.set_major_locator
替换为ax.xaxis.set_major_locator
来将其用于x轴.
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
.
如果您有对数图,则可以使用 matplotlib.ticker.LogLocator
和numticks
关键字参数.在这种情况下,您可以将定义yticks
的行替换为yticks = ticker.LogLocator(numticks=M)
.
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()
`
这篇关于更改子图上的刻度号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!