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

如何为不等尺寸数组制作带可见数据点的等高线/拓扑图?

实现等高线+数据点的拓扑视图方案

完全可以实现,核心是先把你的20×100的DataFrame转换成contour要求的等尺寸X、Y、Z数组,再叠加散点图显示原始数据点,具体操作如下:

1. 构造匹配尺寸的X、Y网格

你的DataFrame行对应Y轴、列对应X轴,直接用numpy.meshgrid生成和Z同维度的网格数组:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 假设你的DataFrame名为df
x = np.arange(df.shape[1])  # 生成100个X轴刻度
y = np.arange(df.shape[0])  # 生成20个Y轴刻度
X, Y = np.meshgrid(x, y)    # 得到20×100的X、Y网格
Z = df.values               # 提取DataFrame的值作为Z数组,尺寸20×100

2. 绘制等高线+原始数据点

先画等高线(填充或线条式都可以),再用散点图叠加数据点:

plt.figure(figsize=(12, 6))
# 画填充等高线,用contour则是线条式等高线
contour_plot = plt.contourf(X, Y, Z, cmap='viridis', alpha=0.7)
plt.colorbar(contour_plot)  # 添加颜色条

# 叠加原始数据点:把网格数组展平成一维
plt.scatter(X.flatten(), Y.flatten(), c=Z.flatten(), 
            cmap='viridis', edgecolor='white', s=15)

plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('等高线+原始数据点拓扑视图')
plt.show()

3. 不规则刻度数据的适配

如果你的X/Y轴不是均匀刻度(比如是时间序列、非均匀采样的位置),只需要把x、y换成实际的刻度值即可:

# 用DataFrame的列名作为X轴实际刻度,索引作为Y轴实际刻度
x = df.columns.values
y = df.index.values
X, Y = np.meshgrid(x, y)

4. 非网格数据的替代方案:tricontour

如果你的数据是真正的不规则散点(非结构化网格),可以用tricontour/tricontourf,无需构造规则网格,直接传入展平后的一维数组:

plt.figure(figsize=(12, 6))
tricontour_plot = plt.tricontourf(X.flatten(), Y.flatten(), Z.flatten(), 
                                  cmap='viridis', alpha=0.7)
plt.colorbar(tricontour_plot)
plt.scatter(X.flatten(), Y.flatten(), c=Z.flatten(), 
            cmap='viridis', edgecolor='white', s=15)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:48:22