Python 如何在Matplotlib中将标题添加到子地块?
我有一个包含许多子图的图Python 如何在Matplotlib中将标题添加到子地块?,python,matplotlib,plot,subtitle,Python,Matplotlib,Plot,Subtitle,我有一个包含许多子图的图 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 = 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\u title()
但后者不会向我的子图添加任何标题
谢谢你的帮助
编辑:
更正了有关设置标题()
的打字错误。感谢Rutger Kassiesax。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\u text(“我的绘图标题”)似乎也能起作用
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.pyplot导入为plt
:
plt.gca().set_title('title')
例如:
plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...
这样就不需要多余的变量。如果您想缩短它,您可以写:
import matplolib.pyplot as plt
for i in range(4):
plt.subplot(2,2,i+1).set_title('Subplot n°{}' .format(i+1))
plt.show()
这可能会使它变得不那么清晰,但您不需要更多的行或变量,以防您有多个图像,并且希望在它们之间循环,并将它们与标题一起逐个显示-这是您可以做的。无需显式定义ax1、ax2等
我越来越倾向于使用的解决方案是:
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
这对我来说很有用,matplotlib版本1.2.2 python 2.7.5对于任何对直方图的字体大小有问题的人来说,奇怪的是,减少仓位的数量让我增加仓位。从500变为100。如果您需要指定fontsize,请使用
ax。改为使用set_title('title',fontsize=16)
。@TobiasP.G.,如何将标题定位在子地块内?@HitanshuSachania例如,ax2
,您可以使用ax2.title.set_y(0.8)
,这将向下移动标题。如果您看到标题与其他绘图重叠,可以将plt.tight_layout()
放在plt.show()
前面,看看这是否有帮助。您好@Jarad,谢谢您的回答。当时,我使用了ax2.text()
,因为ax2.title.set__y()
在某种程度上无法工作。给定4个子地块大小相同,如果我给每个子地块的axis.title.set_y()
赋予$y$0.9$的值,它仍然会将标题放在奇怪的位置,并且与每个子地块不匹配。这种方法很好,因为它可以更好地控制标题位置…例如。通过添加kwarg y=0.7,可以在子地块内绘制子地块标题
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()
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