【问题标题】:Suppress scientific notation offsetText in matplotlib抑制 matplotlib 中的科学记数法 offsetText
【发布时间】:2021-07-05 15:44:17
【问题描述】:

我在 y 轴上有一个带有科学记数法的图。我想专门抑制偏移量/ sci 符号文本,即轴顶部的1e6

与简单地关闭科学记数法是一回事,这会使轴刻度标签25000002000000等;我想按原样保留刻度标签,但只需隐藏顶部的小1e6(因为轴标签已经显示“百万/年”)。有没有简单或“正确”的方法来做到这一点?

(我能想到的显而易见的 hack 是将所有正在绘制的数据简单地除以 1e6,但这并不容易概括,我想知道是否有一种解决方案不是 hack。)

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    为避免文本与 1e7 或更高的公共乘数出错,最好将值除以 100 万。一个方便的方法是使用刻度格式化程序:

    import matplotlib.pyplot as plt
    
    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4))
    ax1.plot([0, 1.5e6])
    ax1.yaxis.set_major_formatter(lambda x, pos: f'{x / 1e6:.1f}')
    ax1.set_ylabel('incidents (millions/year)')
    ax2.plot([0, 1.5e7])
    ax2.yaxis.set_major_formatter(lambda x, pos: f'{x / 1e6:.1f}')
    ax2.set_ylabel('incidents (millions/year)')
    plt.tight_layout()
    plt.show()
    

    请注意,在较旧的 matplotlib 版本中,您不能直接设置格式化函数,并且需要显式的 FuncFormatter

    【讨论】:

      猜你喜欢
      • 2020-05-31
      • 2013-07-18
      • 2017-03-13
      • 2021-06-17
      • 2016-08-15
      • 2021-09-30
      • 2018-03-25
      • 1970-01-01
      相关资源
      最近更新 更多