FAQ: Different Plot Types - Stacked Bars

This community-built FAQ covers the “Stacked Bars” exercise from the lesson “Different Plot Types”.

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

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!

In this excercise, if I write plt.bar(range(len(drinks)),sales 1) at the bottom instead of at the top as follows,
plt.bar(range(len(drinks)),sales2,bottom=sales1)
plt.bar(range(len(drinks)),sales1)

,when I name locations with legend like this,
plt.legend([“Location 1”,“Location 2”])
it doesn’t get right. My question is actually what order does legend name it, and does it change anything if I have draw charts in a different order as appear above?

I’m trying to add coffee labels to the x-line of the bar chart in this exercise

drinks = ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"]
sales1 = [91, 76, 56, 66, 52, 27]
sales2 = [65, 82, 36, 68, 38, 40]
ax = plt.subplot()
plt.bar(range(len(drinks)), sales1)
plt.bar(range(len(drinks)), sales2, bottom = sales1)
plt.title('Coffee Sold in Two Coffee Shops')
plt.xlabel('Coffee')
plt.ylabel('Amount sold')
plt.legend(['Location 1', 'Location 2'])
ax.set_xticklabels (drinks)
plt.show()

But the graph doesn’t show what expected…

Screenshot 2023-07-28 112514

Why ‘Latte’ take place of ‘Cappuccino’ and move all the other coffee on the left, leaving one last bar empty?
What did I do wrong?

Thank you for help

in ax.set_xticklabels(drinks) the labels start at 1, not index 0. Also, set the xticks before you label the x axis.
See:
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xticks.html

Rather, instead of using ax.setxticklabels() you could try:

plt.xticks([0, 1, 2, 3, 4, 5], ["cappuccino", "latte", "chai", "americano", "mocha", "espresso"], rotation=15)  # Set the labels and properties.

Thank you so much!
Now I see my mistake. plt.xticks() function is much easier as I have 4 function in one :star_struck: !
Thank you to teach me new things!

1 Like