gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:42:20 34 4
gpt4 key购买 nike

这是一个与 "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 代码对任一轴都没有影响。

plot

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

最佳答案

您还可以为该轴上的所有后续绘图调用关闭 x 轴的自动缩放,以便它保持由 contourfsharex=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()

example

关于python - 如何在不同的子图中绘制 contourf colorbar - matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32455162/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com