问题
I was wondering if it was possible to apply hue to only the lower part of a seaborn PairGrid
.
For example, say I have the following figure:
For what I need to present I'd like to keep the density plots on the diagonal, the overall scatter plots on the upper (with printed correlation coefficients above them which I know how to do), but on the lower I want to split the points up by hue just to show my audience what happens if we do subset the data.
I thought about just finding out the correlations for the upper, doing a hue plot and just changing all of the markers in the upper plots to the same colour, but then I lose the densities on my diagonal.
Does anybody know if my problem is possible?
Current code I'm using is
ff = sns.PairGrid(test2,vars=['OzekePower','Power0','Power1','Power2'],palette="husl")
ff.map_upper(sns.scatterplot)
ff.map_lower(sns.scatterplot)
ff.map_diag(sns.kdeplot)
So what I'm hoping for is something like
ff.map_lower(sns.scatterplot,hue='species')
but this yields an error.
EDIT - I can do it if I leave the diag and upper blank and assign to the empty plots individually but this seems a lot more lengthy.
回答1:
Unfortunately, PairGrid
does not have a map_dataframe
method, which could otherwise be used to include further dataframe columns into the mapping. Kind of a hack to obtain hue
only in the lower part of the PairGrid
is to leave the hue
argument out in the PairGrid
creation, and fill the grid where no hue is desired.
Then manually set the required parameters for the hue
manually to the grid and finally call map_lower
, which will then see the grid as if it had hue
specified from the start.
import matplotlib.pyplot as plt
import seaborn as sns
df = sns.load_dataset("iris", cache=True)
g = sns.PairGrid(df)
g.map_upper(sns.scatterplot)
g.map_diag(sns.kdeplot)
# Now set parameters needed for `hue`
g.hue_vals = df["species"]
g.hue_names = df["species"].unique()
g.palette = sns.color_palette("husl", len(g.hue_names))
# Then map lower
g.map_lower(sns.scatterplot)
plt.show()
来源:https://stackoverflow.com/questions/54554925/is-there-a-way-to-apply-hue-only-to-lower-part-of-pairgrid-in-seaborn