如何为选定x值绘制误差棒?(解决数据尺寸不匹配问题)
仅为特定X值绘制误差棒的实现方法
要实现仅为特定x值绘制误差棒,核心是让误差棒的x坐标、均值数据、标准差数据三者维度完全匹配——只保留你需要的那些点的对应数据即可。以下是修改后的代码示例:
import numpy as np import matplotlib.pyplot as plt # 假设你的原始参数与路径设置 simulation_name = "test" eta = "0.5" arm_length = "1.0" current_nint = 10 filename = "test_plot" path = "./" figure_name = f"{simulation_name}_eta={eta}_arm_length={arm_length}_nint={current_nint}" fig1, axs1 = plt.subplots(1) # 生成模拟数据(20组,每组2000个数据点) ys = np.random.randn(20, 2000) errorbars = np.std(ys, axis=0) # 每个x位置的标准差 ymean = np.mean(ys, axis=0) # 每个x位置的均值 all_xs = np.arange(2000) # 所有x值(0到1999) # -------------------------- # 核心:选择要绘制误差棒的特定x值索引 # 示例1:每隔100个点取一个 selected_indices = np.arange(0, 2000, 100) # 示例2:指定具体x值,比如[0, 500, 1000, 1500] # target_x = [0, 500, 1000, 1500] # selected_indices = np.isin(all_xs, target_x) # 提取对应的数据 selected_xs = all_xs[selected_indices] selected_ymean = ymean[selected_indices] selected_errorbars = errorbars[selected_indices] # -------------------------- # 绘制误差棒(仅针对选中的x值) plt.errorbar(selected_xs, selected_ymean, yerr=selected_errorbars, fmt='-o') # fmt控制线条和点样式 plt.savefig(f"{path}FitVsGen_{filename}.png") plt.close()
关键说明:
- 维度匹配:确保
selected_xs、selected_ymean、selected_errorbars的长度完全相同,这样plt.errorbar才能正确绘制。 - 灵活选择:你可以通过修改
selected_indices来定义任意需要的x值位置——比如间隔采样、指定特定坐标,或者根据业务逻辑筛选。 - 样式控制:
fmt参数可以调整线条和标记的样式,让选中的误差棒点更显眼(比如用圆形标记o)。
内容的提问来源于stack exchange,提问作者eeqesri
相关产品推荐
相关产品推荐

