Matplotlib pyplot 对数刻度轴刻度线标签(值)消失。如何设置刻度线和标签?

时间:2021-03-16 18:37:44

标签: python matplotlib label

创建 y 轴对数刻度时,绘图会显示一些刻度线,但没有这些刻度线的标签。怎么会有人:

  1. 使默认刻度线位置的标签重新出现
  2. 更改刻度线的位置及其标签值

我正在绘制这两个数组:

E=[0.0e+00 9.0e+16 1.8e+17 2.7e+17 3.6e+17 4.5e+17 5.4e+17 6.3e+17 7.2e+17
 8.1e+17 9.0e+17]

m=[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]

使用此 Python 代码:

import numpy as np
import matplotlib.pyplot as plt    
fig=plt.figure()
ax = plt.gca()


plt.plot(m,E,'r',linewidth=4)
plt.xlim([1, 10])
plt.ylim([E[1], max(E)])
plt.yscale('log')
plt.grid(True, which="both")
#ax.yaxis.set_major_locator(plt.LogLocator())
#ax.yaxis.set_major_formatter(plt.ScalarFormatter())
plt.show()

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决方法。所以这就是我以前得到的:

enter image description here

基本上你可以看到很多次要的刻度线,但只有一个专业,而且只有这个专业有标签。所以我删除了这个单一的主要刻度线及其标签,然后在次要刻度线中添加了标签,我得到了我想要的。

有人可以尝试实际指定主要刻度线并删除次要刻度线,但此解决方案适用于我,对其他人来说是一个简单的快速修复。

最终代码以科学计数法显示刻度 amrk 标签。代码和图如下: fig=plt.figure() ax = plt.gca()

plt.plot(m,E,'r',linewidth=4)
plt.xlim([5, 10])
plt.ylim([E[5], max(E)])
plt.yscale('log')
plt.grid(True, which="both")
plt.title('E=m$c^2$')
plt.xlabel('Mass (grams)')
plt.ylabel('Energy (joules)')

#This makes the major tick mark hidde
ax.yaxis.set_major_locator(plt.NullLocator())

#This sets the minor tickmarks labels to display in scientific notation
#ax.yaxis.set_minor_formatter(plt.FormatStrFormatter("%.0E"))

formatter = plt.LogFormatter(labelOnlyBase=False, minor_thresholds=(1,0.5))
ax.yaxis.set_minor_formatter(formatter)
plt.show()

enter image description here