【问题标题】:Cannot format the ticklabel in the twin x axis in matplotlib.pyplot无法格式化 matplotlib.pyplot 中双 x 轴中的刻度标签
【发布时间】:2019-06-07 17:18:47
【问题描述】:

我想绘制一个带有双 x 轴的图形,并将上轴的刻度标签格式化为科学计数法。

import numpy as np
import matplotlib.pyplot as plt

imp1=np.arange(0,2,2/50)
imp1_pdf=np.arange(0,6,6/50)

fig1=plt.figure()
axs1=fig1.add_subplot(111)
axs1.set_xlim(0,2)
axs1.set_ylim(0,6.5)

axs2 = axs1.twiny()

axs1.plot(imp1,imp1_pdf)

new_tick_locations=axs1.get_xticks()

axs2.set_xticks(new_tick_locations)
axs2.set_xticklabels(new_tick_locations/1000)
axs2.axes.ticklabel_format(axis='x',style='sci',scilimits=(0,0))

axs1.grid(b=True, which='major',linestyle='-')
fig1.tight_layout()
fig1.savefig('tickformat.png',dpi=600)

如果没有刻度标签格式,该图如下所示:

但是当我尝试格式化上x轴时,出现如下错误:

AttributeError:此方法仅适用于 ScalarFormatter。

如果我使用另一种方法,那就是使用FormatStrFormatter

from matplotlib.ticker import FormatStrFormatter

axs2.xaxis.set_major_formatter(FormatStrFormatter('%.1e'))

上 x 轴值将与下 x 轴值相同,如下所示:

谁能告诉我如何解决这个问题?

【问题讨论】:

    标签: python-3.x matplotlib formatting


    【解决方案1】:

    问题是您正在尝试修改自定义标签,这些标签只是您定义的字符串(new_tick_locations/1000)。双轴上的实际值与下轴上的值相同。您只是在修改刻度标签。完成工作的一种方法是使用Decimal 以科学格式构造修改后的刻度标签,然后将它们分配给上方的 x 轴。然后,您可以选择要显示的任何因子而不是 1000

    import numpy as np
    from decimal import Decimal
    import matplotlib.pyplot as plt
    
    imp1=np.arange(0,2,2/50)
    imp1_pdf=np.arange(0,6,6/50)
    
    fig1=plt.figure()
    axs1=fig1.add_subplot(111)
    axs1.set_xlim(0,2)
    axs1.set_ylim(0,6.5)
    
    axs2 = axs1.twiny()
    axs1.plot(imp1,imp1_pdf)
    
    new_tick_locations=axs1.get_xticks()
    ticks = ['%.2E' % Decimal(i) for i in (new_tick_locations/1000)] # <-- make new ticks
    axs2.set_xticks(new_tick_locations)
    axs2.set_xticklabels(ticks, rotation = 45) # <-- assign new ticks and rotate them
    
    axs1.grid(b=True, which='major',linestyle='-')
    fig1.tight_layout()
    

    【讨论】:

    • 谢谢。太棒了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多