簡體   English   中英

如何自定義 matplotlib 圖中每個子圖的比例?

[英]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]

子圖

如圖所示,我想將 ax4 擴展到 ax3 一點點,並且 ax3 應該占據圖形的剩余空間。 ax1 和 ax2 應該保持不變。

您必須將嵌套網格規范與width_ratios參數一起使用:

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

暫無
暫無

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

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