【问题标题】:Overlay Contour Plots in MatplotlibMatplotlib 中的叠加等高线图
【发布时间】:2017-07-24 22:52:55
【问题描述】:

我需要比较两组的二维分布。

当我使用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)

【问题讨论】:

    标签: matplotlib contour


    【解决方案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)
    

    生成如下图像:

    有关颜色图值上方/下方的值行为的更多详细信息,请参阅here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      相关资源
      最近更新 更多