在 Matplotlib 中叠加等高线图
Overlay Contour Plots in Matplotlib
我需要比较 2 个组的二维分布。
当我使用 matplotlib.pyplot.contourf
并叠加图时,每个等高线图的背景颜色会填满整个图 space。有什么方法可以使每个等高线图的最低等高线级别透明,以便更容易看到每个等高线的中心?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import scipy.stats as st
def make_cloud(x, y, std, n=100):
x = np.random.normal(x, std, n)
y = np.random.normal(y, std, n)
return np.array(zip(x, y))
def contour_cloud(x, y, cmap):
xmin, xmax = -4, 4
ymin, ymax = -4, 4
xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([xx.ravel(), yy.ravel()])
values = np.vstack([x, y])
kernel = st.gaussian_kde(values)
f = np.reshape(kernel(positions).T, xx.shape)
plt.contourf(xx, yy, f, cmap=cmap, alpha=0.5)
cloud1 = make_cloud(-1, 1, 1)
cloud2 = make_cloud(1, -1, 1)
plt.scatter(x=cloud1[:,0], y=cloud1[:,1])
plt.scatter(x=cloud2[:,0], y=cloud2[:,1], color='red')
fig = plt.gcf()
ax = plt.gca()
contour_cloud(x=cloud1[:, 0], y=cloud1[:, 1], cmap=cm.Blues)
contour_cloud(x=cloud2[:, 0], y=cloud2[:, 1], cmap=cm.Reds)
contourf
中有一些控件需要查看。您可以手动更改不同的级别,您可以更改颜色图 over/under 规格。默认情况下,最低级别以下(或最高级别以上)的区域填充似乎是透明的。
所以,做你想做的最简单的方法是手动指定级别并指定它们,使得 点低于最低级别,但 没有高于最高水平的任何分数。
如果替换:
plt.contourf(xx, yy, f, cmap=cmap, alpha=0.5)
与:
step = 0.02
m = np.amax(f)
levels = np.arange(0.0, m, step) + step
plt.contourf(xx, yy, f, levels, cmap=cmap, alpha=0.5)
生成如下图像:
有关值 over/under 颜色图值的行为的更多详细信息,请参阅 here。
我需要比较 2 个组的二维分布。
当我使用 matplotlib.pyplot.contourf
并叠加图时,每个等高线图的背景颜色会填满整个图 space。有什么方法可以使每个等高线图的最低等高线级别透明,以便更容易看到每个等高线的中心?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import scipy.stats as st
def make_cloud(x, y, std, n=100):
x = np.random.normal(x, std, n)
y = np.random.normal(y, std, n)
return np.array(zip(x, y))
def contour_cloud(x, y, cmap):
xmin, xmax = -4, 4
ymin, ymax = -4, 4
xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([xx.ravel(), yy.ravel()])
values = np.vstack([x, y])
kernel = st.gaussian_kde(values)
f = np.reshape(kernel(positions).T, xx.shape)
plt.contourf(xx, yy, f, cmap=cmap, alpha=0.5)
cloud1 = make_cloud(-1, 1, 1)
cloud2 = make_cloud(1, -1, 1)
plt.scatter(x=cloud1[:,0], y=cloud1[:,1])
plt.scatter(x=cloud2[:,0], y=cloud2[:,1], color='red')
fig = plt.gcf()
ax = plt.gca()
contour_cloud(x=cloud1[:, 0], y=cloud1[:, 1], cmap=cm.Blues)
contour_cloud(x=cloud2[:, 0], y=cloud2[:, 1], cmap=cm.Reds)
contourf
中有一些控件需要查看。您可以手动更改不同的级别,您可以更改颜色图 over/under 规格。默认情况下,最低级别以下(或最高级别以上)的区域填充似乎是透明的。
所以,做你想做的最简单的方法是手动指定级别并指定它们,使得 点低于最低级别,但 没有高于最高水平的任何分数。
如果替换:
plt.contourf(xx, yy, f, cmap=cmap, alpha=0.5)
与:
step = 0.02
m = np.amax(f)
levels = np.arange(0.0, m, step) + step
plt.contourf(xx, yy, f, levels, cmap=cmap, alpha=0.5)
生成如下图像:
有关值 over/under 颜色图值的行为的更多详细信息,请参阅 here。