Mohammad ElNesr
Mohammad ElNesr

Reputation: 2667

How to color contour labels by a colormap?

I have a contour plot that I color using the Yellow-Green color map named YlGn The labels at the darker fields do not appear well, as they are black.

Is there a method to color the labels in the inverse of the used colormap? i.e., to color the 0.39 label in white, and the 0.15 label in dark green, and the labels in-between accordingly.

enter image description here

I used CS3 = plt.contourf(X, Z, M, levels, cmap=plt.cm.YlGn, extend='both') for the filled contour and CS4 = plt.contour(CS3, colors=('k',), linewidths=(1,)) for the line contour, and finally plt.clabel(CS4, linewidths=2, fmt='%2.2f', colors='k', fontsize=14) for the labels.

However when I tried to add cmap=plt.cm.YlGn_r and removed the colors='k' to the labels (to reverse the colors) it did nothing.

Note: The codes used here are partially taken from this documentation page, but with some modifications to fit my data.

Here are some data to try at a Jupyter notebook:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'

delta = 0.025
x = np.arange(1.0, 3.0, delta)
y = np.arange(1.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)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)
plt.figure()
CS = plt.contour(X, Y, Z, cmap=plt.cm.YlGn_r)
CS2 = plt.contourf(X, Y, Z, color='k')
plt.clabel(CS, fontsize=10,color='k')
plt.title('Simplest default with labels')

Upvotes: 1

Views: 5887

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339290

I guess you mixed up the arguments to contour and contourf. Applying the reverse colormap to contour works fine.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import mlab 

delta = 0.025
x = np.arange(1.0, 3.0, delta)
y = np.arange(1.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)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)
plt.figure()

CS2 = plt.contourf(X, Y, Z, cmap=plt.cm.YlGn_r)
CS = plt.contour(X, Y, Z, cmap=plt.cm.YlGn)
plt.clabel(CS, fontsize=10)

plt.title('Simplest default with labels')

plt.show()

enter image description here

To use the same colormap for the lines as for the fills, but then use a different colormap for the labels, you need to define the colors manually. But the use of the existing levels helps you do that quite efficiently.

CS2 = plt.contourf(X, Y, Z, cmap=plt.cm.YlGn_r)
CS = plt.contour(CS2, cmap=plt.cm.YlGn_r)
plt.clabel(CS, fontsize=10, colors=plt.cm.Reds(CS.norm(CS.levels)))

enter image description here

Upvotes: 4

Related Questions