pandas - 如何从数据(表)中用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()
解决方案
要制作等高线图,z
需要是包含所有点值的二维矩阵(x,y)
。您可以将等高线图所需的数据视为一个 DataFrame,其中索引为x
,列为y
,值为z
。所以z
需要一个二维数组 shape (x.size, y.size)
。
由于您z
不是二维矩阵而是一维数组,因此您不能有等高线图。
例如,您可以做的是relplot
withhue
和/或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()
推荐阅读
- javascript - 如何过滤来自firebase的数据?
- haskell - 如何只显示重复的元素?
- spring-boot - Spring Boot 应用程序在作为容器运行时无法连接到在 docker 容器中运行的 mysql 数据库
- jsonschema - Json Schema:根据使用位置验证类型
- python - 获取浮动 hbar 图上的条数的计数/总和
- mongodb - 只有当 mongodb 中的字段不为空时,mongodb 中是否有办法将过滤器/条件添加到现有过滤器
- html - 如何显示前三个徽标等待一秒钟并无限循环显示下三个徽标?
- jenkins - 如何在所有 jenkins 项目中获取/访问 HTTP 代理配置?
- node.js - 为什么 n 抛出错误?错误:需要 sudo(或更改所有权,或定义 N_PREFIX)
- javascript - 如何在 NodeJS 中查找中英文字符?