简体   繁体   中英

plotting a grouped bar chart with bins

I have a dataframe similar to like this:

Create Date    count1 count2 count3 count4
2018-01          12     21     12    123
2018-02          11     25     12    145
2018-08          12     26     12    145
2019-03          13     28     12    334
2019-06          15     22     12    345
2019-07          16     25     12    165
2020-01          12     25     12    178
2020-02          12     23     12    178
2020-03          12     26     12    187
2021-01          11     28     12    146
2021-02          12     29     12    123
2021-03          11     22     12    189
2022-01          17     21     12    167
2022-02          18     23     12    166
2022-03          19     23     12    123

I want a grouped bar chart where x axis is a year. For example 2018, 2019, 2020, 2021, 2022. In each of those year I want the sum of a column in that year as 1 bar and so on.

What I tried

    df_combined.plot.bar(logy=True)
    plt.xticks(rotation=0)
    plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
    plt.show()

What I am getting is a crowded bar chart like this在此处输入图像描述

You need to make a pandas.DatetimeIndex by using groupBy.sum before calling plot :

(
  df_combined
        .assign(year= pd.DatetimeIndex(df_combined["Create Date"]).year)
        .groupby("year").sum(numeric_only=True) #as_index=True by default
        .plot(kind="bar", logy=True)
)

plt.xticks(rotation=0)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
plt.show();

Output ( plot ):

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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