繁体   English   中英

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

[英]How to group and plot values a bar chart matplotlib

我试图将所有values groupmonths并将其plotbar 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 bar count5 one bar 我希望预期的输出是3单独的bars 一个count2July2August ,和1September

问题是转换为日期时间,需要设置格式或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')

G

如果需要正确的月份订购:

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')

G1

如果想过滤掉0值:

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

G2

感谢@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')

你的代码运行得很好,但你把日/月格式搞混了

你需要做的就是改变

'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'],

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM