# Got annoying Vertical white space in stacked bars

Hi
In practicing drawing stacked bars with matplot I get an annoying white space (vertically) in all my charts HERE is an example . What can b e the solution?

Hello Welcome to the forum.

1 Like

Hello there, many thanks for your help here is my code :

``````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)
plt.figure(figsize = (10,8))
#create d_bottom and f_bottom here
plt.bar (x, As)
plt.bar (x, Bs, bottom = Bs)
plt.bar (x, Cs, bottom = c_bottom)
plt.bar (x, Ds, bottom = d_bottom)
plt.bar (x, Fs, bottom = f_bottom)
ax =plt.subplot()
ax.set_xticks(range(len(unit_topics)))
ax.set_xticklabels(unit_topics)
plt.ylabel("Number of Students")
plt.xlabel("Unit")
plt.savefig("my_stacked_bar.png")
plt.show()
``````
1 Like

This is the result of your code:

Take a look at these two lines from your code:

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

So the first line creates a new set of bars, with heights from the list `As`. These are the blue bars in your plot.

But in the second line, you create a new set of bars (orange bars in the plot) with heights defined in the list `Bs` and with bottom set to the list `Bs`. This means that each bar `i` will have height `Bs[i]` and will be drawn starting at y coordinate = `Bs[i]`.

And this is not what you should have done. You want to draw every next set of bars on the top of the previous set. So the y baseline (`bottom`) should be set to the sum of heights of each previous set of bars. So for the second set of bars you want to set `bottom = As`.

``````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)
``````

If my explanation is a bit messy - sorry, here is another example. Let’s take a look at how you draw the third set of bars:

``````c_bottom = np.add(As, Bs)
plt.bar(x, Cs, bottom = c_bottom)
``````

In the first line, you calculated the sum of the height of corresponding bars from the set `As` and `Bs`. And then you draw the new set of bars - `Cs` specifying that they should be drawn at `y` coordinates equal to the calculated sum.

1 Like

Understood, thanks a lot for your help 2 Likes

You’re very welcome! 1 Like