更改子图上的刻度数

spe*_*ec3 3 python matplotlib axis-labels

如果我有一个子图,如何更改其刻度数?我不知道数据的最大值和最小值。

我的代码是:

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()                
Run Code Online (Sandbox Code Playgroud)

Ffi*_*ydd 6

您可以使用matplotlib.ticker.MaxNLocator自动选择最大N间隔的刻度线。

ax.yaxis.set_major_locator下面仅给出了 y 轴的玩具示例,您可以通过替换为来将其用于 x 轴ax.xaxis.set_major_locator

如果您有对数图,则可以matplotlib.ticker.LogLocatornumticks关键字参数一起使用。在这种情况下,您可以将定义行替换yticksyticks = 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()
Run Code Online (Sandbox Code Playgroud)

示例图 `