add title to collection of pandas hist plots

PythonPandasTitleHistogram

Python Problem Overview


I'm looking for advice on how to show a title at the top of a collection of histogram plots that have been generated by a pandas df.hist() command. For instance, in the histogram figure block generated by the code below I'd like to place a general title (e.g. 'My collection of histogram plots') at the top of the figure:

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

I've tried using the title keyword in the hist command (i.e. title='My collection of histogram plots'), but that didn't work.

The following code does work (in an ipython notebook) by adding text to one of the axes, but is a bit of a kludge.

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

Is there a better way?

Python Solutions


Solution 1 - Python

With newer Pandas versions, if someone is interested, here a slightly different solution with Pandas only:

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

Solution 2 - Python

You can use 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")

Solution 3 - Python

I found a better way:

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

It is very easy, display well at the top, and will not mess up your subplot.

Solution 4 - Python

for matplotlib.pyplot, you can use:

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

or if you're using a Figure object directly,

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

See this example.

Solution 5 - Python

If you want to quickly loop through all columns and get hist plots with titles, try this one.

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondremeView Question on Stackoverflow
Solution 1 - PythonFilippo MazzaView Answer on Stackoverflow
Solution 2 - PythonHYRYView Answer on Stackoverflow
Solution 3 - PythonE.WangView Answer on Stackoverflow
Solution 4 - PythonCrepeGoatView Answer on Stackoverflow
Solution 5 - PythonVictoriaView Answer on Stackoverflow