Matplotlib 将子图标题对齐到图的顶部

问题描述 投票:0回答:1

给出以下最小示例,如何使子图标题垂直对齐(而不移动子图本身)?我需要将纵横比设置为“相等”,这样绘图就不会被拉伸。我故意选择不同尺度的数据。

import numpy as np
import matplotlib.pyplot as plt

data1 = np.random.multivariate_normal(mean=[0,0],cov=np.diag([5,2]),size=50)
data2 = np.random.multivariate_normal(mean=[5,3],cov=np.diag([10,20]),size=50)
data3 = np.random.multivariate_normal(mean=[-8,7],cov=np.diag([1,7]),size=50)

fig, (ax1,ax2,ax3) = plt.subplots(1,3,figsize=(5,2))

ax1.scatter(data1[:,0],data1[:,1])
ax2.scatter(data2[:,0],data2[:,1])
ax3.scatter(data3[:,0],data3[:,1])

ax1.set_aspect('equal')
ax2.set_aspect('equal')
ax3.set_aspect('equal')

ax1.set_title('Title 1')
ax2.set_title('Title 2')
ax3.set_title('Title 3')

plt.show()

编辑:问题已结束,我不知道为什么。我要求的是对齐多个子图的标题而不移动图本身。我认为任何建议的问题都与我的请求无关。

python matplotlib subplot
1个回答
1
投票

matplotlib 3.9 中的新增功能

有一种新的图形方法

align_titles
可以自动对齐子图标题,所以现在就像添加一行一样简单:

fig.align_titles()  # requires matplotlib 3.9+

top-aligned titles via fig.align_titles()


matplotlib 3.9 之前

使用子图字幕自动沿 y 顶部对齐并沿 x 居中对齐:

  1. 创建 3
    subfigures
    (需要 matplotlib 3.4.0+)
  2. 为每个子图添加 100% 宽度轴
  3. 为每个子图添加
    suptitle

字幕将与图形顶部对齐并与轴居中对齐(因为轴的宽度为 100%):

fig = plt.figure(constrained_layout=True, figsize=(10, 4))

# create 3 subfigs (width padding=30%)
sf1, sf2, sf3 = fig.subfigures(1, 3, wspace=0.3)

# add an axes to each subfig (left=0%, bottom=0%, width=100%, height=90%)
ax1 = sf1.add_axes([0, 0, 1, 0.9])
ax2 = sf2.add_axes([0, 0, 1, 0.9])
ax3 = sf3.add_axes([0, 0, 1, 0.9])

ax1.scatter(data1[:, 0], data1[:, 1])
ax2.scatter(data2[:, 0], data2[:, 1])
ax3.scatter(data3[:, 0], data3[:, 1])

ax1.set_aspect('equal')
ax2.set_aspect('equal')
ax3.set_aspect('equal')

# plot suptitle per subfig
sf1.suptitle('suptitle 1')
sf2.suptitle('suptitle 2')
sf3.suptitle('suptitle 3')

plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.