【问题标题】:How do you set the formating of axis labels via secondary_yaxis?如何通过 secondary_yaxis 设置轴标签的格式?
【发布时间】:2021-11-24 13:52:56
【问题描述】:

如何通过secondary_yaxis设置轴标签的格式?

在下面的示例中,我希望更多地控制第二个轴标签(例如 format='%g')。我认为应该可以将ticklabel_formatformat 之类的东西作为kwargs 传递,但似乎都不起作用(两者都提高AttributeError: 'SecondaryAxis' object has no property ...)。

    import matplotlib.pyplot as plt
    import numpy as np

    # Conversion functions to and from km and hPa
    def km2hPa(input):
        return np.exp( input / -7.6 ) * 1013.

    def hPa2Km(input):
        return -7.6 * np.log( input  / 1013. )

    # Fake data to plot
    Y = np.linspace(1000, 100, 100)
    X = np.array( [i**2 for i in np.linspace(0, 10, len(Y)) ] )

    # Plot up data with both primary (hPa) and secondary axis (km)
    plt.close('all')
    kwargs = {} # Add a format specifier here?
    fig, ax = plt.subplots()
    plt.plot(X, Y)
    ax.set_ylabel('Pressure altitude (hPa)')
    ax.invert_yaxis()
    secax = ax.secondary_yaxis('right', functions=(hPa2Km, km2hPa), **kwargs)
    secax.set_ylabel('Altitude (km)')
    plt.show()

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:
    import matplotlib.ticker as ticker
    
    secax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:g}"))
    

    secax.yaxis.set_major_formatter(ticker.FormatStrFormatter("%g"))
    

    【讨论】:

      猜你喜欢
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多