如何在Matplotlib中将标题添加到子地块

2024-04-26 09:59:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含许多子图的图

fig = plt.figure(num=None, figsize=(26, 12), dpi=80, facecolor='w', edgecolor='k')
fig.canvas.set_window_title('Window Title')

# Returns the Axes instance
ax = fig.add_subplot(311) 
ax2 = fig.add_subplot(312) 
ax3 = fig.add_subplot(313) 

如何向子地块添加标题

fig.suptitle为所有图添加标题,尽管ax.set_title()存在,但后者不会向我的子图添加任何标题

谢谢你的帮助

编辑: 更正了set_title()的打字错误。谢谢Rutger Kassies


Tags: noneadd标题titlefigpltaxnum
3条回答

速记答案 import matplotlib.pyplot as plt

plt.gca().set_title('title')

例如:

plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...

那么就不需要多余的变量了

ax.set_title()应为单独的子批次设置标题:

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")
    ax.plot(data)

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")
    ax.plot(data)

    plt.show()

你能检查一下这个代码是否适合你吗?也许以后有什么东西会覆盖它们

ax.title.set_text('My Plot Title')似乎也起作用

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()

matplotlib add titles on subplots

相关问题 更多 >