Search code examples
pythonmatplotlibcolorsseaborn

How to get standard matplotlib colours in seaborn?


I am using python to sketch all my graphs for my thesis. I am almost done, but want to add a few violin plots to my work. Thus far I have used pyplot (or matplotlib) for all my sketches, but the matplotlib violin plot does not work with my data because there are several NaN in. Therefore I am using seaborn for the violin plots. However, the colours are different to that of matplotlib, resulting in an inconsistency in my thesis. I tried finding the hue to select in seaborn to make the colours the same as that of matplotlib, but I cannot find the information any where. Does someone know how to do this?

The code is not really applicable in this question, so I am simply attaching two figures to illustrate my problem. In conclusion, I want to get the matplotlib colours in Seaborn.

Matplotlib colours.

Seaborn colours


Solution

  • The default matplotlib color palette is tab10, as shown in the "Qualitative" colormaps on this documentation page. I think the easiest way to use it would be to set the global colormap to tab10 (or use tab20 if you have more than 10 items) using sns.set_palette. By doing that, every seaborn figure you make in that script that uses a discrete colormap will use the tab10 colormap.

    Edit: As commented by @JohanC, you also need to set saturation=1 when creating the plots. As the documentation states regarding the saturation parameter:

    Proportion of the original saturation to draw colors at. Large patches often look better with slightly desaturated colors, but set this to 1 if you want the plot colors to perfectly match the input color.

    Example (adapted from the seaborn.violinplot documentation):

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    plt.close("all")
    sns.set_palette("tab10") # or "tab20"
    
    df = sns.load_dataset("titanic")
    
    fig, ax = plt.subplots()
    sns.violinplot(data=df, x="age", y="class", ax=ax, saturation=1)
    fig.tight_layout()