I have a little library to plot various comparison figures of different methods (think of machine learning methods). The same method has always the same colour for consistency reason across different plots. Now for one plot I would like to change the order of the layering only, while keeping the colouring the same. So far the colouring and layering was done by a simple order of calling it in the code.
Since I want to change the order of the layering but not the colouring only for one plot I don't want to go through all plot functions and define z_order
and hue_order
.
So how can I achieve this? Looking at the example below I would like the blue line to be above the orange one while type A
is still blue and type B
is still orange.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
df = pd.DataFrame([[1, 10, "A"],[2, 12, "A"],[1, 6, "B"],[2, 13.5, "B"]], columns = ["x", "y", "type"])
sns.lineplot(data=df, x="x", y="y", hue="type")
plt.show()
CodePudding user response:
You can achieve that by specifying hue_order
, but that will switch the colors and the order of the legend labels too. You can change that back with palette
and by reversing the handles and labels to your legend.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
df = pd.DataFrame([[1, 10, "A"],[2, 12, "A"],[1, 6, "B"],[2, 13.5, "B"]], columns = ["x", "y", "type"])
sns.lineplot(data=df, x="x", y="y", hue="type", hue_order=['B', 'A'], palette=['C1', 'C0'])
handles, labels = plt.gca().get_legend_handles_labels()
plt.legend(handles=handles[::-1], labels=labels[::-1], title='type')
plt.show()
Output: