2017-03-04 161 views
1

我需要比较2组的2维分布。覆盖Matplotlib中的轮廓图

当我使用matplotlib.pyplot.contourf并叠加图时,每个等值线图的背景色将填充整个绘图空间。有没有办法让每个轮廓图的最低轮廓线水平透明,以便更容易看到每个轮廓的中心?

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) 

enter image description here

回答

1

有,你会想看看在contourf一些控件。您可以手动更改不同的级别,并且可以在规格上/下更改颜色映射。默认情况下,最低级别(或最高级别以下)区域的填充似乎是透明的。

所以,做你想做的最简单的方法是手动指定级别,并且指定其中,使得低于最低水平点,但高于最高级别的任何点。

如果更换:

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) 

产生图像,如: enter image description here

对于上/下的颜色映射值的行为的详细信息的价值,见here

+0

美丽,谢谢! – Chris