4

I'm plotting some 2D data with Matplotlib once as pcolor(), then superposing this with contour().

enter image description here

When I use colorbar() I get either one or the other of the following colorbars:

colorbars for <code>contour()</code> or <code>pcolor()</code>

How do I make the horizontal lines for the contour levels(left) also show in the colored bar(right)?

tmartin
  • 311
  • 5
  • 15

1 Answers1

4

Based from your revised question I get what you mean. This can still be done using add_lines. This function adds the lines from a non-filled contour plot to a colorbar. The documentation can be found here.

So, by first defining the colorbar based on your pcolor plot you can later add the lines from contour to that colorbar:

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)

#Plot
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)
cbar.add_lines(CF)

plt.show()

enter image description here

The Dude
  • 3,795
  • 5
  • 29
  • 47
  • That's not exactly what I meant. I've revised the question for clarification. – tmartin Sep 24 '14 at 14:29
  • Please see my revised answer – The Dude Sep 24 '14 at 14:40
  • Your answer helped me a lot. You have to create the colorbar for the pcolor figure and then add the lines for the contour with `add_lines()`. If you revise your answer I'll accept it. – tmartin Sep 24 '14 at 14:45
  • That is exactly how you should solve your problem! This is also what I am referring to with my previous comment. – The Dude Sep 24 '14 at 14:51
  • 1
    As per this SO Q&A: https://stackoverflow.com/questions/63623170/an-equivalent-function-to-matplotlib-mlab-bivariate-normal As of Matplotlib 3.1, mlab.bivariate_normal is removed from matplotlib's library. But scipy.stats.multivariate_normal() can be used to replace matplotlib.mlab.bivariate_normal(). Call signature also changes - see link for details. – Biggsy Sep 22 '21 at 09:22