Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting axis labels for histogram pandas

I'm fairly new to this, so there might be a very obvious answer to this. My apologies!

I'm plotting two histograms via a groubpy. I'd like my subplots to each have the same x and y labels and a common title. I understood that sharex=True would do the trick, but apparently not if I set the axis only after the df.hist. I've tried various versions of setting the xlabels and am lost now.

import pylab as pl
from pandas import *

histo_survived = df.groupby('Survived').hist(column='Age', sharex=True, sharey=True)
pl.title("Histogram of Ages")
pl.xlabel("Age")
pl.ylabel("Individuals")

So what I end up with is labels only for the subplot.

Out: <matplotlib.text.Text at 0x11a27ead0>

Screenshot of my histograms

Any idea on how to solve this? (Have to use pandas/python.)

like image 457
horizoncrying Avatar asked Mar 16 '17 11:03

horizoncrying


People also ask

How to modify a histogram in pandas?

Modifying a histogram in Pandas. You can also add titles and axis labels by using the following: df.hist(grid=False, bins=9) plt.xlabel('Age of Players') plt.ylabel('# of Players') plt.title('Age Distribution')

How to share X and y axis labels between subplots?

In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in. Note that passing in both an ax and sharex=True will alter all x axis labels for all subplots in a figure. In case subplots=True, share y axis and set some y axis labels to invisible.

How do I make a histogram in a Dataframe in Python?

Make a histogram of the DataFrame’s columns. A histogram is a representation of the distribution of data. This function calls matplotlib.pyplot.hist (), on each series in the DataFrame, resulting in one histogram per column. The pandas object holding the data.

What is the rotation value of the Y axis labels?

Rotation of y axis labels. For example, a value of 90 displays the y labels rotated 90 degrees clockwise. The axes to plot the histogram on.


1 Answers

Labels are properties of axes objects, that needs to be set on each of them. Here's an example that worked for me:

frame = pd.DataFrame([np.random.rand(20), np.sign(np.random.rand(20) - 0.5)]).T
frame.columns = ['Age', 'Survived']

# Note that you can let the hist function do the groupby
# the function hist returns the list of axes created
axarr = frame.hist(column='Age', by = 'Survived', sharex=True, sharey=True, layout = (2, 1))

for ax in axarr.flatten():
    ax.set_xlabel("Age")
    ax.set_ylabel("Individuals")
like image 63
FLab Avatar answered Oct 15 '22 14:10

FLab