【问题标题】:Matplotlib: Specify format of floats for tick labelsMatplotlib:指定刻度标签的浮点格式
【发布时间】:2015-05-25 04:11:09
【问题描述】:

我正在尝试在 matplotlib 子图环境中将格式设置为两个十进制数。不幸的是,我不知道如何解决这个任务。

为了防止在 y 轴上使用科学记数法,我使用了 ScalarFormatter(useOffset=False),如下面的 sn-p 所示。我认为我的任务应该通过将更多选项/参数传递给使用的格式化程序来解决。但是,我在 matplotlib 的文档中找不到任何提示。

如何设置两位小数或不设置(两种情况都需要)?很遗憾,我无法提供示例数据。


-- 片段--

f, axarr = plt.subplots(3, sharex=True)

data = conv_air
x = range(0, len(data))

axarr[0].scatter(x, data)
axarr[0].set_ylabel('$T_\mathrm{air,2,2}$', size=FONT_SIZE)
axarr[0].yaxis.set_major_locator(MaxNLocator(5))
axarr[0].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[0].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[0].grid(which='major', alpha=0.5)
axarr[0].grid(which='minor', alpha=0.2)

data = conv_dryer
x = range(0, len(data))

axarr[1].scatter(x, data)
axarr[1].set_ylabel('$T_\mathrm{dryer,2,2}$', size=FONT_SIZE)
axarr[1].yaxis.set_major_locator(MaxNLocator(5))
axarr[1].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[1].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[1].grid(which='major', alpha=0.5)
axarr[1].grid(which='minor', alpha=0.2)

data = conv_lambda
x = range(0, len(data))

axarr[2].scatter(x, data)
axarr[2].set_xlabel('Iterationsschritte', size=FONT_SIZE)
axarr[2].xaxis.set_major_locator(MaxNLocator(integer=True))
axarr[2].set_ylabel('$\lambda$', size=FONT_SIZE)
axarr[2].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[2].yaxis.set_major_locator(MaxNLocator(5))
axarr[2].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[2].grid(which='major', alpha=0.5)
axarr[2].grid(which='minor', alpha=0.2)

【问题讨论】:

    标签: python python-3.x matplotlib scipy


    【解决方案1】:

    查看generalspecifically中的相关文档

    from matplotlib.ticker import FormatStrFormatter
    
    fig, ax = plt.subplots()
    
    ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
    

    【讨论】:

    • 注意:如果您喜欢使用新的.format() 样式说明符,您可以使用linked page 中提到的StrMethodFormatter
    • 我正在使用imshow 进行绘图,但这对我不起作用。我也从this answer 尝试过plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.g')),但无济于事。有什么想法吗?
    • @airdas 如果您遇到问题,请提出一个新问题,提供所有详细信息和问题的minimal reproducible example
    • 即使不单独导入 FormatStrFormatter 也可以工作。它位于pyplotimport matplotlib.pyplot as plt;ax.yaxis.set_major_formatter(plt.FormatStrFormatter('%.2f'))
    • 我不得不使用:ax.get_yaxis().set_major_formatter(FormatStrFormatter('%.2f')) 但效果很好。
    【解决方案2】:

    上面的答案可能是正确的方法,但对我不起作用。

    为我解决它的 hacky 方法如下:

    ax = <whatever your plot is> 
    # get the current labels 
    labels = [item.get_text() for item in ax.get_xticklabels()]
    # Beat them into submission and set them back again
    ax.set_xticklabels([str(round(float(label), 2)) for label in labels])
    # Show the plot, and go home to family 
    plt.show()
    

    【讨论】:

    • 你应该把它放在[str(round(float(label), 2)) for label in labels if label!=''] 否则你会遇到空标签的麻烦。
    【解决方案3】:

    如果你是直接使用matplotlib的pyplot(plt),如果你对新式格式字符串比较熟悉,可以试试这个:

    from matplotlib.ticker import StrMethodFormatter
    plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
    plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places
    

    来自documentation

    类 matplotlib.ticker.StrMethodFormatter(fmt)

    使用新样式的格式字符串(由 str.format() 使用)来格式化 打勾。

    用于值的字段必须标记为 x 并且用于的字段 该位置必须标记为 pos。

    【讨论】:

      【解决方案4】:

      在 matplotlib 3.1 中,你也可以使用ticklabel_format。为了防止没有偏移的科学记数法:

      plt.gca().ticklabel_format(axis='both', style='plain', useOffset=False)
      

      【讨论】:

        【解决方案5】:

        使用 lambda 函数格式化标签

        使用不同的 y 标记 3 倍相同的图

        小例子

        import numpy as np
        import matplotlib as mpl
        import matplotlib.pylab as plt
        from matplotlib.ticker import FormatStrFormatter
        
        fig, axs = mpl.pylab.subplots(1, 3)
        
        xs = np.arange(10)
        ys = 1 + xs ** 2 * 1e-3
        
        axs[0].set_title('default y-labeling')
        axs[0].scatter(xs, ys)
        axs[1].set_title('custom y-labeling')
        axs[1].scatter(xs, ys)
        axs[2].set_title('x, pos arguments')
        axs[2].scatter(xs, ys)
        
        
        fmt = lambda x, pos: '1+ {:.0f}e-3'.format((x-1)*1e3, pos)
        axs[1].yaxis.set_major_formatter(mpl.ticker.FuncFormatter(fmt))
        
        fmt = lambda x, pos: 'x={:f}\npos={:f}'.format(x, pos)
        axs[2].yaxis.set_major_formatter(mpl.ticker.FuncFormatter(fmt))
        

        当然,您也可以使用“真实”函数来代替 lambda。 https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-formatters.html

        【讨论】:

          猜你喜欢
          • 2014-03-22
          • 2016-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多