Matplotlib: contourlevels as strings in colorbar

I am plotting some 2D data with Matplotlib once like pcolor()

, then overlaying that on contour()


enter image description here

When I use colorbar()

, I get either one or the other of the following columns:

colorbars for <code> contour () </code>
        <script async src=
or pcolor ()

" data-src="/img/9a31ef22b96e0f9153a1e4a2852b34b1.png" class=" lazyloaded" src="">

How do I make the horizontal lines for outline levels (left) also appear on the color bar (right)?


source to share

1 answer

Based on your revised question, I understand what you mean. This can be done using add_lines

. This function adds lines from a blank path to the color bar. The documentation can be found here .

So, first defining a color bar based on the graph pcolor

, you can add lines from contour

to that color line:

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

#Generate data
delta = 0.025

x = numpy.arange(-3.0, 3.0, delta)
y = numpy.arange(-2.0, 2.0, delta)

X, Y = numpy.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)

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

PC = ax1.pcolor(X, Y, Z)
CF = ax1.contour(X, Y, Z, 50, colors = "black")

cbar = plt.colorbar(PC)


enter image description here



All Articles