I would like to give each histplot
in FacetGrid
from seaborn
a different binwidth
. To give each plot a binwidth
of 3 is possible like this:
JavaScript
x
8
1
import seaborn as sns
2
3
sns.set_theme(style="darkgrid")
4
tips = sns.load_dataset("tips")
5
6
g = sns.FacetGrid(tips, col="day", height=3.5, aspect=.65)
7
g.map(sns.histplot, "total_bill", binwidth = 3)
8
Output:
But let’s say you want to give each plot a different binwidth
, for example 1,2,3 and 4 in a list, the following error appears:
JavaScript
1
3
1
g = sns.FacetGrid(tips, col="day", height=3.5, aspect=.65)
2
g.map(sns.histplot, "total_bill", binwidth = [1,2,3,4])
3
Error:
JavaScript
1
2
1
TypeError: unsupported operand type(s) for +: 'float' and 'list'
2
So I was wondering if anyone knows how to give each plot in the FacetGrid
a different binwidth
using seaborn
?
Advertisement
Answer
You could loop simultaneously through g.axes_dict
and the widths, and call the function separately for each subplot. You’ll need to manually create the correct subset of the dataframe.
JavaScript
1
10
10
1
import seaborn as sns
2
3
sns.set_theme(style="darkgrid")
4
tips = sns.load_dataset("tips")
5
6
g = sns.FacetGrid(tips, col="day", height=3.5, aspect=.65)
7
for (day, ax), binwidth in zip(g.axes_dict.items(), [1, 2, 3, 4]):
8
sns.histplot(tips[tips["day"] == day]['total_bill'], binwidth=binwidth, ax=ax)
9
ax.set_title(f'day={day} binwidth={binwidth}')
10