我正在尝试删除两个特定轴之间的垂直空间;然而
plt.figure(layout='constrained')
会阻止 matplotlib.pyplot.subplots_adjust(hspace=0)
。
layout='constrained'
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 8),layout='constrained')
# fig = plt.figure(figsize=(10, 8))
subfigs = fig.subfigures(2, 1)
axsUp = subfigs[0].subplots(1, 3)
subfigsnest = subfigs[1].subfigures(1, 2, width_ratios=[1, 2])
ax = subfigsnest[0].subplots(1)
axsnest = subfigsnest[1].subplots(2, 1, sharex=True)
subfigsnest[1].subplots_adjust(hspace=0)
plt.show()
layout='constrained'
import matplotlib.pyplot as plt
# fig = plt.figure(figsize=(10, 8),layout='constrained')
fig = plt.figure(figsize=(10, 8))
subfigs = fig.subfigures(2, 1)
axsUp = subfigs[0].subplots(1, 3)
subfigsnest = subfigs[1].subfigures(1, 2, width_ratios=[1, 2])
ax = subfigsnest[0].subplots(1)
axsnest = subfigsnest[1].subplots(2, 1, sharex=True)
subfigsnest[1].subplots_adjust(hspace=0)
plt.show()
将
subplots_adjust(hspace=0)
与 layout='constrained'
一起使用不起作用,并且会产生警告 UserWarning:该图使用了与 subplots_adjust 和/或ight_layout 不兼容的布局引擎;不调用 subplots_adjust。.
虽然这个答案不使用
layout='constrained'
,但以下内容可能对大多数人(包括OP)有用。
我建议使用 嵌套
GridSpec
进行设置,其中仅为第二行设置 hspace=0
。这确实确保了所有轴整齐对齐,同时仍然允许 ax5
和 ax6
粘合在一起共享一个公共 x 轴。
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(10, 8))
gs0 = GridSpec(2, 1, figure=fig) # set up two rows
gs1 = gs0[0].subgridspec(1, 3) # set up 1st row such that it has 3 columns
ax1 = fig.add_subplot(gs1[0, 0]) # create ax1
ax2 = fig.add_subplot(gs1[0, 1]) # create ax2
ax3 = fig.add_subplot(gs1[0, 2]) # create ax3
gs2 = gs0[1].subgridspec(2, 3, hspace=0) # set up second row such that it has 2 sub-rows and 3 sub-columns
ax4 = fig.add_subplot(gs2[:, 0]) # create ax4 such that it spans all sub-rows but only 1 sub-column
ax5 = fig.add_subplot(gs2[0, 1:]) # create ax5 in the 1st sub-row but spanning the last 2 sub-columns
ax6 = fig.add_subplot(gs2[1, 1:], sharex=ax5) # create ax6 in the 2nd sub-row but spanning the last 2 sub-columns
ax5.tick_params(labelbottom=False) # remove ax5 x-axis ticks
ax5.set_yticks(ax5.get_yticks()[1:]) # make sure 1st ax5 ticklabel does not overlab with last ax6 ticklabel
ax6.set_yticks(ax6.get_yticks()[:-1]) # make sure last ax6 ticklabel does not overlab with 1st ax5 ticklabel
for i, ax in enumerate([ax1, ax2, ax3, ax4, ax5, ax6]):
ax.text(0.5, 0.5, f"ax{i+1}", transform=ax.transAxes, ha='center', va='center', fontsize='xx-large')