简体   繁体   中英

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 : 在此处输入图片说明

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM