首页 文章

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

提问于
浏览
1

我试图 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 单独 bars . count2July2August1September .

3 回答

  • 4

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

    感谢@asongtoruin的另一个想法:

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

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

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

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

    你需要做的就是改变

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

相关问题