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

标签 python matplotlib offset scientific-notation

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

相关文章:

python - 在幕后,子类化用户和创建一对一字段之间有什么区别?

docker - 如何在 ipython 中渲染 matplotlib 图

byte - Libgdx Pixmap 和 getFrameBufferPixels

excel - 拉取从单个单元格溢出的每第 n 组行

python - 这是检测 cx_oracle 是否安装了 unicode 或非 unicode 版本的首选方法吗?

python - 独立的 python 安装,包含可执行工具(pip、orbited 等)

macos - MacoS 上 "Matplotlib is building the font cache using fc-list. This may take a moment."的问题

python - Matplotlib:imshow 中的 set_data 对绘图没有影响

android - 平板电脑上的 Mapview : How can I center the map with an offset?

python - 添加新文本到 Sklearn TFIDIF Vectorizer (Python)