1

I have two Dictionaries:

A = {2018: 23, 2019: 30}
B = {2018: 26, 2019:35} 

Now I want to plot trend for 2018/2019 for A and B. however when plotting the bar graph, I am getting the following result. The years are expanding to fill space and b is hiding out A completely. Please suggest how to plot the graph.

enter image description here

The original data have Average marks for maths, science, and total which I want to plot on the same graph (bar graph) for two years to show the trend.

1 Answer 1

3

You can align the bars of a bar graph by their left of right edge (pass a negative width to align using the right edge) - in this way you can get side-by-side bars. Alternatively you can stack the bars.

Here is the code with the output:

import matplotlib.pyplot as plt

A = {2018: 23, 2019:30}
B = {2018: 26, 2019:35}

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(12,5))

ax1.bar(A.keys(), A.values(), width=0.2, align='edge', label='A')
ax1.bar(B.keys(), B.values(), width=-0.2, align='edge', label='B')
ax1.set_xticks([2018, 2019])
ax1.set_xlabel('YEAR')
ax1.legend()

ax2.bar(A.keys(), A.values(), width=0.4, align='center', label='A')
ax2.bar(B.keys(), B.values(), bottom=[A[i] for i in B.keys()], width=0.4, align='center', label='B')
ax2.set_xticks([2018, 2019])
ax2.set_xlabel('YEAR')
ax2.legend()

fig.show()

enter image description here

EDIT: If you start to deal with more data it makes sense to use a package that can handle data more easily. Pandas is a great package that will do this for you.

Here is an example with 4 sets of time-series data:

import matplotlib.pyplot as plt
import pandas as pd

A = {2018: 23, 2019:30}
B = {2018: 26, 2019:35}
C = {2018: 30, 2019:40}
D = {2018: 20, 2019:50}

df = pd.DataFrame([A,B,C,D], index=['A','B','C','D']).transpose()

fig, ax= plt.subplots(1,1, figsize=(6,5))

df.plot.bar(ax=ax)
ax.set_xlabel('YEAR')

fig.tight_layout()
fig.show()

The output is this figure: enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

thanks A lot, Robbie, Wanted to ask, what if I had 3 Variables to be plotted (A, B, C). How would we adjust the width?
Hi @ApoorvaaSingh - check out the edit, hopefully this helps!
Thank you. It was helpful :)
Also, if you could tell me how would i rotate the Xlabels (i tried using ax.set_xticklabels(rotation = 90), does not seem to work
Sure, you have to add that argument to the call to the panda's bar function: df.plot.bar(ax=ax, rot=0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.