【问题标题】:Create stacked bar with matplotlib使用 matplotlib 创建堆积条形图
【发布时间】:2020-09-09 12:32:42
【问题描述】:

我有以下格式的数据显示:

values = np.array([10, 12,13, 5,20], [30, 7, 10, 25,2], [10, 12,13, 5,20]])

我想创建一个如下图所示的垂直堆积条形图。数组中的每个元素都属于一个堆叠条。

我已经搜索过如何使用 matplotlib 做到这一点,但不幸的是,我仍然没有找到一种方法来做到这一点。我该怎么做?

【问题讨论】:

标签: python matplotlib


【解决方案1】:

AFAIK,现在有一种简单的方法可以做到这一点。您需要自己计算条形的确切位置,然后对其进行归一化。

import numpy as np
import matplotlib.pyplot as plt

values = np.array([[10, 12,13, 5,20], [30, 7, 10, 25,2], [10, 12,13, 5,20]])
values_normalized = values/np.sum(values, axis=0)
bottom_values = np.cumsum(values_normalized, axis=0)
bottom_values = np.vstack([np.zeros(values_normalized[0].size), bottom_values])
text_positions = (bottom_values[1:] + bottom_values[:-1])/2
r = [0, 1, 2, 3, 4] # position of the bars on the x-axis
names = ['A', 'B', 'C', 'D', 'E'] # names of groups
colors = ['lightblue', 'orange', 'lightgreen']
for i in range(3):
    plt.bar(r, values_normalized[i], bottom=bottom_values[i], color=colors[i], edgecolor='white', width=1, tick_label=['a','b','c','d','e'])
    for xpos, ypos, yval in zip(r, text_positions[i], values[i]):
        plt.text(xpos, ypos, "N=%d"%yval, ha="center", va="center")
    # Custom X axis
plt.xticks(r, names, fontweight='bold')
plt.xlabel("group")
plt.show()

There is a source 告诉如何在条形顶部添加文本。我现在有点着急,所以我希望这很有用,如果需要,我会在第二天更新我的答案。

我已经更新了我的答案。在条形顶部添加文本很棘手,它需要计算它们的垂直位置。

顺便说一句,我已经重构了我共享的链接中的大部分代码。

【讨论】:

    【解决方案2】:
    • Python 3.8
    • matplotlib 3.3.1
    • numpy 1.19.1

    Chat Result

    import matplotlib.pyplot as plt
    import numpy as np
    
    values = np.array([[10, 12, 13, 5, 20], [30, 7, 10, 25, 2], [10, 12, 13, 5, 20]])
    row, column = values.shape  # (3, 5)
    
    x_type = [x+1 for x in range(column)]
    ind = [x for x, _ in enumerate(x_type)]
    
    values_normalized = values/np.sum(values, axis=0)
    value1, value2, value3 = values_normalized[0,:], values_normalized[1,:], values_normalized[2,:]
    
    # Create figure
    plt.figure(figsize=(8, 6))
    plt.bar(ind, value1, width=0.8, label='Searies1', color='#5B9BD5')
    plt.bar(ind, value2, width=0.8, label='Searies2', color='#C00000', bottom=value1)
    plt.bar(ind, value3, width=0.8, label='Searies3', color='#70AD47', bottom=value1 + value2)
    
    # Show text
    bottom_values = np.cumsum(values_normalized, axis=0)
    bottom_values = np.vstack([np.zeros(values_normalized[0].size), bottom_values])
    text_positions = (bottom_values[1:] + bottom_values[:-1])/2
    c = list(range(column))
    for i in range(3):
        for xpos, ypos, yval in zip(c, text_positions[i], values[i]):
            plt.text(xpos, ypos, yval, horizontalalignment='center', verticalalignment='center', color='white')
    
    plt.xticks(ind, x_type)
    plt.legend(loc='center', bbox_to_anchor=(0, 1.02, 1, 0.1), handlelength=1, handleheight=1, ncol=row)
    plt.title('CHART TITLE', fontdict = {'fontsize': 16,'fontweight': 'bold', 'family': 'serif'}, y=1.1)
    
    # Hide y-axis
    plt.gca().axes.yaxis.set_visible(False)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 2017-11-02
      • 2018-01-17
      • 2019-11-28
      • 2014-06-02
      • 1970-01-01
      相关资源
      最近更新 更多