python - 如何在matplotlib中设置轴乘数的值?

标签 python matplotlib plot

我必须绘制 (0, 32000) 范围内的值。当我这样做时,我得到以下刻度标签:

0, 5000, 10000, 15000, 20000, 25000, 30000, 35000

但我想要以下内容:

0, 5, 10, 15, 20, 25, 30, 35

使用轴乘数(刻度标签下方的那个小数字)x 10^3。我真的需要 x 10^3

我知道如何强制 matplotlib 使用轴乘数。当我使用以下内容时:

fmt = ScalarFormatter()
fmt.set_powerlimits((-3, 3))
ax.xaxis.set_major_formatter(fmt)

或者这个:

pylab.ticklabel_format(axis='x', style='sci', scilimits=(-3, 3),
                       useOffset=False)

matplotlib 总是返回轴乘数 x 10^4,所以我得到了这些丑陋的刻度标签:

0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5

您会同意乘数 x 10^3 会产生更好的刻度标签。如何设置 10^3 而不是 10^4

This question类似但不涉及为轴乘数设置具体值。

最佳答案

来自available tickers , 两个选项是:

  1. EngFormatter()
  2. FuncFormatter()

使用 EngFormatter 你会得到 SI prefixes ,以及可选的单位,例如通过传递 unit='Hz'

更一般地说,您可以定义自己的格式化程序

scale_factor = 10**3
fmt = mpl.ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_factor))

编辑: 您还可以子类化 ScalarFormatter 并覆盖数量级确定的顺序,如:

class MagnitudeFormatter(matplotlib.ticker.ScalarFormatter):
    def __init__(self, exponent=None):
        super().__init__()
        self._fixed_exponent = exponent

    def _set_order_of_magnitude(self):
        if self._fixed_exponent:
            self.orderOfMagnitude = self._fixed_exponent
        else:
            super()._set_order_of_magnitude()

然后使用 MagnitudeFormatter(3) 作为格式化程序。这样做的好处是它保留了“1e3”轴装饰。

关于python - 如何在matplotlib中设置轴乘数的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28904397/

相关文章:

python - 如何在 python 中交换值?

python - 在 sqlite 3 中的表内创建表(python)

python - matplotlib 的 xkcd() 不工作

svg - 使用 Bokeh 生成高分辨率图形?

r - 在 R 中生成高分辨率树状图

python - 用 nose/fixture/webtest (amidoinitrite) 测试 cherrypy

python - 反转字典

python - Seaborn 多轴图将不同颜色分配给相同/共享类别色调

python - 为什么此代码不保存带有标题的图形?

c++ - CERN 根目录 : Is is possible to plot pairs of x-y data points?