【问题标题】:How to add title to subplots in Matplotlib如何在 Matplotlib 中为子图添加标题
【发布时间】:2014-10-04 02:01:06
【问题描述】:

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

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

【问题讨论】:

    标签: python matplotlib plot subtitle


    【解决方案1】:

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

    【讨论】:

    • 对于直方图字体大小有问题的任何人,奇怪的是,减少 bin 的数量让我增加它。从 500 到 100。
    • 如果您需要能够指定字体大小,请改用ax.set_title('title', fontsize=16)
    • @TobiasP.G.,你如何在子情节中定位标题?
    • 嗨@Jarad,谢谢你的回答。当时,我使用了ax2.text(),因为ax2.title.set_y() 无法正常工作。给定 4 个相同大小的子图,如果我为每个子图的 axis.title.set_y() 赋予 $y$ 的 $0.9$ 值,它仍然会将标题放在奇怪的位置,并且与每个子图都不匹配。
    【解决方案2】:

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

    您能否检查此代码是否适合您?也许以后有东西会覆盖它们?

    【讨论】:

    • 这对我有用,matplotlib 版本 1.2.2 python 2.7.5
    【解决方案3】:

    假设的简写答案 import matplotlib.pyplot as plt:

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

    如:

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

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

    【讨论】:

    • 这种方法很好,因为它可以更好地控制标题位置......例如通过添加 kwarg y=0.7 您可以在子图中绘制子图标题
    【解决方案4】:

    如果你想让它更短,你可以写:

    import matplotlib.pyplot as plt
    for i in range(4):
        plt.subplot(2,2,i+1).set_title(f'Subplot n°{i+1}')
    plt.show()
    

    它可能不太清楚,但你不需要更多的行或变量

    【讨论】:

    • 对于任何只是复制粘贴的人来说,导入时都会出现拼写错误
    【解决方案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
    
    1. 创建任意数量的轴
    2. axs.ravel() 将您的 2-dim 对象转换为 1-dim 行主要样式的向量
    3. 将标题分配给当前轴对象

    【讨论】:

      【解决方案6】:

      如果您有多张图片,并且想要循环浏览它们并一一显示它们以及标题 - 这就是您可以做的。无需显式定义ax1、ax2等。

      1. 关键是您可以在代码的第 1 行中定义动态轴 (ax) 您可以在循环中设置其标题。
      2. 二维数组的行是轴(ax)的长度(len)
      3. 每行有 2 个项目,即它是列表中的列表(第 2 点)
      4. set_title 可用于设置标题,一旦选择了正确的轴(ax)或子图。
      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】:
        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()
        

        【讨论】:

          【解决方案8】:

          您只能通过迭代为每个图表赋予不同的标题和标签。

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

          输出:

          【讨论】:

          • subplots_adjust 调用可以解决重叠的标题。所以这非常有用。谢谢!
          【解决方案9】:

          从 matplotlib 3.4.3 开始,Figure.add_subplot 函数支持标题为:

          fig.add_subplot(311, title="first")
          fig.add_subplot(312, title="second")
          

          【讨论】:

            猜你喜欢
            • 2018-01-19
            • 1970-01-01
            • 2020-02-12
            • 1970-01-01
            • 1970-01-01
            • 2013-10-11
            相关资源
            最近更新 更多