Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay Contour Plots in Matplotlib

I need to compare 2 dimensional distributions of 2 groups.

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)

enter image description here

like image 861
Chris Avatar asked Mar 04 '17 23:03

Chris


People also ask

How do you add a Colorbar to a contour plot in Python?

A color bar can be added to the filled contour plot using either the pyplot. colorbar() function or the figure. colorbar() method.

What is Contourf?

contourf( Z ) creates a filled contour plot containing the isolines of matrix Z , where Z contains height values on the x-y plane. MATLAB® automatically selects the contour lines to display. The column and row indices of Z are the x and y coordinates in the plane, respectively.


1 Answers

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.

If you replace:

plt.contourf(xx, yy, f, cmap=cmap, alpha=0.5)

with:

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: enter image description here

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

like image 82
Douglas Dawson Avatar answered Sep 27 '22 17:09

Douglas Dawson