求助:为散点图添加误差棒无效,颜色条及颜色缩放异常
问题解决步骤
1. 修复颜色条缩放与颜色映射问题
你当前代码的核心问题是把values传给了scatter的第三个参数s(点的大小),而非颜色参数c,导致颜色映射完全未生效,颜色条自然出现异常。修正代码如下:
(x, y) = self.rig_parameters["image_size"] disparity_image = np.array(image) locations = np.where(disparity_image > error_bound) values = disparity_image[locations] plt.xlim(0, x) plt.ylim(y, 0) # 修正:将values传给c参数指定点的颜色,s参数设置点的大小(示例设为15) scatter = plt.scatter(locations[1], locations[0], c=values, s=15, vmin=error_bound, vmax=256) plt.colorbar(scatter) # 显式传入scatter对象,确保颜色条与散点颜色映射匹配 plt.show()
修改后颜色会根据values正常映射,颜色条的缩放也会和vmin、vmax设定值对应。
2. 添加误差棒
散点图的误差棒需要明确每个点在x/y方向的误差值。假设你已有对应的误差数据(示例用随机数据模拟,实际替换为你的真实误差值),可以通过以下两种方式实现:
方法一:用errorbar直接绘制带误差棒的散点
(x, y) = self.rig_parameters["image_size"] disparity_image = np.array(image) locations = np.where(disparity_image > error_bound) values = disparity_image[locations] # 示例:生成随机误差数据,实际替换为你的真实误差 x_err = np.random.rand(len(values)) * 2 y_err = np.random.rand(len(values)) * 2 plt.xlim(0, x) plt.ylim(y, 0) # fmt='o'指定散点样式,c绑定颜色映射,ecolor设置误差棒颜色 errorbar = plt.errorbar(locations[1], locations[0], xerr=x_err, yerr=y_err, fmt='o', c=values, vmin=error_bound, vmax=256, s=15, ecolor='gray') # 手动创建颜色条,适配errorbar的颜色映射 sm = plt.cm.ScalarMappable(cmap=errorbar.cmap, norm=errorbar.norm) sm.set_array(values) plt.colorbar(sm) plt.show()
方法二:分开绘制误差棒与散点(更灵活控制样式)
(x, y) = self.rig_parameters["image_size"] disparity_image = np.array(image) locations = np.where(disparity_image > error_bound) values = disparity_image[locations] x_err = np.random.rand(len(values)) * 2 y_err = np.random.rand(len(values)) * 2 plt.xlim(0, x) plt.ylim(y, 0) # 先绘制误差棒,fmt='none'隐藏默认线条和点 plt.errorbar(locations[1], locations[0], xerr=x_err, yerr=y_err, fmt='none', ecolor='gray', capsize=2) # 再绘制散点,颜色映射正常生效 scatter = plt.scatter(locations[1], locations[0], c=values, s=15, vmin=error_bound, vmax=256) plt.colorbar(scatter) plt.show()
如果你的误差是与视差values相关的单一值(比如每个点的误差为values * 0.1),只需将x_err或y_err替换为对应计算逻辑即可。
内容的提问来源于stack exchange,提问作者FourierFlux
相关产品推荐
相关产品推荐

