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:
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:
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?
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
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
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)
I loaded already a CSV and did some work on the data. That’s ok. I have the following 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:
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?
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
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
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)