2017-03-04 157 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