You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在误差棒柱状图中绘制连接柱形顶部中心的线条?

在误差棒柱状图中添加连接柱顶中心的线条

要实现连接各柱形顶部中心的红色线条,只需在现有柱状图代码中添加一行折线绘制逻辑即可,具体修改如下:

修改后的完整代码

import numpy as np
import matplotlib.pyplot as plt

# 输入原始数据
aluminum = np.array([6.4e-5 , 3.01e-5 , 2.36e-5, 3.0e-5, 7.0e-5, 4.5e-5, 3.8e-5, 4.2e-5, 2.62e-5, 3.6e-5])
copper = np.array([4.5e-5 , 1.97e-5 , 1.6e-5, 1.97e-5, 4.0e-5, 2.4e-5, 1.9e-5, 2.41e-5, 1.85e-5, 3.3e-5])
steel = np.array([3.3e-5 , 1.2e-5 , 0.9e-5, 1.2e-5, 1.3e-5, 1.6e-5, 1.4e-5, 1.58e-5, 1.32e-5 , 2.1e-5])

# 计算平均值
aluminum_mean = np.mean(aluminum)
copper_mean = np.mean(copper)
steel_mean = np.mean(steel)

# 计算标准差
aluminum_std = np.std(aluminum)
copper_std = np.std(copper)
steel_std = np.std(steel)

# 准备绘图用的列表
materials = ['Aluminum', 'Copper', 'Steel'] 
x_pos = np.arange(len(materials))
CTEs = [aluminum_mean, copper_mean, steel_mean]
error = [aluminum_std, copper_std, steel_std]

# 构建图像
fig, ax = plt.subplots()
ax.bar(x_pos, CTEs, yerr = error, align = 'center', alpha = 0.5, ecolor = 'black', capsize=10)
# 添加连接柱顶中心的红色折线与标记点
ax.plot(x_pos, CTEs, color='red', marker='o', linestyle='-', linewidth=2)
ax.set_ylabel('Coefficient of Thermal Expansion ($\degree C^{-1}$)') 
ax.set_xticks(x_pos)
ax.set_xticklabels(materials)
ax.set_title('Coefficient of Thermal Expansion (CTE) of Three Metals')  
ax.yaxis.grid(True)
plt.show()

关键逻辑说明

新增的ax.plot(x_pos, CTEs, color='red', marker='o', linestyle='-', linewidth=2)语句实现了核心需求:

  • x_pos对应每个柱形的中心x坐标,CTEs是柱形的高度(平均值),两者一一对应能精准连接柱顶中心
  • color='red'将线条设置为红色
  • marker='o'在每个柱顶中心添加圆形标记,让线条与柱顶的连接更清晰
  • linestyle='-'使用实线连接各点,linewidth=2可按需调整线条粗细

内容的提问来源于stack exchange,提问作者José

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 02:52:13