将Matplotlib偏移符号从科学更改为普通

时间:2018-12-21 02:19:15

标签: python matplotlib offset scientific-notation

我想将绘图中y轴偏移的格式设置为非科学计数法,但是我找不到执行此操作的设置。其他问题及其解决方案描述了如何完全消除偏移或将y标记设置为科学/普通符号;我尚未找到设置偏移量本身的符号的答案。

我已经尝试过使用这两个选项,但是我认为它们用于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

2 个答案:

答案 0 :(得分:2)

一种方法是禁用偏移文本本身,并在其中添加自定义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()

wordpress development

答案 1 :(得分:2)

您可以继承默认的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()

https://github.com/Azure-Samples/active-directory-dotnetcore-console-up-v2