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

使用matplotlib tricontour屏蔽无效三角形时遇多维索引报错求助

解决tricontour屏蔽大三角形时的多维索引错误

错误原因

触发ValueError: Cannot index with multidimensional key是因为你的x和y是Pandas Series对象,而triang.triangles是二维数组(每行存储一个三角形的三个顶点索引)。Pandas Series不支持用多维数组做索引,必须先转成NumPy数组才能进行后续的数组运算。

修改方案

在创建Triangulation之前,将x和y转换为NumPy数组,使用to_numpy()方法(推荐)或.values属性。

修改后的完整代码

fig, (ax2) = plt.subplots(nrows=1)

# 关键修改:将Pandas Series转为NumPy数组
x = x.to_numpy()
y = y.to_numpy()

triang = tri.Triangulation(x, y)

# 仅绘制边长最大值≤max_radius的三角形
max_radius = 2
triangles = triang.triangles

# 屏蔽不符合要求的三角形
xtri = x[triangles] - np.roll(x[triangles], 1, axis=1)
ytri = y[triangles] - np.roll(y[triangles], 1, axis=1)
maxi = np.max(np.sqrt(xtri**2 + ytri**2), axis=1)
triang.set_mask(maxi > max_radius)

# 绘制等值线与填充
ax2.tricontour(triang, plausability_control['wc_values'][1], levels=20, linewidths=0.2, colors='k')
cntr2 = ax2.tricontourf(triang, plausability_control['wc_values'][1], levels=20, cmap="RdBu")

# 设置颜色条
cbar2 = fig.colorbar(cntr2, ax=ax2)
cbar2.set_label('(m-3 m3)', loc='center', fontsize=8, rotation=270, labelpad=15)

# 设置坐标轴范围与标题
ax2.set(xlim=(xmin, xmax), ylim=(ymin, ymax))
ax2.set_title('Reference Scenario: Water Content - time step ' + str(1))

plt.subplots_adjust(hspace=0.5)
plt.savefig('reference_experiment')
plt.show()
plt.close()

额外说明

如果x和y来自DataFrame的列,可直接通过x = df['x_column'].to_numpy()的方式转换,确保后续数组运算基于NumPy对象,避免Pandas与NumPy的索引兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:30:28