首页 > 解决方案 > 如何从数据(表)中用python绘制等高线图?

问题描述

我想使用表格数据绘制等高线图。我有 2 个变量和响应(3 列)。我不明白如何使用它来构建这个情节。我尝试了下面的代码。但我又犯了一个错误:输入 z 必须是 2D,而不是 1D。

feature_x = data.factor1
feature_y = data.factor2
  
# Creating 2-D grid of features
[X, Y] = np.meshgrid(feature_x, feature_y)
  
fig, ax = plt.subplots(1, 1)
  
Z = data.response
  
# plots filled contour plot
ax.contourf(X, Y, Z)
  
ax.set_title('Filled Contour Plot')
ax.set_xlabel('feature_x')
ax.set_ylabel('feature_y')
  
plt.show()

数据 在此处输入图像描述

在此处输入图像描述

标签: pandasmatplotlibplotcontour

解决方案


要制作等高线图,z需要是包含所有点值的二维矩阵(x,y)。您可以将等高线图所需的数据视为一个 DataFrame,其中索引为x,列为y,值为z。所以z需要一个二维数组 shape (x.size, y.size)

由于您z不是二维矩阵而是一维数组,因此您不能有等高线图。

例如,您可以做的是relplotwithhue和/或size

import numpy as np
import pandas as pd
import seaborn as sns

x = np.array([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])
y = np.array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
z = np.array([249, 523, 603, 775, 577, 763, 808, 695, 642, 525, 795, 758])
df = pd.DataFrame({'x':x, 'y':y, 'z':z})

sns.relplot(
    data=df,
    x='x', y='y',
    size='z', sizes=(10, 100),
    hue='z',
    palette='coolwarm',
);

在此处输入图像描述

编辑

但是......如果你正在寻找一个连续的估计,你可以使用gaussian_kde,例如

import scipy.stats as sps
import matplotlib.pyplot as plt

offset = .25
xmin = x.min()-offset
xmax = x.max()+offset
ymin = y.min()-offset
ymax = y.max()+offset

X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([X.ravel(), Y.ravel()])
values = np.vstack([x, y])
kernel = sps.gaussian_kde(values, weights=z)
Z = np.reshape(kernel(positions).T, X.shape)

fig, ax = plt.subplots(figsize=(7, 7))
ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r,
          extent=[xmin, xmax, ymin, ymax],
          aspect='auto'
         )
sns.scatterplot(
    data=df,
    x='x', y='y',
    size='z', sizes=(10, 200),
    color='k'
)
ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])
ax.legend(loc='upper left', bbox_to_anchor=(1,1))
plt.show()

在此处输入图像描述


推荐阅读