简体   繁体   中英

How to customize the ratio of each subplot in a matplotlib figure?

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec


def format_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)

fig = plt.figure(constrained_layout=True)

gs = GridSpec(2, 2, figure=fig)
ax1 = fig.add_subplot(gs\[0, 0\])
# identical to ax1 = plt.subplot(gs.new_subplotspec((0, 0), colspan=3))
ax2 = fig.add_subplot(gs\[0, 1\])
ax3 = fig.add_subplot(gs\[1, 1\])
ax4 = fig.add_subplot(gs\[1, 0\])
# ax5 = fig.add_subplot(gs\[-1, -2\])

fig.suptitle("GridSpec")
format_axes(fig)

plt.show()][1]][1]

子图

As shown in the picture i want to extend ax4 into ax3 a little bit and ax3 should occupy the remaining space of the figure. The ax1 and ax2 should remain the same.

You have to use nested grid specs together with width_ratios parameter:

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


def format_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i + 1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)


# gridspec inside gridspec
fig = plt.figure()

gs0 = gridspec.GridSpec(2, 1, figure=fig)

gs00 = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs0[0])
gs01 = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs0[1], width_ratios=[2, 1])

ax1 = fig.add_subplot(gs00[:, :-1])
ax2 = fig.add_subplot(gs00[:, -1])

ax3 = fig.add_subplot(gs01[:, :-1])
ax4 = fig.add_subplot(gs01[:, -1])

plt.suptitle("GridSpec Inside GridSpec")
format_axes(fig)

plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM