Search code examples
pythonpandasseaborn

Seaborn: Get color/hue from factorplot/facetgrid


Is there a way to get the color that is assigned to each group when calling Seaborn's factorplot? E.g. can I get the color of "one" in the following plot? Thanks!

df = pd.DataFrame({
    "name": ["one"]*4 + ["two"]*4 + ["three"]*4 + ["four"]*4 + ["five"]*4,
    "value": np.random.randint(0, 10, 20),
    "num": range(0, 4)*5
    })
ax = sns.factorplot(x="num", y="value", hue="name", data=df, kind="point", legend_out=False)
legend = plt.legend(fontsize="x-large")
plt.show()

plot


Solution

  • Eight years later and this question doesn't have a good answer, so I'm answering my own. Seaborn doesn't have factorplot anymore, but this can be achieved by catplot now. As the author of seaborn (tremendous work, mwaskom) suggested in the comments, instead of extracting the colors used in the plot after it has been drawn, we can specify the colors we want to use before it is drawn.

    This can be done with the palette argument in the catplot() call. The palette is a dictionary where the keys represent the different values in the column we are plotting, and the values represent the colors. In this example, we are coloring the name column (as specified by the hue argument in the call to catplot()):

    # Dummy dataframe
    df = pd.DataFrame({
        "name": ["one"]*4 + ["two"]*4 + ["three"]*4 + ["four"]*4 + ["five"]*4,  # This is the column we're coloring
        "value": np.random.randint(0, 10, 20),
        "num": np.tile(range(0, 4), 5)})
    
    # Setup colors. The keys correspond to the unique values in the "name" column, the values are the colors to be used.
    color_palette = {
        "one": "red",
        "two": "blue",
        "three": "green",
        "four": "yellow",
        "five": "orange"}
    
    # Plot
    ax = sns.catplot(x="num", y="value", hue="name", palette=color_palette, data=df, kind="point", legend_out=False)
    plt.gcf().set_size_inches(10, 5)  # Optional, increase figure size
    plt.show()
    

    Which result in the following figure: Finished figure