Table of Contents

Stack bar Graph Example – Matplotlib Tutorial

When we need to represent stacked data over a different range of categories, we use a stacked bar graph. Let’s take the same example where a person prefers to watch and enjoy Youtube, Netflix, Amazon Prime, HBO Now, Hulu over a week. So, when we create a stack bar graph plot, we will be able to see the time spent by the user each day on a different video streaming apps in a span of 7 days from Monday to Sunday as a whole by the person.

Creating a Stack Bar Graph using matplotlib

We will simply take one list for x coordinates and five lists for our y coordinates. The only new thing we will introduce here is bottom property to arrange stacks. Rest of the functions we have already discussed such as bar() xlabel() ylabel() title() legend() show()

The below python code is a basic example of how to create and draw a stack plot using Matplotlib.

 

import matplotlib.pyplot as plt


Days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" ]
Youtube = [3, 3.5, 4, 2, 1, 5, 6]
Netflix = [1, 3, 2, 1, 2, 4, 5]
Amazon_Prime = [0.8, 0.8, 0.8, 0.8 ,0.8, 3, 3 ]
HBO_Now = [0.6, 0.6, 0.6, 0.6, 0.6, 2, 2]
Hulu = [0.3, 0.3, 0.3, 0.3, 0.3, 1, 1]
labels =["Youtube", "Netflix", "Amazon_Prime", "HBO_Now", "Hulu"]
width = 0.35       # the width of the bars: can also be len(x) sequence

a = [Youtube[i] for i in range(len(Youtube))]
b = [Youtube[i] + Netflix[i] for i in range(len(Youtube))]
c = [Youtube[i] + Netflix[i] + Amazon_Prime[i] for i in range(len(Youtube))]
d = [Youtube[i] + Netflix[i] + Amazon_Prime[i] + HBO_Now[i]for i in range(len(Youtube))]

p1 = plt.bar(Days, Youtube, width)
p2 = plt.bar(Days, Netflix, width, bottom=a )
p3 = plt.bar(Days, Amazon_Prime, width, bottom=b)
p4 = plt.bar(Days, HBO_Now, width, bottom=c)
p5 = plt.bar(Days, Hulu, width, bottom=d)

plt.title('Stack Bar Graph Example')
plt.xlabel("Days" )
plt.ylabel("Video Streaming Apps")
plt.title("Stack Plot Example")

plt.legend(labels)
plt.show()

 

In the above code, you can see the use of the bottom property. Our motive is to stack:

  • Youtube data at the base level (n, which refers to the data height taken by Y coordinates of Youtube).
  • Netflix will stack over youtube data, thus the bottom will scale to youtube+Netflix data
  • Amazon_prime will stack over youtube and Netflix data, thus the bottom will scale to youtube+Netflix+Amazon_prime data
  • HBO_Now will stack over youtube, Netflix data and Amazon_prime thus the bottom will scale to youtube+Netflix+Amazon_prime_ data
  • Hulu will stack over youtube, Netflix data,  Amazon_prime and HBO_Now thus the bottom will scale to youtube+Netflix+Amazon_prime+HBO_Now data

Given below is the code shown in Python Online code editor where you can edit the code to experiment with the data and stack bar Graph.