Issue
Hi to all the experts,
I'm new to Python and Data Science and actually I'm learning with a real world example to get into Data Science.
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.
Whats the best way, to plot a clear, beautiful chart with matplotlib?
Thanks in Advance.
Many Greetings Leon
Solution
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)
Answered By - Redox
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.