如何基于自定义计算值,用Matplotlib plt.bar绘制分色柱状图?
自定义颜色分组的Matplotlib柱状图实现方案
直接上可运行的完整代码,完全符合你的需求:
import matplotlib.pyplot as plt # 替换成你自己计算好的My_Custom系列数值 My_Custom_0 = 2.5 My_Custom_1 = 4.2 My_Custom_2 = 5.8 My_Custom_3 = 4.5 My_Custom_4 = 3.0 # 整理数据:按顺序排列数值、标签、对应颜色 values = [My_Custom_0, My_Custom_1, My_Custom_2, My_Custom_3, My_Custom_4] labels = ['Custom 0', 'Custom 1', 'Custom 2', 'Custom 3', 'Custom 4'] # 按你的分组规则设置颜色:0/4为红色,1/2/3为绿色 colors = ['red', 'green', 'green', 'green', 'red'] # 生成柱子的x轴位置 x_pos = range(len(values)) # 绘制柱状图,指定颜色 plt.bar(x_pos, values, color=colors) # 添加柱子下方的自定义标签 plt.xticks(x_pos, labels) # 可选:添加标题和坐标轴标签(按需调整) plt.title('Custom Values Bar Chart') plt.ylabel('Calculated Value') # 调整布局,防止标签被截断 plt.tight_layout() # 显示图形 plt.show()
关键细节说明
- 数据处理:所有数值都是你自己计算好的直接复用,全程没有使用任何第三方计算函数(比如Scipy的泊松工具),完全符合要求。
- 配色实现:通过给
plt.bar()的color参数传入颜色列表,直接对应每个柱子的颜色,不用复杂的分组逻辑,简单高效。 - 标签设置:
plt.xticks()直接把x轴的位置刻度替换成你需要的自定义标签,清晰明了。 - 布局调整:
tight_layout()自动调整图形边距,避免标签被图形边缘截断,提升可读性。
内容的提问来源于stack exchange,提问作者Drankenkin
相关产品推荐
相关产品推荐

