【问题标题】:Change offset in scientific axis label format更改科学轴标签格式的偏移量
【发布时间】:2019-07-27 19:49:37
【问题描述】:

我正在使用以下刻度标签格式:

ax.ticklabel_format(axis="y", style="sci", useOffset=True, scilimits=(0,0))

我的问题是标签是浮动的。所以最低值可能是 0.5(乘以偏移量),最高值可能是 2.0(乘以偏移量)。 在这种情况下,我希望各自的标签为 5 和 20,并将偏移量更改 10 倍。

我是否必须手动设置刻度标签和偏移文本,或者是否有一个简单的命令可以做到这一点?我无法想象像这样自定义刻度标签不是内置的,但到目前为止我在搜索中找不到任何东西。

【问题讨论】:

  • 它不是内置的。我也不确定所需的算法。您是否介意手动设置指数(比如应该是 10^5,手动输入 5),还是还需要根据数据范围计算指数?
  • 如果我必须手动设置标签和偏移文本,计算正确的指数不是问题。我只是认为将所有标签和偏移文本缩放一个常数因子会更简单。
  • 如果您想手动输入指数,here 将是一个解决方案。
  • 这看起来很有希望。一旦我让它工作(或不工作;-)),我将发布更新。无论如何,感谢您迄今为止的帮助。

标签: python matplotlib axis-labels


【解决方案1】:

感谢 ImportanceOfBeingErnest 的解决方案。 解决方案基于this

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import matplotlib
from matplotlib import pyplot as plt
from matplotlib.ticker import ScalarFormatter
import numpy as np




class ModifiedFormatter(ScalarFormatter):
    def __init__(self, order, fformat="%.0f", offset=True, mathText=True):
        self.oom = order
        self.fformat = fformat
        ScalarFormatter.__init__(self,useOffset=offset,useMathText=mathText)

    def _set_orderOfMagnitude(self, nothing):
        self.orderOfMagnitude = self.oom

    def _set_format(self, vmin, vmax):
        self.format = self.fformat
        if self.useMathText:
            self.format = "$%s$" % matplotlib.ticker._mathdefault(self.format)






def test():

    fig, ax = plt.subplots(nrows=1,ncols=1,figsize=(15,8))

    xv = np.random.normal(0,1,100000)

    xmin, xmax = -3, 3
    nbins = 100

    ax.hist(xv, bins=nbins, range=(xmin,xmax), histtype="step", color="blue")



    # determine the new order of major formatter
    # since I want 2 digits accuracy, new_order = old_order - 1
    ymin, ymax = ax.get_ylim()
    order = int("{:1.8e}".format(ymax).split("e")[1])-1
    ax.yaxis.set_major_formatter(ModifiedFormatter(order))
    ax.ticklabel_format(axis="y", style="sci", useOffset=True, scilimits=(0,0))

    ax.tick_params(axis="both", labelsize=20)
    ax.yaxis.get_offset_text().set_fontsize(18) 


    ax.set_xlabel("x axis label", fontsize=20)
    ax.set_ylabel("y axis label", fontsize=20)



    plt.subplots_adjust(top=0.9,bottom=0.1,left=0.065,right=0.99,hspace=0.2,wspace=0.2)

    plt.show()



if __name__ == '__main__':
    test()

之前:

之后:

【讨论】:

    猜你喜欢
    • 2014-08-01
    • 2019-11-15
    • 1970-01-01
    • 2021-09-23
    • 2022-01-22
    • 2011-06-26
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多