Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyplot contourf: How can I make the colors in the chart continuous?

When I use contourf, matplotlib chooses to group the values into similar regions and color those regions. How can I make this plot show the full spectrum of different values? In the code below, I want the colors to be continuous, so that sun over the hill is a gradient of increasing colors, instead of these sudden changes in color.

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10.0 * (Z2 - Z1)
CS = plt.contourf(X, Y, Z, vmin = 0., vmax = 3., cmap=plt.cm.coolwarm)
plt.show()

enter image description here

like image 262
kilojoules Avatar asked Jan 03 '23 15:01

kilojoules


2 Answers

A quick workaround would be to make the levels that the contour plot uses very small. Don't use vmin and vmax.

Z = 10.0 * (Z2 - Z1)
clev = np.arange(Z.min(),Z.max(),.001) #Adjust the .001 to get finer gradient
CS = plt.contourf(X, Y, Z, clev, cmap=plt.cm.coolwarm)
plt.show()

EDIT If you just want the top part more continous play around with the lower and upper bounds of the contour levels.

Z = 10.0 * (Z2 - Z1)
clev = np.arange(0,Z.max(),.001) #Adjust the .001 to get finer gradient
CS = plt.contourf(X, Y, Z, clev, cmap=plt.cm.coolwarm,extend='both')
plt.show()

enter image description here

like image 89
BenT Avatar answered Jan 13 '23 09:01

BenT


By definition of the word "contour," contourf plots and fills discrete contours. You may want to consider plt.imshow instead.

plt.imshow(Z, vmin = 0., vmax = 3., cmap=plt.cm.coolwarm, origin='lower', 
           extent=[X.min(), X.max(), Y.min(), Y.max()])
plt.show()

enter image description here

like image 35
DYZ Avatar answered Jan 13 '23 07:01

DYZ