简体   繁体   English

使用matplotlib在Python中正确对齐极坐标图

[英]Correctly aligning polar plots in Python with matplotlib

fig, ax = plt.subplots(1, 2, subplot_kw=dict(projection='polar'))

ax[0].set_theta_zero_location("N")
ax[0].set_theta_direction(-1)
cax = ax[0].contourf(theta, r, values_2d,100)
cb = fig.colorbar(cax)
cb.set_label("Distance")

dax = ax[1].contourf(theta, r, d_values_2d,2)
db = fig.colorbar(dax)
db.set_label("Gradient")

plt.tight_layout(pad=0.4, w_pad=0.5)

plt.show()

The above figure has two plots on it. 上图有两个图。 I can't find a way to make the colorbar sit with each respective figure, though. 但是,我找不到一种方法来使colorbar与每个相应的图放在一起。 Also, they're different sizes, why? 而且,它们的大小不同,为什么呢?

在此处输入图片说明

You can pass the Axes instance to which the colorbar should be attached to fig.colorbar() with the keyword ax . 您可以使用关键字axfig.colorbar()附加到其上的Axes实例传递给fig.colorbar() From the documentation: 从文档中:

ax : Axes, list of Axes, optional 轴:轴,轴列表,可选

Parent axes from which space for a new colorbar axes will be stolen. 父轴,新色条轴的空间将被窃取。 If a list of axes is given they will all be resized to make room for the colorbar axes. 如果给出了轴列表,则将全部调整它们的大小,以便为色条轴腾出空间。

Also, to avoid overlap, you can pass the keyword pad . 另外,为避免重叠,您可以传递关键字pad Here an a little bit altered version of your code: 这是您的代码的一些改动版本:

from matplotlib import pyplot as plt
import numpy as np

#the coordinates
theta = np.linspace(0,2*np.pi, 100)
r = np.linspace(0,1,100)

#making up some data    
theta,r = np.meshgrid(theta,r)
values_2d = np.sin(theta)*np.exp(-r)

d_values_2d = np.cos(theta)*np.sqrt(r)

fig, ax = plt.subplots(
    1, 2, subplot_kw=dict(projection='polar'),
    figsize = (10,4)
)

ax[0].set_theta_zero_location("N")
ax[0].set_theta_direction(-1)
cax = ax[0].contourf(theta, r, values_2d,100)

#the first altered colorbar command
cb = fig.colorbar(cax, ax = ax[0], pad = 0.1)
cb.set_label("Distance")

dax = ax[1].contourf(theta, r, d_values_2d,2)

#the second altered colorbar command
db = fig.colorbar(dax, ax = ax[1], pad = 0.1)
db.set_label("Gradient")

plt.tight_layout(pad=0.4, w_pad=0.5)

plt.show()

This gives the following result: 得到以下结果: 以上代码的结果

As to why you get the figure you get with your original code, I'm guessing that without the ax keyword, colorbar has to guess where to put the colorbar and it uses either the current active Axes instance or the last created one. 至于为什么要用原始代码得到图形,我猜想如果没有ax关键字, colorbar必须猜测将colorbar放在哪里,并且它使用当前活动的Axes实例或最后一个创建的实例。 Also, as both colorbars are attached to the same Axes there is less room for the actual plot, which is why the right plot in your example is way smaller than the left one. 另外,由于两个颜色条都连接到相同的轴,所以实际图的空间较小,这就是示例中右图比左图小得多的原因。

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

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