0

I want to draw two subplots in one figure, one being a simple line graph y = f(x), and the other a 2D heatmap, like the one shown here.

But I wish to add a colorbar to the second plot. The code that I use is :

from pylab import*

fig = figure()
sub1 = fig.add_subplot(121)
sub2 = fig.add_subplot(122)

x=linspace(0,10,200)
y=exp(x)
sub1.plot(x,y)

x=linspace(-10,10,200)
y=linspace(-10,10,200)
xx,yy=meshgrid(x,y)
z=sin(xx)+cos(yy)
sub2.imshow(z)
sub2.colorbar()

show()

But this gives an error message

Traceback (most recent call last):
File "ques2.py", line 16, in <module>
    sub2.colorbar()
AttributeError: 'AxesSubplot' object has no attribute 'colorbar'

What can I do?

And the output of the program obtained without manually adjusting the subplot parameters is shown here. The two plots have very inequal sizes. Is there a way to mention the required size of subplot images in the program itself?

kanayamalakar
  • 564
  • 1
  • 11
  • 27

1 Answers1

1

When adding colorbars, it is common practice to assign a variable to the image returned by imshow such as img = sub2.imshow(z) used below. Then you can add a colorbar to your image by telling plt.colorbar the image and the axis for the colorbar (in your case, plt.colorbar(img, ax=sub2).

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
sub1 = fig.add_subplot(121)
sub2 = fig.add_subplot(122)

x = np.linspace(0,10,200)
y = np.exp(x)
sub1.plot(x,y)

x = np.linspace(-10,10,200)
y = np.linspace(-10,10,200)
xx, yy = np.meshgrid(x,y)
z = np.sin(xx)+np.cos(yy)

img = sub2.imshow(z)
plt.colorbar(img, ax=sub2)

As for changing the size of your subplots, see this post.

Community
  • 1
  • 1
lanery
  • 5,222
  • 3
  • 29
  • 43
  • Is there a way to make the colorbar thinner. Because I think it is consuming a lot of space. – kanayamalakar Apr 09 '16 at 03:33
  • colorbar has a nice group of parameters for customizing size: fraction, shrink, and aspect. See [colorbar.make_axes()](http://matplotlib.org/api/colorbar_api.html#matplotlib.colorbar.make_axes) for details. Basically tweak those parameters as necessary until you're satisfied. The other parameters listed in the table are for customizing position/orientation. – lanery Apr 09 '16 at 03:51