Matplotlib semi log plot:当range为larg时,小刻度线消失

2024-04-24 03:47:14 发布

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


Tags: python
1条回答
网友
1楼 · 发布于 2024-04-24 03:47:14

matplotlib的解决方案>;=2.0.2

让我们考虑下面的例子

enter image description here

由以下代码生成:

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

y = np.arange(12)
x = 10.0**y

fig, ax=plt.subplots()
ax.plot(x,y)
ax.set_xscale("log")
plt.show()

小的标签确实消失了,通常的显示方式(比如plt.tick_params(axis='x', which='minor'))也失败了。

第一步是在轴上显示10的所有能量

locmaj = matplotlib.ticker.LogLocator(base=10,numticks=12) 
ax.xaxis.set_major_locator(locmaj)

enter image description here

其中诀窍是将numticks设置为等于或大于滴答数的数字(在本例中为12或更高)。

然后,我们可以添加一些小标签

locmin = matplotlib.ticker.LogLocator(base=10.0,subs=(0.2,0.4,0.6,0.8),numticks=12)
ax.xaxis.set_minor_locator(locmin)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

enter image description here

请注意,我将此限制为每十年包含4个小刻度(使用8同样可能,但在本例中会使轴过度拥挤)。还要注意numticks再次(非常不确切地)大于或等于12。

最后,我们需要使用一个NullFormatter()来表示小蜱虫,以避免它们出现任何蜱虫标签。

matplotlib 2.0.0

的解决方案

以下命令在matplotlib 2.0.0或更低版本中有效,但在matplotlib 2.0.2中无效。

让我们考虑下面的例子

enter image description here

由以下代码生成:

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

y = np.arange(12)
x = 10.0**y

fig, ax=plt.subplots()
ax.plot(x,y)
ax.set_xscale("log")
plt.show()

小的标签确实消失了,通常的显示方式(比如plt.tick_params(axis='x', which='minor'))也失败了。

第一步是在轴上显示10的所有能量

locmaj = matplotlib.ticker.LogLocator(base=10.0, subs=(0.1,1.0, ))
ax.xaxis.set_major_locator(locmaj)

enter image description here

然后,我们可以添加一些小标签

locmin = matplotlib.ticker.LogLocator(base=10.0, subs=(0.1,0.2,0.4,0.6,0.8,1,2,4,6,8,10 )) 
ax.xaxis.set_minor_locator(locmin)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

enter image description here

请注意,我将此限制为每十年包含4个小刻度(使用8同样可能,但在本例中会使轴过度拥挤)。还要注意-这可能是这里的关键-subs参数给出了放置记号的基数的整数幂的倍数(请参见documentation),它给出了一个范围超过20年的列表,而不是一个。

最后,我们需要使用一个NullFormatter()来表示小蜱虫,以避免它们出现任何蜱虫标签。

相关问题 更多 >