Search code examples
pythonpython-3.xmatplotlibbar-chartstacked-chart

Problem in horizontal stacked bar graph in matplotlib


Below is my code which creates horizontal stacked bar graph:

import matplotlib.pyplot as plt

year = [2014]  
tutorial_public = [30]  
tutorial_premium = [10]
tutorial_premiumx = [20] 

fig, axs = plt.subplots(1)

axs.barh(year, tutorial_premium, color="yellow")  
axs.barh(year, tutorial_public, left=tutorial_premium, color="red")
axs.barh(year, tutorial_premiumx, left=tutorial_public, color="blue")

It produces the below image : enter image description here

What i find absurd here is that length of the red part is only 20 but it should be 30 because tutorial_public = [30] . What am i doing wrong here?


Solution

  • The width of the red bar is 30, your problem is that you have hidden part of the bar with the blue bar (try it by commenting the last line of your code)

    You need to adjust the left= argument of your third barh (Notice that I have converted your list to numpy arrays to facilitate arithmetic operations):

    import matplotlib.pyplot as plt
    
    year = [2014]  
    tutorial_public = np.array([30])
    tutorial_premium = np.array([10])
    tutorial_premiumx = np.array([20])
    
    fig, axs = plt.subplots(1)
    
    axs.barh(year, tutorial_premium, color="yellow")  
    axs.barh(year, tutorial_public, left=tutorial_premium, color="red")
    axs.barh(year, tutorial_premiumx, left=tutorial_premium+tutorial_public, color="blue")