使用plt.errorbar绘制子图时出现‘ax参数值重复’TypeError问题求助
解决Matplotlib errorbar报错:TypeError: inner() got multiple values for argument 'ax'
错误根源
plt.errorbar不支持ax参数:全局的plt.errorbar()函数没有ax这个参数,传递ax=ax[i]会导致参数冲突,触发报错。正确方式是直接调用子图对应的轴对象(ax[i])的errorbar()方法。- Y轴数值写死:初始代码中
y=dataSoda["As"]固定为As列,导致所有子图都绘制As的数值,不符合每个子图对应不同元素的需求。 - 冗余循环:不需要单独循环不确定度列,在同一个循环里通过字符串拼接即可获取对应元素的不确定度列。
修正后的完整代码
import matplotlib.pyplot as plt import seaborn as sns # 创建子图布局 fig, ax = plt.subplots(nrows=3, ncols=3, figsize=[10, 6]) ax = ax.flatten() # 遍历每个元素列 elements = ["As", "W", "Li", "Mn", "Sn", "Zn", "Ba"] for i, column in enumerate(elements): # 绘制散点图 sns.scatterplot( x="A_encoded", y=column, data=dataSoda, s=40, c="green", ax=ax[i], label="Soda-Pottash" ) # 绘制误差棒(调用轴对象的errorbar方法) ax[i].errorbar( x=dataSoda["A_encoded"], y=dataSoda[column], # 对应当前元素的Y值 yerr=dataSoda[f"Ungenauigkeit {column}"], # 动态拼接不确定度列名 fmt="none", c="black", capsize=4, label="Uncertainty Intervall" ) # 可选:添加子图标题和图例 ax[i].set_title(f"Element: {column}") ax[i].legend() # 调整子图间距,防止重叠 plt.tight_layout() plt.show()
关键修改说明
- 将
plt.errorbar(..., ax=ax[i])替换为ax[i].errorbar(...),直接在目标子图轴上绘制误差棒。 - 把
y=dataSoda["As"]改为y=dataSoda[column],确保每个子图对应当前循环的元素数值。 - 用
f"Ungenauigkeit {column}"动态拼接不确定度列名,避免冗余循环,简化逻辑。
内容的提问来源于stack exchange,提问作者Nic
相关产品推荐
相关产品推荐

