Stacked histogram by decade from dataframe

Viewed 171

I have a dataframe that contains the date of a snowstorm and also a ranking of said snowstorm ranging from 1950-2019. I want to create a stacked histogram where the x-axis is decade and the y-axis is counts of snowstorm by category.

An example of what I am trying to create is listed below. Snowstorm climatology

I am having trouble understanding how exactly to aggregate the data in such a fashion that would allow me to plot something like I shared.

For example, here is a snippet of the 1950s dataframe:

    Start       End         Category    Year    count
    1959-03-12  1959-03-14  2           1950    13
    1958-03-18  1958-03-23  3           1950    6
    1958-02-12  1958-02-18  3           1950    6
    1957-12-03  1957-12-05  1           1950    32
    1956-03-18  1956-03-20  1           1950    32

I have all of the counts for each category, but how do I turn that into data that is plottable on stacked histogram?

1 Answers

Aggregate you data first, then plot with the argument stacked=True

pivot_table

df.pivot_table('count', 'Year', 'Category', 'sum').plot.bar(stacked=True)

groupby

df.groupby(['Year', 'Category'])['count'].sum().unstack().plot.bar(stacked=True)

enter image description here

Keep in mind that you can change the aggregation to something else.

df.pivot_table('count', 'Year', 'Category', 'first').plot.bar(stacked=True)
df.groupby(['Year', 'Category'])['count'].first().unstack().plot.bar(stacked=True)

Also, you can drop duplicates prior.

(
    df.drop_duplicates(['Year', 'Category'])
      .pivot_table('count', 'Year', 'Category')
      .plot.bar(stacked=True)
)
Related