【问题标题】:Invert stacked bars in matplotlib反转 matplotlib 中的堆叠条形图
【发布时间】:2021-10-22 15:43:57
【问题描述】:

I would like to invert the position of the colours in the bar chart below.

这是用于生成图表的部分代码:

ax.bar(date,caloric_intake, width=0.4)
ax.bar(date,exercice_deficit,width=0.4,bottom=caloric_intake )

我已尝试使用底部参数,但图表中的结果条变得更高。 as seen in this picture

有谁知道如何解决这个问题?提前致谢。

【问题讨论】:

    标签: python matplotlib bar-chart


    【解决方案1】:

    我没有看到您的代码。但在此示例中,堆叠条顶部的第一个图中的“ax.bar”设置,见下文:

    import matplotlib.pyplot as plt
    
    
    labels = ['G1', 'G2', 'G3', 'G4', 'G5']
    men_means = [20, 35, 30, 35, 27]
    women_means = [25, 32, 34, 20, 25]
    men_std = [2, 3, 4, 1, 2]
    women_std = [3, 5, 2, 3, 3]
    width = 0.35 
    
    fig, ax = plt.subplots()
    
    ax.bar(labels, women_means, width, yerr=women_std, bottom=men_means,label='Women')
    ax.bar(labels, men_means, width, yerr=men_std, label='Men')
    
    
    ax.set_ylabel('Scores')
    ax.set_title('Scores by group and gender')
    ax.legend()
    
    plt.show()
    

    输出:

    import matplotlib.pyplot as plt
    
    
    labels = ['G1', 'G2', 'G3', 'G4', 'G5']
    men_means = [20, 35, 30, 35, 27]
    women_means = [25, 32, 34, 20, 25]
    men_std = [2, 3, 4, 1, 2]
    women_std = [3, 5, 2, 3, 3]
    width = 0.35 
    
    fig, ax = plt.subplots()
    
    ax.bar(labels, men_means, width, yerr=men_std, label='Men')
    ax.bar(labels, women_means, width, yerr=women_std, bottom=men_means,label='Women')
    
    
    ax.set_ylabel('Scores')
    ax.set_title('Scores by group and gender')
    ax.legend()
    
    plt.show()
    

    输出:

    【讨论】:

    • 是的,抱歉,第二张图片对应的代码是:ax.bar(date,exercice_deficit,width=0.4,bottom=caloric_intake ) ax.bar(date,caloric_intake, width=0.4) 我试过换线,但条形的总高度仍然比第一张高
    猜你喜欢
    • 2020-10-16
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 2020-10-05
    相关资源
    最近更新 更多