我有一个包含许多子图的图。
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
答案 0 :(得分:192)
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()
您可以查看此代码是否适合您吗?也许有些东西会在以后覆盖它们?
答案 1 :(得分:80)
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()
答案 2 :(得分:22)
假设的简写回答
import matplotlib.pyplot as plt
:
plt.gca().set_title('title')
如:
plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...
然后不需要多余的变量。
答案 3 :(得分:5)
我倾向于越来越使用的一种解决方案是:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2) # 1
for i, ax in enumerate(axs.ravel()): # 2
ax.set_title("Plot #{}".format(i)) # 3
答案 4 :(得分:3)
如果要缩短它,可以写:
PrintStream
它可能不太清楚,但是您不需要更多的行或变量
答案 5 :(得分:1)
fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=1, ncols=4,figsize=(11, 7))
grid = plt.GridSpec(2, 2, wspace=0.2, hspace=0.5)
ax1 = plt.subplot(grid[0, 0])
ax2 = plt.subplot(grid[0, 1:])
ax3 = plt.subplot(grid[1, :1])
ax4 = plt.subplot(grid[1, 1:])
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()
答案 6 :(得分:0)
如果您有多张图片,并且想要循环浏览它们,并与标题一起按1比例显示-这就是您可以执行的操作。无需显式定义ax1,ax2等。
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2, figsize=(6, 8))
for i in range(len(ax)):
for j in range(len(ax[i])):
## ax[i,j].imshow(test_images_gr[0].reshape(28,28))
ax[i,j].set_title('Title-' + str(i) + str(j))
答案 7 :(得分:0)
您只能通过迭代为每个图形指定不同的标题和标签。
titles = {221: 'First Plot', 222: 'Second Plot', 223: 'Third Plot', 224: 'Fourth Plot'}
fig = plt.figure()
for x in range(221,225):
ax = fig.add_subplot(x)
ax.title.set_text(titles.get(x))
plt.subplots_adjust(left=0.1,
bottom=0.1,
right=0.9,
top=0.9,
wspace=0.4,
hspace=0.4)
plt.show()
输出: