如何在Python中创建各变量值间带间隙的堆叠柱状图
没问题,我来帮你实现这个堆叠柱状图!你的需求是让A、B、C三个变量对应的堆叠柱子之间带有间隙,而且三个变量的数值长度不一样对吧?我用matplotlib给你写了两种可行的方案,你可以根据自己的需求选:
方案一:每个变量对应一个独立堆叠柱,组间带间隙
这种方案里,A、B、C各自的数值会堆叠成一个柱子,三个柱子之间留有明显的间隙,能清晰看到每个变量的总数值和各部分的占比。
代码如下:
import matplotlib.pyplot as plt import numpy as np # 你的原始数据 A = [3, 5, 7] B = [4, 5, 7] C = [2, 3, 4, 5, 6, 7] # 定义每个变量堆叠柱的x轴位置,通过间隔数值来制造间隙 group_x = [0, 2, 4] bar_width = 0.8 # 绘制A的堆叠柱 bottom = 0 for value in A: plt.bar(group_x[0], value, bar_width, bottom=bottom) bottom += value # 绘制B的堆叠柱 bottom = 0 for value in B: plt.bar(group_x[1], value, bar_width, bottom=bottom) bottom += value # 绘制C的堆叠柱 bottom = 0 for value in C: plt.bar(group_x[2], value, bar_width, bottom=bottom) bottom += value # 配置图表细节 plt.xticks(group_x, ['A', 'B', 'C']) plt.xlabel('Variables') plt.ylabel('Cumulative Value') plt.title('Stacked Bars with Gaps Between Variables') plt.tight_layout() plt.show()
代码说明:
- 我们通过设置
group_x为[0,2,4],让三个堆叠柱之间自动产生间隙; - 每个变量的数值逐个堆叠,
bottom变量用来记录上一层柱子的顶部位置,确保新的柱子叠在上面; - 最后通过
xticks把x轴刻度替换成变量名称,让图表更易读。
方案二:保留每个变量的所有独立柱子,组间带间隙
如果你希望每个变量的每个数值都作为独立的柱子(同一变量的柱子相邻堆叠),不同变量的柱子组之间留间隙,可以用这个方案:
import matplotlib.pyplot as plt import numpy as np A = [3, 5, 7] B = [4, 5, 7] C = [2, 3, 4, 5, 6, 7] # 设置组间间隙宽度和柱子宽度 gap = 2 bar_width = 0.7 # 为每个变量的柱子分配x轴位置 x_A = np.arange(len(A)) x_B = np.arange(len(B)) + len(A) + gap x_C = np.arange(len(C)) + len(A) + len(B) + 2*gap # 绘制A的堆叠柱(每个数值对应一个堆叠层) bottom_A = 0 for val in A: plt.bar(x_A, val, bar_width, bottom=bottom_A) bottom_A += val # 绘制B的堆叠柱 bottom_B = 0 for val in B: plt.bar(x_B, val, bar_width, bottom=bottom_B) bottom_B += val # 绘制C的堆叠柱 bottom_C = 0 for val in C: plt.bar(x_C, val, bar_width, bottom=bottom_C) bottom_C += val # 配置图表 plt.xlabel('Element Index') plt.ylabel('Cumulative Value') plt.title('Stacked Bars with Gaps Between Variable Groups') plt.tight_layout() plt.show()
代码说明:
- 我们为每个变量的柱子分配了不重叠的x轴范围,用
gap控制组之间的间隔; - 同一变量内的每个数值都堆叠在对应位置的柱子上,能看到每个元素的累积值;
- 这种方案适合需要对比同一变量内不同元素堆叠情况的场景。
你可以根据自己的实际需求选择其中一种,运行代码就能得到符合要求的堆叠柱状图啦!
内容的提问来源于stack exchange,提问作者PPM
相关产品推荐
相关产品推荐

