I am encountering a problem in which seaborn's relplot
function creates a FacetGrid
that is different from creating the FacetGrid
manually. I find this unintuitive and would like the relplot
function to give me a FacetGrid
that behaves similarly to the manually created one.
The issue is that when using the map
function on the FacetGrid
returned from relplot
, it does not consider a specified hue anymore. Here is a minimal example that explains my point:
import numpy as np
import seaborn as sns
import pandas as pd
def foo(color=None, label=None, tag=None):
print(tag, color, label)
x = np.random.randn(100)
df = pd.DataFrame({
'x' : x,
'y' : 2 * x,
'row' : np.random.randn(x.shape[0]) > 0,
'col' : np.random.randn(x.shape[0]) > 0,
'hue' : np.random.randn(x.shape[0]) > 0,
})
g = sns.relplot(data = df, x = 'x', y = 'y', row='row', col='col', hue='hue')
g.map(foo, tag='relplot')
g2 = sns.FacetGrid(data = df, row = 'row', col = 'col', hue='hue')
g2.map(foo, tag='FacetGrid')
When calling the map
function on the facet grid returned by relplot
, it will only be called four times (once per row and column) but will not respect the fact that I also specified a hue. The output is:
relplot (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) None
relplot (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) None
relplot (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) None
relplot (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) None
If I map the same function to the FacetGrid
that is manually created, it will result in the expected behaviour:
FacetGrid (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) False
FacetGrid (0.8666666666666667, 0.5176470588235295, 0.3215686274509804) True
FacetGrid (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) False
FacetGrid (0.8666666666666667, 0.5176470588235295, 0.3215686274509804) True
FacetGrid (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) False
FacetGrid (0.8666666666666667, 0.5176470588235295, 0.3215686274509804) True
FacetGrid (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) False
FacetGrid (0.8666666666666667, 0.5176470588235295, 0.3215686274509804) True
Is there any explanation as to why that happens? Is there a way to change relplot
's behaviour to match the expected one, i.e. to respect the hue parameter I set?
Is there any explanation as to why that happens?
Yes, in relplot
the hue
logic is all handled within scatterplot
, not by the FacetGrid
.
Is there a way to change relplot's behaviour to match the expected one?
No, in this case you'll want to make your custom function handle the hue logic internally or start with FacetGrid
directly.