【问题标题】:how to force matplotlib to display only whole numbers on the Y axis [duplicate]如何强制matplotlib在Y轴上仅显示整数[重复]
【发布时间】:2015-02-14 07:09:27
【问题描述】:

我正在可视化的数据只有在它是整数时才有意义。

即就我正在分析的信息的上下文而言,0.2 的记录没有意义。

如何强制 matplotlib 在 Y 轴上仅使用整数。 IE。 1、100、5 等?不是 0.1、0.2 等

for a in account_list:
    f = plt.figure()
    f.set_figheight(20)
    f.set_figwidth(20)
    f.sharex = True
    f.sharey=True

    left  = 0.125  # the left side of the subplots of the figure
    right = 0.9    # the right side of the subplots of the figure
    bottom = 0.1   # the bottom of the subplots of the figure
    top = 0.9      # the top of the subplots of the figure
    wspace = 0.2   # the amount of width reserved for blank space between subplots
    hspace = .8  # the amount of height reserved for white space between subplots
    subplots_adjust(left=left, right=right, bottom=bottom, top=top, wspace=wspace, hspace=hspace)

    count = 1
    for h in headings:
        sorted_data[sorted_data.account == a].ix[0:,['month_date',h]].plot(ax=f.add_subplot(7,3,count),legend=True,subplots=True,x='month_date',y=h)

        #set bottom Y axis limit to 0 and change number format to 1 dec place.
        axis_data = f.gca()
        axis_data.set_ylim(bottom=0.)
        from matplotlib.ticker import FormatStrFormatter
        axis_data.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))

        #This was meant to set Y axis to integer???
        y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
        axis_data.yaxis.set_major_formatter(y_formatter)

        import matplotlib.patches as mpatches

        legend_name = mpatches.Patch(color='none', label=h)
        plt.xlabel("")
        ppl.legend(handles=[legend_name],bbox_to_anchor=(0.,1.2,1.0,.10), loc="center",ncol=2, mode="expand", borderaxespad=0.)
        count = count + 1
        savefig(a + '.png', bbox_inches='tight')

【问题讨论】:

    标签: python visualization


    【解决方案1】:

    最灵活的方法是将integer=True 指定为默认的刻度定位器(MaxNLocator)做类似这样的事情:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    
    fig, ax = plt.subplots()
    
    # Be sure to only pick integer tick locations.
    for axis in [ax.xaxis, ax.yaxis]:
        axis.set_major_locator(ticker.MaxNLocator(integer=True))
    
    # Plot anything (note the non-integer min-max values)...
    x = np.linspace(-0.1, np.pi, 100)
    ax.plot(0.5 * x, 22.8 * np.cos(3 * x), color='black')
    
    # Just for appearance's sake
    ax.margins(0.05)
    ax.axis('tight')
    fig.tight_layout()
    
    plt.show()
    

    或者,您可以按照 Marcin 和 Joel 的建议手动设置刻度位置/标签(或使用 MultipleLocator)。这样做的缺点是您需要计算出有意义的刻度位置,而不是让 matplotlib 根据轴限制选择一个合理的整数刻度间隔。

    【讨论】:

    • 谢谢@Joe Kington -- 你能帮我吗我觉得我用错了:我收到错误:axis_data.set_major_locator(ticker.MaxNLocator(integer=True)) 'AxesSubplot' 对象没有属性'set_major_locator'。这是因为我试图将 SUBPLOTS 的 Y 轴设置为整数吗?
    • @yoshiserry - 我猜你想打电话给ax.set_major_locator而不是ax.yaxis.set_major_locator。刻度定位器是Axis(即x/y 轴)的属性,而不是Axes(即绘图)的属性。试试axis_data.yaxis.set_major_locator(或xaxis,视情况而定)。
    【解决方案2】:

    如果只是要更改的 yaxis,一个简单的方法是确定您想要的刻度:

    tickpos = [0,1,4,6]
    
    py.yticks(tickpos,tickpos)
    

    将刻度放在 0、1、4 和 6 处。更一般地

    py.yticks([0,1,2,3], ['zero', 1, 'two', 3.0])
    

    将第二个列表的标签放在第一个列表中的位置。如果标签是 yvalue,最好使用 py.yticks(tickpos,tickpos) 版本,以确保无论何时更改刻度的位置,标签都会发生相同的变化。

    不过,更一般地说,Kington 的回答会让你告诉 pylab y 轴的整数,但让它选择刻度的位置。

    【讨论】:

      【解决方案3】:

      另一种强制整数刻度的方法是使用pyplot.locator_params

      使用与已接受答案中几乎相同的示例:

      import numpy as np
      import matplotlib.pyplot as plt
      
      # Plot anything (note the non-integer min-max values)...
      x = np.linspace(-0.1, np.pi, 100)
      plt.plot(0.5 * x, 22.8 * np.cos(3 * x), color='black')
      
      # use axis={'both', 'x', 'y'} to choose axis
      plt.locator_params(axis="both", integer=True, tight=True)
      
      # Just for appearance's sake
      plt.margins(0.05)
      plt.tight_layout()
      
      plt.show()
      

      【讨论】:

      • 又好又干净! plt.locator_params(axis="x", integer=True)
      【解决方案4】:

      您可以按如下方式修改刻度标签/数字。这只是示例,因为您没有提供任何您拥有的代码,所以不确定它是否适用于您。

      import matplotlib.pyplot as plt
      
      fig, ax = plt.subplots()
      
      fig.canvas.draw()
      
      # just the original labels/numbers and modify them, e.g. multiply by 100
      # and define new format for them.
      labels = ["{:0.0f}".format(float(item.get_text())*100) 
                      for item in ax.get_xticklabels()]
      
      
      ax.set_xticklabels(labels)
      
      plt.show()
      

      不修改x轴:

      修改后:

      【讨论】:

        猜你喜欢
        • 2012-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-25
        • 1970-01-01
        • 2021-08-10
        • 1970-01-01
        • 2021-12-30
        相关资源
        最近更新 更多