Reputation: 59
I'm using Seaborn's FacetGrid to plot multiple matplotlib.pyplot.hist plots with predefined bins. I want it to show the X-tick labels.
Based on what I read, I was trying:
bins = [0,3,6,9,12,15,18,21,24,30,40,50,60,80]
g = sns.FacetGrid(allData, col="Survived", row="Sex")
g = g.map(plt.hist, "Age", bins=bins)
g.set_xticklabels(bins)
The ticks don't match the bins the way I expected; I'd have thought each bar is a 'bin' and so the first bar would be: [0-3], the second: [3-6], etc. Instead each tick spans multiple bars. (Titanic dataset was being used).
I basically want each bar labelled with the age-range is represents. I'm not sure where I'm going wrong, any help would be appreciated.
Upvotes: 0
Views: 1897
Reputation: 7331
Here a example (with .set(xticks=bins)
:
bins = [0,3,6,9,12,15,18,21,24,30,40,50,60,80]
g = sns.FacetGrid(allData, col="Survived", row="Sex", size=8)
g = (g.map(plt.hist, "Age", bins=bins)).set(xticks=bins)
Upvotes: 3
Reputation: 4506
I never used sns, in matplotlib i have better control over the plot although more typing is required.
import numpy as np
import matplotlib.pyplot as plt
def fun():
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(100)
return x
fig, ax = plt.subplots(2,2, sharex=True, figsize=(14, 8))
binned = list(range(50, 160, 10))
ax[0,0].hist(fun(), binned, density=True, facecolor='g', alpha=0.75)
ax[0,0].set_title('Sex = male | survived = 0')
ax[0,1].hist(fun(), binned, density=True, facecolor='g', alpha=0.75)
ax[0,1].set_title('Sex = male | survived = 1')
ax[1,0].hist(fun(), binned, density=True, facecolor='g', alpha=0.75)
ax[1,0].set_title('Sex = female | survived = 0')
ax[1,1].hist(fun(), binned, density=True, facecolor='g', alpha=0.75)
ax[1,1].set_title('Sex = female | survived = 1')
for col in ax:
for row in col:
if row.axes.rowNum == 1:
row.set_xlabel('age')
row.locator_params(axis='x', nbins=15)
row.spines['right'].set_visible(False)
row.spines['top'].set_visible(False)
row.grid()
plt.show()
Upvotes: 0