gpt4 book ai didi

python - Matplotlib:如何删除一组子图之间的间距

转载 作者:行者123 更新时间:2023-12-01 07:19:11 42 4
gpt4 key购买 nike

我有一系列使用 gridspec 创建的 pyplot 子图。它们之间都有一个 hspace,这很好,但我想保留其中的三个,没有任何空间。有没有办法做到这一点?目前,它们看起来像这样:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()
grid_spec = gridspec.GridSpec(nrows=10, ncols=10)
grid_spec.update(hspace=1.5)

ax1 = plt.subplot(grid_spec[0:4, :])
ax2 = plt.subplot(grid_spec[4:7, :], sharex=ax1)

# I would like to group the next 3 together
# so that they are stacked top to bottom and side by side
ax3 = plt.subplot(grid_spec[7:8, :5])
ax4 = plt.subplot(grid_spec[8:, :5], sharex=ax3)
ax5 = plt.subplot(grid_spec[8:, 5:6], sharey=ax4)

plt.show()

My current subplot layout

我希望它们像这样排列,这样我就可以绘制以下二维 KDE 图,并在上方和右侧显示相关的一维图(粗略地显示这种用油漆粗略绘制的数据):

My intended subplot layout

非常感谢您对此提供的任何帮助。似乎找不到关于此类事情的文档。谢谢!

最佳答案

您可以使用 mpl_toolkits.axes_grid1.make_axes_locatable 来分割 3 x 2 网格子图的区域。

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig = plt.figure()
gs = fig.add_gridspec(nrows=3, ncols=2, hspace=.5,
height_ratios=[4, 3, 3], width_ratios=[7, 4])

ax1 = fig.add_subplot(gs[0, :])
ax2 = fig.add_subplot(gs[1, :], sharex=ax1)


ax3 = fig.add_subplot(gs[2, 0])
div = make_axes_locatable(ax3)
ax4 = div.append_axes("top", "40%", pad=0.2, sharex=ax3)
ax5 = div.append_axes("right", "25%", pad=0.2, sharey=ax3)

ax4.tick_params(labelbottom=False)
ax5.tick_params(labelleft=False)

plt.show()

enter image description here

此外,您还可以创建一个子网格规范,例如

import matplotlib.pyplot as plt
from matplotlib import gridspec

fig = plt.figure()
gs = gridspec.GridSpec(nrows=3, ncols=2, hspace=.5,
height_ratios=[4, 3, 3], width_ratios=[7, 4])

ax1 = fig.add_subplot(gs[0, :])
ax2 = fig.add_subplot(gs[1, :], sharex=ax1)

sub_gs = gridspec.GridSpecFromSubplotSpec(2,2, subplot_spec=gs[2,0], hspace=0.3, wspace=0.1,
height_ratios=[1,3], width_ratios=[3,1])
ax3 = fig.add_subplot(sub_gs[1,0])
ax4 = fig.add_subplot(sub_gs[0,0], sharex=ax3)
ax5 = fig.add_subplot(sub_gs[1,1], sharey=ax3)

ax4.tick_params(labelbottom=False)
ax5.tick_params(labelleft=False)

plt.show()

enter image description here

在这两种情况下,您可能都需要稍微微调参数。一般来说,matplotlib gridspec tutorial提供了一个很好的概述,并提供了有关此问题的许多示例。

关于python - Matplotlib:如何删除一组子图之间的间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57788906/

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