gpt4 book ai didi

python - 将 matplotlib 偏移表示法从科学更改为简单

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:20 35 4
gpt4 key购买 nike

我想将绘图中 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()

Example image with data centered around the offset I want

最佳答案

您可以子类化默认的 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()

enter image description here

关于python - 将 matplotlib 偏移表示法从科学更改为简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53878397/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com