-1

I make several plots my data using seaborn's displot. I cutomise the palette using the dictionary:

my_palette = {'car': 'b', 'foot':'k', 'metro':'c', 'bus':'r', 'bike':'y'} # values of hue

And then plot like so:

# fig customisation omitted for brevity
sns.displot(df1, x='distance', kind='ecdf', hue='mode', log_scale=True, palette=my_palette,)

Giving:

enter image description here

But then when I plot the next figure, the legend order change (as python dictionary isn't ordered), like this one:

sns.displot(df2, x='distance', kind='ecdf', hue='mode', log_scale=True, palette=my_palette,)

Which gives:

enter image description here

I am wondering if there's a way to maintained a defined ordering, such as foot, bike, bus, car, metro

planar
  • 13
  • 4
  • You could set a fixed order with `df1["mode"] = pd.Categorical(df1["mode"], ["foot", "bike", "bus", "car", "metro"])` and similar for `df2`. – JohanC Oct 11 '22 at 18:21

1 Answers1

2

You can use hue_order base order that you want and keys of your my_palette dict.

sns.displot(df2, x='distance', kind='ecdf', hue='mode', 
            log_scale=True, palette=my_palette,
            hue_order=['foot', 'bike', 'bus', 'car', 'metro']
            )

from doc:

hue_order: Specify the order of processing and plotting for categorical levels of the hue semantic.

I'mahdi
  • 23,382
  • 5
  • 22
  • 30