Matplotlib:设置xlimits也会强制使用记号标签?

2024-03-28 09:01:41 发布

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

我刚升级到matplotlib 2.0,我觉得我在吃疯狂的药。我试着做一个对数线性图,y轴在线性刻度上,x轴在log10刻度上。以前,下面的代码可以让我精确地指定记号的位置以及它们的标签:

import matplotlib.pyplot as plt

plt.plot([0.0,5.0], [1.0, 1.0], '--', color='k', zorder=1, lw=2)

plt.xlim(0.4,2.0)
plt.ylim(0.0,2.0)

plt.xscale('log')

plt.tick_params(axis='x',which='minor',bottom='off',top='off')

xticks = [0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
ticklabels = ['0.4', '0.6', '0.8', '1.0', '1.2', '1.4', '1.6', '1.8', '2.0']
plt.xticks(xticks, ticklabels)

plt.show()

但在matplotlib 2.0中,这使我得到了一组重叠的记号标签,matplotlib显然想自动创建记号:

enter image description here

但如果我把plt.xlim公司(0.4,2.0)“行并让它自动确定轴限制,没有重叠的刻度标签,我只得到我想要的:

enter image description here

但这行不通,因为我现在有无用的x轴极限。在

有什么想法吗?在

编辑:对于将来搜索互联网的人来说,我越来越确信这实际上是matplotlib本身的一个缺陷。我又回到1.5.3节。只是为了避免这个问题。在


Tags: 代码importmatplotlib对数plt线性标签pyplot
1条回答
网友
1楼 · 发布于 2024-03-28 09:01:41

重叠的其他ticklabels来自一些次要的ticklabels,它们出现在绘图中。要去掉它们,可以将次要格式化程序设置为NullFormatter

plt.gca().xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

问题中的完整代码可能看起来像

^{pr2}$

enter image description here

下面的代码可能更直观,因为它没有将xticklabels设置为字符串,其中我们使用FixedLocatorScalarFormatter
此代码生成与上面相同的绘图。在

import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np

x = np.linspace(0,2.5)
y = np.sin(x*6)
plt.plot(x,y, ' ', color='k', zorder=1, lw=2)

plt.xlim(0.4,2.0)
plt.xscale('log')

xticks = [0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]

xmajorLocator = matplotlib.ticker.FixedLocator(locs=xticks) 
xmajorFormatter = matplotlib.ticker.ScalarFormatter()
plt.gca().xaxis.set_major_locator( xmajorLocator )
plt.gca().xaxis.set_major_formatter( xmajorFormatter )
plt.gca().xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

plt.show()

相关问题 更多 >