将标题添加到Pandas直方图图集中

73

我正在寻求如何在由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='我的直方图集合'),但没有起作用。

以下代码在ipython笔记本中确实起作用,它通过向其中一个坐标轴添加文本来实现,但有点笨拙。

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

有更好的方法吗?

5个回答

116

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

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

43
你可以使用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")

96
hist() 不能有命名的 title 参数是否有技术上的原因? - Stefan Falk

24

我发现了一种更好的方法:

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

这很容易,在顶部显示效果很好,不会搞乱你的子图。


17

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

参见此示例


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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接