Search code examples
pythonmatplotlibseaborncolor-palette

Fix color coding when plotting in for loop with seaborn/matplotlib


I am plotting multiple scatter plots in a for loop and the "hue" is set according to a specific dimension. This dimension can either take on the value 1 or 0. Thus I am defining the palette to also have 2 colors only:

colors = ["#6e0303", "#2d659c"]
sns.set_palette(sns.color_palette(colors))

When I then plot in a for loop the scatter plot, the hue for 1 takes on the one color for some of the plots and the other for the rest of the plots. However, I want the color to always be fixed_ 1 -> "#6e0303" 0 -> "#2d659c"

I am calling the following code inside the foor loop:

plt.figure()
sns.scatterplot(data=df, x="x_col", y="y_col", hue="my_dimension")

Is there a way to achieve this?


Solution

  • For this, you will only need to slightly tweak the logic you have in place. First, you will need to change your colors variable from an array to a dict:

    colors = {0: "#2d659c", 1: "#6e0303"}
    

    Then, you will need to use Seaborn's palette argument with the dictionary:

    sns.scatterplot(data=df, x="x_col", y="y_col", hue="my_dimension", palette=colors)