I have the code below that creates a two axes figure. The figure shows box plots for three categorical variables (x axis, hue and figure axes) and one numerical (y axis, shared by the two figure axes ax0
and ax1
).
# modules used
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
# data generation
df = pd.DataFrame([[np.random.choice(['PFOS','PFOA','PFHxS']),
np.random.choice(region_order),
np.random.choice([True, False]),
v] for v in np.random.normal(10,5,200)],
columns=['c','r','u','value'])
dfu = df.loc[df['u']==False,:] # subset of dataframe used for second axis
# required order of categorical variables
region_order = [*reversed(['Arctic Sea', 'North Atlantic'])]
compound_order = ['PFOS', 'PFHxS', 'PFOA']
# figure with two axes
f, (ax0,ax1) = plt.subplots(nrows=1, ncols=2, figsize=(12, 8), sharey=True)
sns.boxplot(data=df, x='value', y="r",
hue='c', palette="PuOr", ax=ax0,
hue_order=compound_order, order=region_order,
fliersize=0.5, linewidth=0.75)
sns.boxplot(data=dfu, x='value', y="r",
hue='c', palette="PuOr", ax=ax1,
hue_order=compound_order, order=region_order,
fliersize=0.5, linewidth=.75)
plt.show()
The first figure axis uses the complete data frame while the second axis uses a subset only.
As you can see, the order of the hue is not consistent between the two axes. The hue legend for the compounds (c
) is the same for both axes, so the second axis reverses the hue order for some reason.
How can I have both axes keeping the same hue order?