Reputation: 4944
I'm using matplotlib
and python 3.7 to plot an expense report divided into categories.
The goal would be to plot a multi-bar graph to compare data year over year.
I found a way to do this using a line graph, but not with the more appropriate bar graph because the bar just overlap each other.
This is the code used to generate this graph:
data = {'category 1': 120.50,
'category 2': 135.59,
'category 3': 130.71,
'category 4': 150.71}
group_data = list(data.values())
group_names = list(data.keys())
fig, axs = plt.subplots(2)
axs[0].plot(group_names, group_data, label="2020")
axs[0].plot(group_names, [v * 1.1 for v in group_data], label="2019")
axs[1].bar(group_names, group_data, label="2020")
axs[1].bar(group_names, [v * 1.1 for v in group_data], label="2019")
axs[0].legend()
Looked at the official doc (https://matplotlib.org/3.2.1/gallery/lines_bars_and_markers/categorical_variables.html) but didn't find a proper solution.
Upvotes: 1
Views: 1983
Reputation: 150825
You can consider Pandas for easy plot function:
import pandas as pd
# 2020 data
df = pd.DataFrame({'2020':data})
# 2019 data
df['2019'] = df['2020'] * 1.1
# plot bar
df.plot.bar()
Output:
Upvotes: 1
Reputation: 39072
You can use the parameter zorder
to decide the stack order of your bars. The bars with smaller height should have a higher z-order so that they appear at the front.
axs[1].bar(group_names, group_data, label="2020", zorder=1)
axs[1].bar(group_names, [v * 1.1 for v in group_data], label="2019", zorder=0)
Upvotes: 0