amc
amc

Reputation: 833

Change 1 point color in scatter plot regardless of color palette

I have a pandas data frame df like this

NAME VALUE ID A 0.2 X B 0.4 X C 0.5 X D 0.8 X ... Z 0.3 X

I would like to color all the points by the 'NAME' column by specifying the hue='NAME' but specify the color for ONE point: B.

How do you specify the color for 1 point only, and have the "hue" command take care of the rest (where each point A-Z has a unique color)?

Right now this is my command to plot, where hue is the NAME.

plot = sns.stripplot(x="ID", y="VALUE", hue="NAME", data=df, jitter=True, c=df['NAME'], s=7, linewidth=1)

Upvotes: 1

Views: 3508

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339250

You can replace one color in the palette by converting it to a list of colors and then replace one of the colors by some other color of your liking.

import pandas as pd
import numpy as np;np.random.seed(42)
import matplotlib.pyplot as plt
import seaborn as sns

letters = list(map(chr, range(ord('A'), ord('Z')+1)))
df = pd.DataFrame({"NAME" : letters, 
                   "VALUE": np.sort(np.random.rand(len(letters)))[::-1],
                   "ID" : ["X"]*len(letters)})

special_letter = "B"
special_color = "indigo"

levels = df["NAME"].unique()
colors = sns.color_palette("hls", len(levels))
inx = list(levels).index(special_letter)
colors[inx] = special_color

ax = sns.stripplot(x="ID", y="VALUE", hue="NAME", data=df, 
                     jitter=True,  s=7, palette=colors)

ax.legend(ncol=3, bbox_to_anchor=(1.05,1), loc=2)
ax.figure.subplots_adjust(right=0.6)
plt.show()

enter image description here

Instead of providing a palette directly, one may also (thanks to @mwaskom for pointing that out) use a dictionary of (hue name, color) pairs:

levels = df["NAME"].unique()
colors = sns.color_palette("hls", len(levels))
colors = dict(zip(levels, colors))
colors[special_letter] = special_color

Upvotes: 4

Related Questions