首页 > 解决方案 > Matplotlib:来自两个数组的高斯等高线图

问题描述

我有两个 numpy 数组,一个形状 (239,2) 包含我的数据点,另一个形状 (239,) 包含这些数据点的二元高斯密度值。

如何使用 Matplotlib 在数据点的散点图上为我的密度函数创建等高线图?

目前我TypeError: Input z must be a 2D array在尝试使用contourmatplotlib 中的函数时得到一个 , 。如果我有每个数据点的 X 轴、Y 轴和概率密度值,为什么 z 必须是 2D 的?我需要以某种方式进行插值吗?

fig, ax = plt.subplots()
ax.scatter(X[:,0], X[:,1], c='green')
ax.scatter(X[:,0], X[:,1], c='orange')
ax.contour(z, X[:,0], X[:,1])           <-- TypeError happens here
plt.show()

X 的形状为 (239, 2),z 的形状为 (239,)

标签: pythonmatplotlib

解决方案


contour needs z values on a regular 2D grid, perhaps your data is better suitable for the tricontour method:

from matplotlib.tri import Triangulation
import matplotlib.pyplot as plt
import numpy as np

x = np.random.random((100))
y = np.random.random((100))
z = x * y

tri = Triangulation(x,y)

plt.tricontour(tri, z, )
plt.scatter(x,y, c=z)
plt.show()

推荐阅读