本文介绍了Matplotlib中的叠加轮廓图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to compare 2 dimensional distributions of 2 groups.

当我使用 matplotlib.pyplot.contourf 并覆盖图,每个轮廓图的背景色将填充整个图空间。有什么方法可以使每个轮廓图的最低轮廓线透明,以便更容易看到每个轮廓线的中心?

When I use matplotlib.pyplot.contourf and overlay the plots, the background color of each contour plot fills the entire plot space. Is there any way to make the lowest contour level transparent for each contour plot so that it's easier to see the center of each contour?

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 ,您需要查看一些控件。您可以手动更改不同的级别,还可以更改颜色表的规格。默认情况下,最低水平(或最高水平)以下区域的填充似乎是透明的。

There are a few controls you will want to look at for contourf. You can manually change the different levels and you can change the color map over/under specifications. By default, the fill for areas under the lowest level (or above the max) seems to be transparent.

因此,执行所需操作的最简单方法是手动指定级别并指定级别,以使在最低级别以下的地方有 个点,但并非高于最高水平的任何点。

So, the easiest way to do what you want is to manually specify the levels and specify them such that there are points below the lowest level, but are not any points above the highest level.

如果您替换:

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)

产生的图像如下:

produces an image like:

有关颜色表值上方/下方的值的行为的更多详细信息,请参见。

For more details on the behavior for values over/under the colormap values, see here.

这篇关于Matplotlib中的叠加轮廓图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:27