Plotting a multiple index pivot table

Question:

I loaded already a CSV and did some work on the data. That’s ok. I have the following dataframe:

dataframe

Then, I created a Pivot from the dataframe:

pivot = pd.pivot_table(
data=df,
index=['Category', 'month', 'year'],
values='Amount',
aggfunc='sum',
margins=True)

Now, I have the following dataframe:

new dataframe

Now, I want to plot the following (line chart or bar chart):

  • X: Month
  • Y: Amount

But, I want that for explicit Category like "Business" to see, how the amount changed over the periods.

How can I plot a clear chart with matplotlib?

Asked By: d3rpr0f1

||

Answers:

You can use the below code to build the graphs. I think the stacked bar graphs would be a good way to see the Amount in each month.

Code

## Add AFTER you have created your pivot table
dfg = pivot.reset_index().set_index(['Month', 'Category']).sort_index(level=[0,1])

fig, ax = plt.subplots(figsize=(6,4))

dfg['Amount'].unstack().plot.bar(stacked=True, ax=ax, legend = False)
ax.set_xticklabels(sorted(df.Month.unique()), rotation=0)
ax.set_title('My Graph')
fig.legend(loc="upper right", bbox_to_anchor=(1.1, 0.9))
plt.show()

Stacked Bar graph

enter image description here

Unstacked Bar graph

Change stacked = True to stacked = False to see the bars next to each other, if you are not a fan of stacked bars

enter image description here

Line Graphs
You can also use line graphs, but not my personal preference.
Replace the plot.bar line in above code to

dfg['Amount'].unstack().plot(kind='line', marker='o', ax=ax, legend = False)

enter image description here

Answered By: Redox
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.