简体   繁体   English

如何在不同的子图中绘制pcolor colorbar - matplotlib

[英]How to plot pcolor colorbar in a different subplot - matplotlib

I am trying to split my plots in different subplots.. What I want to achieve is to put a colorbar for a subplot in a different subplot. 我试图在不同的子图中分割我的图。我想要实现的是在不同的子图中为子图放置一个颜色条。 Right now I am using: 现在我正在使用:

# first graph
axes = plt.subplot2grid((4, 2), (0, 0), rowspan=3)
pc = plt.pcolor(df1, cmap='jet')

# second graph
axes = plt.subplot2grid((4, 2), (3, 0))
plt.pcolor(df2, cmap='Greys')

# colorbar
plt.subplot2grid((4, 2), (0, 1), rowspan=3)
plt.colorbar(pc) 

But the result is the following (notice the unwanted empty graph left to the colorbar): 但结果如下(注意留在颜色条上的不需要的空图): 错误的图表

What can I do to print only the colorbar without the left plot? 如果没有左图,我该怎么办才能打印彩条?

Thanks 谢谢

colorbar() accepts a cax keyword argument that allows you to specify the axes object that the colorbar will be drawn on. colorbar()接受一个cax关键字参数,该参数允许您指定将在其上绘制caxaxes对象。

In your case, you would change your colorbar call to the following: 在您的情况下,您可以将colorbar调用更改为以下内容:

# colorbar
axes = plt.subplot2grid((4, 2), (0, 1), rowspan=3)
plt.colorbar(pc, cax=axes)

This will take up the whole space given by subplot2grid ; 这将占用subplot2grid给出的整个空间; you can adjust this to be more reasonable either by having the main axes take up many more columns than the colorbar axes, or by setting up the gridspec explicitly. 你可以通过让主轴占据比色条轴更多的列,或通过明确设置gridspec来调整它更合理。 For example, your figure may be easier to tweak with the following: 例如,使用以下内容可能更容易调整您的数字:

from matplotlib import gridspec
gs = gridspec.GridSpec(2, 2, height_ratios=(3, 1), width_ratios=(9, 1))

# first graph
axes = plt.subplot(gs[0,0])
pc = plt.pcolor(df1, cmap='jet')

# second graph
axes = plt.subplot(gs[1,0])
plt.pcolor(df2, cmap='Greys')

# colorbar
axes = plt.subplot(gs[0,1])
plt.colorbar(pc, cax=axes)

Then you can just change height_ratios and width_ratios to your liking. 然后你可以根据自己的喜好改变height_ratioswidth_ratios

I believe you should use ax instead of cax . 我相信你应该使用ax而不是cax

# colorbar
axes = plt.subplot2grid((4, 2), (0, 1), rowspan=3)
plt.colorbar(pc, ax=axes)

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

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