首页 > 解决方案 > 带有按计数排序的条形返回的熊猫图?

问题描述

我正在使用以下代码创建一个图表,显示我的 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 排序?

标签: pythonpandasplotbar-chart

解决方案


如果我理解正确,您只需要按报告日期对数据框进行排序,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')

在此处输入图像描述


推荐阅读