【问题标题】:Pyplot: using percentage on x axisPyplot:在x轴上使用百分比
【发布时间】:2014-12-05 07:47:24
【问题描述】:

我有一个基于简单数字列表的折线图。默认情况下,x 轴只是绘制的每个值的增量 1。我想成为一个百分比,但不知道如何。因此,x 轴不是从 0 到 5,而是从 0% 到 100%(但保持合理间隔的刻度线。下面的代码。谢谢!

from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid.axislines import Subplot

data=[8,12,15,17,18,18.5]
fig=plt.figure(1,(7,4))
ax=Subplot(fig,111)
fig.add_subplot(ax)
plt.plot(data)

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    下面的代码将为您提供一个基于百分比的简化 x 轴,它假定您的每个值都是 0% 到 100% 之间的空格。

    它创建了一个perc 数组,其中包含可用于绘图的均匀分布的百分比。然后它会调整 x 轴的格式,使其包含一个使用 matplotlib.ticker.FormatStrFormatter 的百分号。不幸的是,这使用了旧样式的字符串格式,而不是新样式,旧样式文档可以在 here 找到。

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.ticker as mtick
    
    data = [8,12,15,17,18,18.5]
    perc = np.linspace(0,100,len(data))
    
    fig = plt.figure(1, (7,4))
    ax = fig.add_subplot(1,1,1)
    
    ax.plot(perc, data)
    
    fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
    xticks = mtick.FormatStrFormatter(fmt)
    ax.xaxis.set_major_formatter(xticks)
    
    plt.show()
    

    【讨论】:

    • 旧的格式没有错。它仍然是两者中更具互操作性的(例如,参见日志模块)。
    • 如果原始值已经像 0.5 会是什么格式?我想把这个变成 50%。
    • 另一种可能的解决方案是使用mtick.FuncFormatter("{:.0%}".format),它使用了我认为更具可读性和灵活性的新型格式字符串。
    【解决方案2】:

    这晚了几个月,但我用 matplotlib 创建了PR#6251 以添加一个新的PercentFormatter 类。使用该类,您可以执行以下操作来设置轴:

    import matplotlib.ticker as mtick
    
    # Actual plotting code omitted
    
    ax.xaxis.set_major_formatter(mtick.PercentFormatter(5.0))
    

    这将在 0% 到 100% 的范围内显示 0 到 5 的值。格式化程序在概念上与@Ffisegydd 建议的做法相似,只是它可以考虑任意现有的刻度。

    PercentFormatter() 接受三个参数,maxdecimalssymbolmax 允许您设置对应于轴上 100% 的值(在您的示例中,5)。

    另外两个参数可以设置小数点后的位数和符号。它们分别默认为None'%'decimals=None 将根据您显示的轴数自动设置小数位数。

    请注意,如果您刚刚绘制数据,此格式化程序将使用通常会生成的任何刻度。除了输出到刻度线的字符串之外,它不会修改任何内容。

    更新

    PercentFormatter 在 2.1.0 版中被 Matplotlib 接受。

    【讨论】:

      【解决方案3】:

      今天已经很晚了,但我写了这个并认为它可能有用:

      def transformColToPercents(x, rnd, navalue):
          
          # Returns a pandas series that can be put in a new dataframe column, where all values are scaled from 0-100%
          # rnd = round(x)
          # navalue = Nan== this
          
          hv = x.max(axis=0)
          lv = x.min(axis=0)
          
          pp = pd.Series(((x-lv)*100)/(hv-lv)).round(rnd)                        
          
          return pp.fillna(navalue)  
      
      
      df['new column'] = transformColToPercents(df['a'], 2, 0)
      

      【讨论】:

      • 将近 7 年前只是有点晚了。xD
      猜你喜欢
      • 1970-01-01
      • 2015-05-17
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2018-02-25
      • 2020-10-17
      相关资源
      最近更新 更多