1

I'm plotting some 2D data as shown. The axes aspect should be equal and the axes range should differ.

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

#Generate data
delta = 0.025

x = numpy.arange(-5.0, 5.0, delta)
y = numpy.arange(-5.0, 5.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,  aspect='equal')

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

plt.xlim(-4.0, 4.0)
plt.ylim(-2.0, 2.0)

cbar = plt.colorbar(PC)
cbar.add_lines(CF)

plt.show()

enter image description here

How can I make the colobar has the same height as the plotted data?

tmartin
  • 311
  • 5
  • 15

1 Answers1

4

You can do this using make_axes_locatable:

import numpy
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from mpl_toolkits.axes_grid1 import make_axes_locatable

#Generate data
delta = 0.025

x = numpy.arange(-5.0, 5.0, delta)
y = numpy.arange(-5.0, 5.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,  aspect='equal')

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

plt.xlim(-4.0, 4.0)
plt.ylim(-2.0, 2.0)

divider = make_axes_locatable(ax1)
cax1 = divider.append_axes("right", size="5%", pad=0.05)

cbar = plt.colorbar(PC, cax = cax1)
cbar.add_lines(CF)

plt.show()

enter image description here

The Dude
  • 3,795
  • 5
  • 29
  • 47
  • This will not work for projected axes such as GeoAxes, the call to divider.append_axes() will throw an exception. Fro regular axes will work. – Bogdan Oct 09 '16 at 19:37