63

我正在寻找有关如何在由 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)

有没有更好的办法?

4

5 回答 5

101

对于较新的 Pandas 版本,如果有人感兴趣,这里有一个与 Pandas 略有不同的解决方案:

ax = data.plot(kind='hist',subplots=True,sharex=True,sharey=True,title='My title')
于 2017-10-31T13:37:07.367 回答
38

您可以使用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")
于 2013-10-28T00:50:39.903 回答
20

我找到了一个更好的方法:

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

这很容易,在顶部显示得很好,并且不会弄乱你的子图。

于 2016-06-19T12:35:55.227 回答
10

对于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")

请参阅此示例

于 2019-02-28T16:22:36.570 回答
0

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

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)
于 2021-10-06T15:42:23.053 回答