迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

如何在 Matplotlib 中为所有子图设置一个主标题

作者:迹忆客 最近更新:2023/03/17 浏览次数:

我们使用 set_title(label)title.set_text(label) 方法将标题添加到 Matplotlib 中的各个子图中。但是,要为所有子图添加通用的主标题,我们使用 pyplot.suptitle()Figure.suptitle() 方法。

pyplot.suptitle() 为所有 Matplotlib 子图添加主标题

我们使用 matplotlib.pyplot.suptitle() 方法来设置 Matplotlib 中所有子图共有的主标题。

import numpy as np
import matplotlib.pyplot as plt

m1=1
c1=0

m2 = 2
c2 = 2

m3 = 2
c3 = 1

m4 = 1
c4 = 2

x=np.linspace(0,3,100)
y1 = m1*x + c1
y2 = m2*x + c2
y3 = m3*x + c3
y4 = m4*x + c4

fig, ax = plt.subplots(2, 2,figsize=(10, 8))

ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x,y4)

ax[0, 0].set_title("Line-1")
ax[0, 1].set_title("Line-2")
ax[1, 0].set_title("Line-3")
ax[1, 1].set_title("Line-4")

plt.suptitle('Various Straight Lines',fontsize=20)

fig.tight_layout()
plt.show()

输出:

plt.suptitle 方法将主标题添加到 Matplotlib 中的子图中

在这个例子中,axes.set_title() 方法用于向各个子图添加标题,而 plt.suptitle() 方法用于对所有子图添加通用标题。我们可以使用 plt.suptitle() 方法的各种参数来指定各种参数,例如 x 坐标,y 坐标,字体大小和对齐方式。在这种情况下,设置 fontsize=20 以使主标题与每个子图的标题区分开。

figure.suptitle() 为所有 Matplotlib 子图添加主标题

还可以使用 matplotlib.figure.Figure.suptitle() 方法为图中的所有子图设置主标题。

import numpy as np
import matplotlib.pyplot as plt

m1=1
c1=0

m2 = 2
c2 = 2

m3 = 2
c3 = 1

m4 = 1
c4 = 2

x=np.linspace(0,3,100)
y1 = m1*x + c1
y2 = m2*x + c2
y3 = m3*x + c3
y4 = m4*x + c4

fig, ax = plt.subplots(2, 2,figsize=(10, 8))

ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x,y4)

ax[0, 0].set_title("Line-1")
ax[0, 1].set_title("Line-2")
ax[1, 0].set_title("Line-3")
ax[1, 1].set_title("Line-4")

fig.suptitle('Various Straight Lines',fontweight ="bold")

fig.tight_layout()
plt.show()

输出:

fig.suptitle 方法将主标题添加到 Matplotlib 中的子图中

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便