【问题标题】:Sort bar plot by month ascending按月升序对条形图进行排序
【发布时间】:2021-08-11 07:20:31
【问题描述】:

感谢您的帮助!

我在 Python 和 Matplotlib 中有 concat 3 个数据帧,每个数据帧的列“日期”为 datetime64,例如“2020-03-05”。当我绘制它们时,我无法获得月份/是的从左到右升序”

        
    vc = pd.concat([df1, df2, df3])
    vc['month_year'] = vc['date'].dt.strftime('%b %Y')
    vc['month_year'].value_counts().plot(kind='bar')

谢谢!

Graph

【问题讨论】:

  • 如果我在计算频率后按升序排序会发生什么?
  • 你能添加你的输出吗?您可以尝试将标志ascending=True 添加到value_counts() 方法中:vacancies['MONTH_YEAR'].value_counts(ascending=True).plot(kind='bar')
  • 如果不行试试:或者改成这个:vacancies['MONTH_YEAR'].value_counts(ascending=True).sort_values(by='MONTH_YEAR',ascending = True).plot(kind='bar')
  • @EitanRosati 添加:ascending=True 只是颠倒当前顺序,但仍不按月/年从左到右排序 .sort_values(by='MONTH_YEAR',ascending = True) 得到错误"TypeError: sort_values() 得到了一个意外的关键字参数 'by' 但谢谢!

标签: python matplotlib monthcalendar


【解决方案1】:

要按升序显示月份,您可以这样做:

  1. strftime()return ndarray 所以它的排序与日期时间对象不同。而不是使用strftime() 将其转换为周期对象:dt.to_period('M')
  2. value_counts() 之后的值按计数排序,month_year 成为此 DataFrame 的索引。所以你只需要在绘图之前对索引进行排序。

更改后的代码:

vc = pd.concat([df1, df2, df3])
vc['month_year'] = vc['date'].dt.to_period('M')
vc_graph = vc['month_year'].value_counts().sort_index(ascending=True)
vc_graph.index = (vc_graph.index).strftime('%b %Y')
vc_graph.plot(kind='bar')

输出将如下所示:

【讨论】:

  • 谢谢,但我想保持格式为“2019 年 1 月”。这可能吗?
  • 当然,它添加了更多代码。我在答案中添加了它
猜你喜欢
  • 2017-12-06
  • 2018-04-18
  • 1970-01-01
  • 2021-07-06
  • 1970-01-01
  • 2014-10-02
  • 1970-01-01
  • 2021-10-10
  • 2013-05-30
相关资源
最近更新 更多