【问题标题】:add title to collection of pandas hist plots为 pandas hist plots 集合添加标题
【发布时间】:2013-11-06 00:30:48
【问题描述】:

我正在寻找有关如何在由 pandas df.hist() 命令生成的直方图集合顶部显示标题的建议。例如,在下面代码生成的直方图块中,我想在图的顶部放置一个通用标题(例如“我的直方图集合”):

data = DataFrame(np.random.randn(500).reshape(100,5), columns=list('abcde'))
axes = data.hist(sharey=True, sharex=True)

我尝试在 hist 命令中使用 title 关键字(即 title='My collection of histogram plots'),但没有成功。

以下代码确实通过向其中一个轴添加文本来工作(在 ipython 笔记本中),但有点杂乱无章。

axes[0,1].text(0.5, 1.4,'My collection of histogram plots', horizontalalignment='center',
               verticalalignment='center', transform=axes[0,1].transAxes)

有没有更好的办法?

【问题讨论】:

    标签: python pandas title histogram


    【解决方案1】:

    如果您想快速遍历所有列并获取带有标题的历史图,请尝试这个。

    import matplotlib.pyplot as plt
    
    fig, axs = plt.subplots(len(data.columns), figsize=(4,10))
    for n, col in enumerate(data.columns):
        data[col].hist(ax=axs[n],legend=True)
    

    【讨论】:

      【解决方案2】:

      对于matplotlib.pyplot,您可以使用:

      import matplotlib.pyplot as plt
      # ...
      plt.suptitle("your title")
      

      或者如果您直接使用Figure 对象,

      import matplotlib.pyplot as plt
      fig, axs = plt.subplots(...)
      # ...
      fig.suptitle("your title")
      

      this example

      【讨论】:

        【解决方案3】:

        对于较新的 Pandas 版本,如果有人感兴趣,这里有一个稍微不同的解决方案,仅适用于 Pandas:

        ax = data.plot(kind='hist',subplots=True,sharex=True,sharey=True,title='My title')
        

        【讨论】:

          【解决方案4】:

          我找到了更好的方法:

          plt.subplot(2,3,1)  # if use subplot
          df = pd.read_csv('documents',low_memory=False)
          df['column'].hist()
          plt.title('your title')
          

          这很简单,在顶部显示得很好,而且不会弄乱你的子图。

          【讨论】:

            【解决方案5】:

            你可以使用suptitle():

            import pylab as pl
            from pandas import *
            data = DataFrame(np.random.randn(500).reshape(100,5), columns=list('abcde'))
            axes = data.hist(sharey=True, sharex=True)
            pl.suptitle("This is Figure title")
            

            【讨论】:

            • hist() 不能有命名的title 参数是否有任何技术原因?
            猜你喜欢
            • 2016-09-18
            • 1970-01-01
            • 1970-01-01
            • 2017-05-11
            • 1970-01-01
            • 1970-01-01
            • 2017-05-17
            • 1970-01-01
            • 2015-08-18
            相关资源
            最近更新 更多