简体   繁体   English

包含折线图和热图的Python子图

[英]Python subplots containing line-graph and heatmaps

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 . 我想在一个图中绘制两个子图,一个是简单的折线图y = f(x),另一个是二维热图, 如此处所示

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? 有没有办法在程序本身中提及所需的子图图像大小?

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. 添加颜色条时,通常的做法是为imshow返回的图像分配一个变量,例如下面使用的img = sub2.imshow(z) 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 ). 然后,您可以通过告诉plt.colorbar图像和plt.colorbar的轴(在您的情况下为plt.colorbar(img, ax=sub2 ))向图像添加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 . 至于更改子图的大小,请参阅这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM