FAQ: Recreate graphs using Matplotlib! - Stacked Bars

This community-built FAQ covers the “Stacked Bars” exercise from the lesson “Recreate graphs using Matplotlib!”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Data Science

Data Visualization in Python

FAQs on the exercise Stacked Bars

In the context of this exercise, applying stacked bar charts, when do we usually apply them?

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

I don’t understand how the bar will stack from the c grade and up, I tried to add or substract my new “bottom” variable to the respectfull grade list with no success.

import codecademylib
from matplotlib import pyplot as plt
import numpy as np

unit_topics = [‘Limits’, ‘Derivatives’, ‘Integrals’, ‘Diff Eq’, ‘Applications’]
As = [6, 3, 4, 3, 5]
Bs = [8, 12, 8, 9, 10]
Cs = [13, 12, 15, 13, 14]
Ds = [2, 3, 3, 2, 1]
Fs = [1, 0, 0, 3, 0]

x = range(5)

c_bottom = np.add(As, Bs)
#create d_bottom and f_bottom here
d_bottom = np.add(c_bottom, Cs)
f_bottom = np.add(d_bottom, Ds)
#create your plot here
#Question 2
plt.figure(figsize= (10,8))
ax = plt.subplot()
ax.set_xticks(range(len(unit_topics)))
ax.set_xticklabels(unit_topics)
plt.bar(x, As, Label=‘A’)
plt.bar(x, Bs, Label=‘B’)
plt.bar(x, c_bottom, Label=‘C’)
plt.bar(x, d_bottom, Label=‘D’)
plt.bar(x, (f_bottom + Fs), Label=‘F’)
plt.title(‘Grade distribution’)
plt.xlabel(‘Unit’)
plt.ylabel(‘Number of Students’)
plt.savefig(‘my_stacked_bar.png’)
plt.show()

Your code looks good up to the second bar plot (as I think you expect). Remember that Bs needs to begin where As left off. We can achieve this stacking by

plt.bar(x, Bs, bottom=As)

Continue this for all letter grades, and you should be good.

Note: adding labels was a nice touch, but you didn’t end up using them by creating a legend anywhere.

this is the best solution

plt.bar(x, As)

plt.bar(x, Bs, bottom=As)

plt.bar(x, Cs, bottom=c_bottom)

plt.bar(x, Ds, bottom=d_bottom)

plt.bar(x, Fs, bottom=f_bottom)

1 Like

Thank you it works

I have reviewed the concepts and it only mention the bottom function on question 3 without much clarity.

Cheer

Why are we using function… rest all i understood

np.add()

You could use list comprehension to do the same thing. The NumPy array function np.add() just makes it easier to do the same thing.
For example:
a = [1, 2, 3, 4, 5]
b = [2, 4, 6, 8, 10]

List_comp:
a_b = [(n + m) for n, m in zip(a, b)]
returns: [3, 6, 9, 12, 15]

NumPy Add Func:
a_b = np.add(a, b)
returns: [3, 6, 9, 12, 15]

I only have a basic understanding of numpy but I hope that this helps!

1 Like

Same story here, I don’t know what version of Matplotlib is in the kernel that Codecademy runs but the instructions are too long for something this simple, it makes more sense to me to simply use Pandas.

This implementation is two lines long.

import pandas as pd

unit_topics = ["Limits", "Derivatives", "Integrals", "Diff Eq", "Applications"]
As = [6, 3, 4, 3, 5]
Bs = [8, 12, 8, 9, 10]
Cs = [13, 12, 15, 13, 14]
Ds = [2, 3, 3, 2, 1]
Fs = [1, 0, 0, 3, 0]

df2 = pd.DataFrame(dict(As=As, Bs=Bs, Cs=Cs, Ds=Ds, Fs=Fs), index=unit_topics)

df2.plot.bar(stacked=True, rot=0, figsize=(10,8))

1 Like

Hi team,

Does anybody know how to number labels on to the stacked bars?
In the ‘Creating Pie Chart’ lesson, there is a keyword argument used to achieve this and its called autopct = '%0.2F
This keyword argument will produce labels with numbers + 2 decimal places onto the pie chart.

But how about for stacked bars? I tried using the autopct keyword argument but it didn’t work.

Kind Regards,
Jimmy

There’s no simple method to complete this so far as I know. It would be worth having a look at this recipe on the matplotlib docs page which has an exmaple of how to achieve this-
https://matplotlib.org/3.3.0/gallery/lines_bars_and_markers/barchart.html

With stacked plots it would probably take more work and you may need to search around for answers like the following-

1 Like

Great,
Thanks for the resource…

The final graph example doesn’t have the x-axis label of ‘Unit’ that I can see. However, it won’t let you progress until you add the label. Even after adding the label it doesn’t show up on the x-axis.

I’m afraid I can’t run this lesson to check it but if you’re adding a label you may have redraw the figure and fig.show it again. If it’s the example figure on the right hand side of the page you’re quite right that it doesn’t actually show an x-label, it only has xtick labels. Perhaps they want the legend added instead?
Apologies if that isn’t much help.

Hi, it did work for me after I added the x label ‘Units’. It doesn’t show on the graph though.

The instruction calls for ‘add the title, x label and y label the same as on the graph example’ so I assumed it was a trick question to see if the student noticed there is no x label and leave it off their version, however after omitting the x label it will error and tell you to add it in. So I think this is just an oversight in the lesson and should be updated to save confusion for others in the future. :slight_smile: