包含线图和热图的Python子图

时间:2016-04-08 17:22:15

标签: python image subplot colorbar

我想在一个图中绘制两个子图,一个是简单的折线图y = f(x),另一个是2D热图,like the one shown here

但是我希望在第二个图中添加一个颜色条。我使用的代码是:

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()

但是这会给出错误消息

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

我该怎么办?

并且无需手动调整子图参数is shown here即可获得程序的输出。这两个地块的大小非常不等。有没有办法在程序本身中提到所需的子图图像大小?

1 个答案:

答案 0 :(得分:0)

添加色条时,通常会将变量分配给imshow返回的图像,例如下面使用的img = sub2.imshow(z)。然后,您可以通过告知plt.colorbar图像和颜色条的轴(在您的情况下为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)

关于更改子图的大小,请参阅this post