在极坐标等高线图中添加颜色条
接着我之前的问题,我想知道怎么正确地创建多个极坐标的contourf
子图,并给它们加一个统一的颜色条。我试了下面这种方法:
import numpy as np
import matplotlib.pyplot as plt
#-- Generate Data -----------------------------------------
# Using linspace so that the endpoint of 360 is included...
azimuths = np.radians(np.linspace(0, 360, 100))
zeniths = np.arange(0, 70, 10)
r, theta = np.meshgrid(zeniths, azimuths)
values1 = np.random.random((azimuths.size, zeniths.size))
values2 = np.random.random((azimuths.size, zeniths.size))
#-- Plot... ------------------------------------------------
fig, axs = plt.subplots(1, 2, subplot_kw=dict(projection='polar'))
p1 = axs[0].contourf(theta, r, values1, 100)
p2 = axs[1].contourf(theta, r, values2, 100)
cbar = plt.colorbar(p2, ax=axs[1])
plt.show()
但是右边的极坐标图比左边的小:
注意,如果把colorbar
这一行注释掉,两个子图的大小就会一样:
我该怎么让它们的大小一样呢?还有,怎么把颜色条调整得和极坐标图的圆圈一样高?谢谢!
2 个回答
2
使用 subplot2grid
来创建多个图表,并把 colorbar
放在一个不同的区域:
azimuths = np.radians(np.linspace(0, 360, 100))
zeniths = np.arange(0, 70, 10)
r, theta = np.meshgrid(zeniths, azimuths)
values1 = np.random.random((azimuths.size, zeniths.size))
values2 = np.random.random((azimuths.size, zeniths.size))
#-- Plot... ------------------------------------------------
#fig, axs = plt.subplots(1, 2, subplot_kw=dict(projection='polar'))
fig = plt.figure()
ax1=plt.subplot2grid((1,10), (0, 0), colspan=4, projection='polar')
ax2=plt.subplot2grid((1,10), (0, 4), colspan=4, projection='polar')
ax3=plt.subplot2grid((1,15), (0, 14), colspan=1)
p1 = ax1.contourf(theta, r, values1, 100)
p2 = ax2.contourf(theta, r, values2, 100)
cbar = plt.colorbar(p2, cax=ax3)
plt.show()
4
为此,你需要做一些调整。
与其使用色彩图(colormap),因为它会在图上添加一个新的坐标轴来显示色彩图的比例,不如直接定义一个绘图区域来展示色彩图。
我稍微修改了一下你的代码,以便实现这个目的。
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
#-- Generate Data -----------------------------------------
# Using linspace so that the endpoint of 360 is included...
azimuths = np.radians(np.linspace(0, 360, 100))
zeniths = np.arange(0, 70, 10)
r, theta = np.meshgrid(zeniths, azimuths)
values1 = np.random.random((azimuths.size, zeniths.size))
values2 = np.random.random((azimuths.size, zeniths.size))
#-- Plot... ------------------------------------------------
fig, axs = plt.subplots(1, 2, figsize=(12,5),subplot_kw=dict(projection='polar'))
p1 = axs[0].contourf(theta, r, values1, 100)
p2 = axs[1].contourf(theta, r, values2, 100)
#-- obtaining the colormap limits
vmin,vmax = p2.get_clim()
#-- Defining a normalised scale
cNorm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
#-- Creating a new axes at the right side
ax3 = fig.add_axes([0.9, 0.1, 0.03, 0.8])
#-- Plotting the colormap in the created axes
cb1 = mpl.colorbar.ColorbarBase(ax3, norm=cNorm)
fig.subplots_adjust(left=0.05,right=0.85)
plt.show()
希望这能帮到你