Dana Roemling
Dana Roemling

Reputation: 313

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.)

Upvotes: 21

Views: 70626

Answers (3)

Clay
Clay

Reputation: 2726

For those looking for a simple one line solution in matplotlib, just tack on .set_xlabel("your_label") to the end.

df.col_to_graph.plot.hist(bins=10, alpha=0.5, figsize=(16, 12)).set_xlabel("col_to_graph label")

Upvotes: 0

Kermit
Kermit

Reputation: 5982

I came here looking for the same thing, but found it easier to do in plotly

import plotly.express as px

px.histogram(df, x="t_depth", nbins=150).update_layout(
    xaxis = dict(dtick=10), bargap=0.2
)

enter image description here

Upvotes: 1

FLab
FLab

Reputation: 7466

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

Upvotes: 38

Related Questions