【问题标题】:Setting Order of Columns with matplotlib bar chart使用 matplotlib 条形图设置列顺序
【发布时间】:2017-01-01 07:21:55
【问题描述】:

我用以下代码制作了一个条形图:

Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index')
df.plot(kind = 'bar')

它会生成以下条形图:

我想更改列的列出顺序。我尝试了一些似乎不起作用的不同方法。我正在使用的 DataFrame 如下所示:

我正在创建图中数据框中最后一列的条形图。将不胜感激创建条形图的替代方法的任何方向或想法,以使我能够更改轴的顺序。因为它存在,所以很难解释。

【问题讨论】:

    标签: python pandas numpy matplotlib bar-chart


    【解决方案1】:

    我建议您将TEMPBIN_CON 一分为二:LOWER_TEMPHIGHER_TEMP。然后,您使用以下列对 DataFrame 进行排序:

    sorted = df.sort_values(by=['LOWER_TEMP', 'HIGHER_TEMP'])
    

    然后你按照你已经完成的那样做情节:

    sorted.plot(kind='bar')
    

    【讨论】:

      【解决方案2】:

      我认为您可以将value_countssort_index 和最后一个Series.plot.bar 一起使用:

      weatherDFConcat['TEMPBIN_CON'].value_counts().sort_index().plot.bar()
      

      或者,如果您想使用您的解决方案:

      Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
      df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index').sort_index()
      df.plot(kind = 'bar')
      

      示例:

      import matplotlib.pyplot as plt
      
      weatherDFConcat = pd.DataFrame({'TEMPBIN_CON':['30 degrees or more', '-15 to -18 degrees', '-3 to 0 degrees', '15 to 18 degrees', '-15 to -18 degrees'
      ]})
      print (weatherDFConcat)
                TEMPBIN_CON
      0  30 degrees or more
      1  -15 to -18 degrees
      2     -3 to 0 degrees
      3    15 to 18 degrees
      4  -15 to -18 degrees
      
      weatherDFConcat['TEMPBIN_CON'].value_counts().sort_index().plot.bar()
      plt.show()
      

      【讨论】:

      • 它是如何工作的?还是您需要一些自定义订购?
      • 添加 .sort_index() 对我的数据效果很好 - 谢谢!
      猜你喜欢
      • 2013-12-31
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      相关资源
      最近更新 更多