【问题标题】:Matplotlib: how to remove spacing between a group of subplotsMatplotlib:如何删除一组子图之间的间距
【发布时间】:2019-09-04 12:56:36
【问题描述】:

我有一系列使用 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()

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

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

【问题讨论】:

  • 建议将其安排为 3x1 grodspwc,然后三个较小的地块组成一个 subgridsepc,可能是双嵌套以获得较小的水平尺寸。然后你可以为小的 subgridspec 设置诸如间距和高度比之类的东西。

标签: python matplotlib data-visualization


【解决方案1】:

您可以使用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()

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

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()

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2023-02-09
  • 2019-06-13
  • 2020-02-26
  • 2023-04-10
  • 1970-01-01
  • 2017-03-09
相关资源
最近更新 更多