只显示主要刻度标签的次要刻度

2024-05-15 22:18:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望轴上有小刻度,但只显示大刻度标签。例如,小记号是[19,20,21。。。40,41]和主要的记号标签是[20,25,30,35,40]。我该怎么做?下面的代码不起作用。我知道可以使用multipleocator,FormatStrFormatter,比如this example。但是,我在轴上的值有点“奇怪”,起始值是19(不是20),结束值是41,这在使用multipleocator时会造成困难。

import numpy as np
from matplotlib import pylab as plt

fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(19.,41,23)
y = x**2
ax.plot(x,y)
ax.set_xticks(x)
ax.set_xticklabels(x, minor=False)
plt.show()

它给了我以下的情节: enter image description here

ax.set_xticklabels([20, 25, 30, 35, 40], minor=False) 再给我一个情节: enter image description here 我怎样才能改变我的代码来得到我需要的。非常感谢你的帮助!


Tags: 代码importfalseasnpfigplt标签
1条回答
网友
1楼 · 发布于 2024-05-15 22:18:56

我真的不明白为什么在您的示例中使用MultipleLocator很困难。

通过在代码中添加这些行

from matplotlib.ticker import MultipleLocator, FormatStrFormatter

majorLocator   = MultipleLocator(5)
majorFormatter = FormatStrFormatter('%d')
minorLocator   = MultipleLocator(1)

ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)
ax.xaxis.set_minor_locator(minorLocator)

你会得到这个图像,我知道这是你想要的(不是吗?): enter image description here


如果不希望刻度显示在数据范围之下,请使用FixedLocator手动定义刻度:

from matplotlib.ticker import FixedLocator

majorLocator   = FixedLocator(np.linspace(20,40,5))
minorLocator   = FixedLocator(np.linspace(19,41,23))

你会得到这个图像: enter image description here

相关问题 更多 >