簡體   English   中英

Matplotlib:如何刪除一組子圖之間的間距

[英]Matplotlib: how to remove spacing between a group of subplots

我有一系列使用 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 圖並在上方和右側顯示相關的一維圖(粗略地顯示這種用油漆粗略繪制的數據):

我打算的子情節布局

我感謝您對此的任何幫助。 似乎無法找到有關此類事情的文檔。 謝謝!

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

在此處輸入圖片說明

此外,您可以創建一個 subgridspec,如

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 教程提供了一個很好的概述,其中包含許多關於此問題的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM