[英]Change matplotlib offset notation from scientific to plain
我想在我的绘图中将y轴偏移的格式设置为非科学记数法,但我找不到设置来执行此操作。 其他问题及其解决方案描述了如何完全消除偏移量,或者将y-ticks设置为科学/普通符号; 我没有找到设置偏移本身的符号的答案。
我已经尝试过使用这两个选项,但我认为它们是针对y-ticks而不是偏移量:
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
和
ax.get_yaxis().get_major_formatter().set_scientific(False)
所以,当我想要+6378.1
时,实际结果是+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()
一种方法是禁用偏移文本本身并在其中添加自定义ax.text
,如下所示
from matplotlib import pyplot as plt
import random
plt.rcParams['font.family'] = 'monospace'
offset = 6378.1
Date = range(10)
R = [offset+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=offset)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
ax.yaxis.offsetText.set_visible(False)
ax.text(x = 0.0, y = 1.01, s = str(offset), transform=ax.transAxes)
plt.show()
您可以ScalarFormatter
默认的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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.