Skip to main content
 首页 » 编程设计

python之如何在不同的子图中绘制 contourf colorbar之matplotlib

2025年05月04日10unruledboy

这是一个与 "How to plot pcolor colorbar in a different subplot - matplotlib" 非常相似的问题.我正在尝试绘制一个填充轮廓图和一个带有共享轴的线图和一个单独的子图中的颜色条(即它不会占用 contourf 轴的空间,从而破坏 x 轴共享)。但是,我的代码中的 x 轴不能很好地重新缩放:

import numpy as np 
import matplotlib as mpl 
import matplotlib.pyplot as plt 
 
z = np.random.rand(20, 20) 
x, y = np.arange(20), np.arange(20) 
y2 = np.random.rand(20) 
fig = plt.figure(figsize=(8, 8)) 
gs = mpl.gridspec.GridSpec(2, 2, height_ratios=[1, 2], width_ratios=[2, 1]) 
ax1 = fig.add_subplot(gs[1, 0]) 
ax2 = fig.add_subplot(gs[0, 0], sharex=ax1) 
ax3 = fig.add_subplot(gs[1, 1]) 
cont = ax1.contourf(x, y, z, 20) 
plt.tick_params(which='both', top=False, right=False) 
ax2.plot(x, y2, color='g') 
plt.tick_params(which='both', top=False, right=False) 
cbar = plt.colorbar(cont, cax=ax3) 
cbar.set_label('Intensity', rotation=270, labelpad=20) 
plt.tight_layout() 
plt.show() 

生成一个从 0 到 20(含)而不是 0 到 19 的 x 轴,这意味着填充等高线图中有难看的空白。注释掉上面代码中的 sharex=ax1 意味着等值线图的 x 轴缩放得很好,但它上面的线图和 plt.tick_params 代码对任一轴都没有影响。

有没有办法解决这个问题?

请您参考如下方法:

您还可以为该轴上的所有后续绘图调用关闭 x 轴的自动缩放,以便它保持由 contourf 和 sharex=True 设置的范围:

ax2.set_autoscalex_on(False) 

这甚至发生在您调用 ax2.plot() 之前,我认为它比调用 ax2.set_xlim(0, 19) 更好,因为您不需要了解可能需要的 x 轴的实际限制是多少。


import numpy as np 
import matplotlib as mpl 
import matplotlib.pyplot as plt 
from mpl_toolkits.axes_grid1.inset_locator import inset_axes 
  
z = np.random.rand(20, 20) 
x, y = np.arange(20), np.arange(20) 
y2 = np.random.rand(20) 
fig = plt.figure(figsize=(8, 8)) 
gs = mpl.gridspec.GridSpec(2, 1, height_ratios=[1, 2], width_ratios=[2]) 
ax1 = fig.add_subplot(gs[1, 0]) 
ax2 = fig.add_subplot(gs[0, 0], sharex=ax1) 
cont = ax1.contourf(x, y, z, 20) 
plt.tick_params(which='both', top=False, right=False) 
 
ax2.set_autoscalex_on(False) 
ax2.plot(x, y2, color='g') 
 
axins = inset_axes(ax1, 
           width="5%", # width = 10% of parent_bbox width 
           height="100%", # height : 50% 
           loc=6, 
           bbox_to_anchor=(1.05, 0., 1, 1), 
           bbox_transform=ax1.transAxes, 
           borderpad=0, 
       ) 
 
cbar = plt.colorbar(cont, cax=axins) 
plt.show()