如何在Matplotlib中为子批次添加标题?

2024-04-26 12:20:09 发布

您现在位置: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()的输入错误。谢谢拉特格·卡西


Tags: noneadd标题titlefigplt数字ax
3条回答

假设的速记回答 import matplotlib.pyplot as plt

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

如所示:

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

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

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

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

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

相关问题 更多 >