python matplotlib,特定子图之间的间距

hfwmuf9z  于 2023-08-06  发布在  Python
关注(0)|答案(2)|浏览(147)

因此,创建了8个子图,我希望在子图2和子图3之间以及子图6和7之间有一个间距。大概是这样的:

的数据
这些都是我得到的情节,我正在想办法实现这一点。



下面是我的代码:

import matplotlib.pyplot as plt
import numpy as np
# Create the main subplot
fig, axs = plt.subplots(2, 4, figsize=(20, 18))

 # Subplot 1
ax1 = axs[0, 0]
ax1.plot(np.random.rand(10))
ax1.set_title('Subplot 1')
ax1.set_position([0.0, 0.6, 0.125, 0.125])
# Subplot 2
ax2 = axs[0, 1]
ax2.plot(np.random.rand(10))
ax2.set_title('Subplot 2')
ax2.set_position([0.25, 0.6, 0.125, 0.125])

# Subplot 3
ax3 = axs[0, 2]
ax3.plot(np.random.rand(10))
ax3.set_title('Subplot 3')
ax3.set_position([0.75, 0.6, 0.125, 0.125])
# Subplot 4
ax4 = axs[0, 3]
ax4.plot(np.random.rand(10))
ax4.set_title('Subplot 4')
ax4.set_position([1, 0.6, 0.125, 0.125])

# Subplot 5
ax5 = axs[1, 0]
ax5.plot(np.random.rand(10))
ax5.set_title('Subplot 5')
ax5.set_position([0, 0.3, 0.125, 0.125])

# Subplot 6
ax6 = axs[1, 1]
ax6.plot(np.random.rand(10))
ax6.set_title('Subplot 6')
ax6.set_position([0.25, 0.3, 0.125, 0.125])

# Subplot 7
ax7 = axs[1, 2]
ax7.plot(np.random.rand(10))
ax7.set_title('Subplot 7')
ax7.set_position([0.75, 0.3, 0.125, 0.125])

# Subplot 8
ax8 = axs[1, 3]
ax8.plot(np.random.rand(10))
ax8.set_title('Subplot 8')
ax8.set_position([1, 0.3, 0.125, 0.125])

# Adjust the spacing between subplots
fig.tight_layout()

fig.subplots_adjust(wspace=0, hspace=0.4)

# Display the plot
plt.show()

字符串

vdgimpew

vdgimpew1#


的数据
您可以使用Matplotlib的新特性subfigures

import matplotlib.pyplot as plt

fig = plt.figure()
fig.suptitle('fig title')
sfigs = fig.subfigures(2,2)

for sfig in sfigs.flatten():
    ax0, ax1 = sfig.subplots(1, 2)
    ax0.plot((0,1),(0,1)) ; ax1.plot((0,1),(0,1))
    sfig.subplots_adjust(wspace=0, hspace=0)
    sfig.suptitle('aaa')

plt.show()

字符串

w8biq8rn

w8biq8rn2#

使用subplot2grid是另一种方法:

ax1 = plt.subplot2grid((11, 9), (0, 0), rowspan=5, colspan=2)
ax2 = plt.subplot2grid((11, 9), (0, 2), rowspan=5, colspan=2)
ax3 = plt.subplot2grid((11, 9), (0, 5), rowspan=5, colspan=2)
ax4 = plt.subplot2grid((11, 9), (0, 7), rowspan=5, colspan=2)
ax5 = plt.subplot2grid((11, 9), (6, 0), rowspan=5, colspan=2)
ax6 = plt.subplot2grid((11, 9), (6, 2), rowspan=5, colspan=2)
ax7 = plt.subplot2grid((11, 9), (6, 5), rowspan=5, colspan=2)
ax8 = plt.subplot2grid((11, 9), (6, 7), rowspan=5, colspan=2)

字符串


的数据
例如,对于ax1(11, 9),主绘图窗口分为11行和9列。第二元组(0, 0)指定每个框的左上角的位置,例如,行0 &列0。rowspancolspan是创建每个框的行数和列数。

相关问题