【问题标题】:Pandas Plot with Bar Returns Sorted by Counts?带有按计数排序的条形返回的熊猫图?
【发布时间】:2020-01-21 22:44:47
【问题描述】:

我正在使用以下代码创建一个图表,显示我的 df 中出现了多少空值,按日期列排序:

df[df['Gas'].isnull()]['ReportDate_Time'].sort_values().value_counts().plot()

这是它返回的图,没问题,但我宁愿使用条形图。但是,如果我将 'bar' 参数传递给 plot 方法,我会自动按总计数排序而不是按 ReportDate_Time 排序,这正是我最初想要的:

df[df['Gas'].isnull()]['ReportDate_Time'].sort_values().value_counts().plot('bar')

如何使用条形图并同时按 ReportDate_Time 排序?

【问题讨论】:

  • sort_values() 之后使用value_counts() 基本上会覆盖排序。在致电plot 之前,请确保按照您的意愿对数据进行排序。
  • 您好,没有您的数据很难尝试,但是...您是否尝试过反转 df[df['Gas'].isnull()]['ReportDate_Time'].value_counts()。 sort_values.plot('bar')

标签: python pandas plot bar-chart


【解决方案1】:

如果我理解正确,您只需按报告日期对数据框进行排序,sort_values('Reportdate')

请参阅下面的示例。

dates = pd.date_range(pd.to_datetime('2020-01-21'), pd.to_datetime('2020-02-01'),freq='D')
vals = np.random.randint(0,500,size=len(dates))
df = pd.DataFrame({'ReportDate' : dates, 'count' : vals})
df.sort_values('count',inplace=True)
df.reset_index(drop=True,inplace=True)

print(df)
   ReportDate  count
0  2020-01-28    135
1  2020-01-30    194
2  2020-01-21    238
3  2020-01-29    316
4  2020-01-31    325
5  2020-01-26    408
6  2020-01-23    450
7  2020-01-22    451
8  2020-01-25    452
9  2020-01-24    454
10 2020-02-01    463
11 2020-01-27    489



df.set_index('ReportDate').plot(kind='bar')

还有排序:

df.sort_values('ReportDate',ascending=True).set_index('ReportDate').plot(kind='bar')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-31
    • 2018-02-27
    • 2019-04-13
    • 2017-04-01
    • 2021-03-28
    • 1970-01-01
    • 2021-08-28
    • 2015-06-28
    相关资源
    最近更新 更多