matplotlib中水平堆积条形图的问题

Problem in horizontal stacked bar graph in matplotlib

下面是我创建水平堆积条形图的代码:

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

它产生下图:

我觉得这里很荒谬的是红色部分的长度只有 20 但它应该是 30 因为 tutorial_public = [30] 。我在这里做错了什么?

红色条的宽度30,你的问题是你用蓝色条隐藏了部分条(通过注释代码的最后一行来试试) )

您需要调整第三个 barhleft= 参数(注意我已将您的列表转换为 numpy 数组以方便算术运算):

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