如何分组和绘制条形图 matplotlib 中的值

How to group and plot values a bar chart matplotlib

我正在尝试将所有 group values 变成 monthsplot 这些 bar chart。以下是我迄今为止尝试过的方法:

import pandas as pd

d1 = ({
    'Date' : ['1/7/18','1/7/18','1/8/18','1/8/18','1/9/18'],     
    'Value' : ['Foo','Bar','Foo','Bar','Foo'],           
    })

df1 = pd.DataFrame(data = d1)

df1['Date'] = pd.to_datetime(df1['Date'])
df1.set_index('Date', inplace = True)
df1.resample('1M').count()['Value'].plot(kind = 'bar')

但这只会产生 one barcount5。我希望预期的输出是 3 单独的 barsJulycountAugust2September1

问题在于转换为日期时间,需要设置格式或 dayfirst=True,因为 DD/MM/YY:

df1['Date'] = pd.to_datetime(df1['Date'], format='%d/%m/%y')

或:

df1['Date'] = pd.to_datetime(df1['Date'], dayfirst=True)

如果需要按月份名称绘图,请使用:

df1['Date'] = pd.to_datetime(df1['Date'], format='%d/%m/%y').dt.month_name()
#alternative
#df1['Date'] = pd.to_datetime(df1['Date'], format='%d/%m/%y').dt.strftime('%B')
df1.groupby('Date')['Value'].count().plot(kind = 'bar')

如果需要正确的月份排序:

months = ['January','February','March','April','May','June','July','August',
          'September','October','November','December']

df1['Date'] = pd.Categorical(df1['Date'], categories=months, ordered=True)
df1.groupby('Date')['Value'].count().plot(kind = 'bar')

如果要过滤掉 0 个值:

df1.groupby('Date')['Value'].count().pipe(lambda x: x[x != 0]).plot(kind = 'bar')

感谢@ason​​gtoruin 的另一个想法:

df1['Date'] = pd.to_datetime(df1['Date'], format='%d/%m/%y') 
#if necessary sorting datetimes
#df1 = df1.sort_values('Date')

df1['month_name'] = df1['Date'].dt.month_name()

df1.groupby('Date').agg({'Value': 'count', 'month_name': 'first'})
                   .plot(x='month_name', y='Value', kind='bar')

您的代码工作正常,但您混淆了 day/month 格式

你只需要改变

'Date' : ['1/7/18','1/7/18','1/8/18','1/8/18','1/9/18'], 

'Date' : ['7/1/18','7/1/18','8/1/18','8/1/18','9/1/18'],

另一种解决方案是使用数据透视表 table 按日期分组。

pd.pivot_table(df1, values='Value', index='Date', aggfunc='count').plot(kind='bar')