我想将绘图中 y 轴偏移的格式设置为非科学记数法,但找不到执行此操作的设置。其他问题及其解决方案描述了如何完全删除偏移量,或将 y-ticks 设置为科学/简单表示法;我还没有找到设置偏移量表示法本身的答案。
我已经尝试过使用这两个选项,但我认为它们适用于 y 刻度,而不是偏移量:
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
和
ax.get_yaxis().get_major_formatter().set_scientific(False)
所以,实际结果是+6.3781e3
,当我想要+6378.1
有什么办法吗?
编辑:添加示例代码和图形:
#!/usr/bin/env python
from matplotlib import pyplot as plt
from matplotlib import ticker
plt.rcParams['font.family'] = 'monospace'
import random
Date = range(10)
R = [6373.1+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
plt.show()
最佳答案
您可以子类化默认的 ScalarFormatter
并替换 get_offset
方法,这样它就可以简单地按原样返回偏移量。请注意,如果您想使其与乘法“偏移量”兼容,则需要调整此解决方案(目前它只打印一条警告)。
from matplotlib import pyplot as plt
import matplotlib.ticker
import random
class PlainOffsetScalarFormatter(matplotlib.ticker.ScalarFormatter):
def get_offset(self):
if len(self.locs) == 0:
return ''
if self.orderOfMagnitude:
print("Your plot will likely be labelled incorrectly")
return self.offset
Date = range(10)
R = [6373.1+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.yaxis.set_major_formatter(PlainOffsetScalarFormatter())
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
plt.show()
关于python - 将 matplotlib 偏移表示法从科学更改为简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53878397/