简体   繁体   中英

Different hue for each category seaborn

So, I have made a stripplot with seaborn the easiest way, with 5 different categories:

sns.set_style('whitegrid')
plt.figure(figsize=(35,20))
sns.set(font_scale = 3)
sns.stripplot(df.speed, df.routeID, hue=df.speed>50, jitter=0.2, alpha=0.5, size=10, edgecolor='black')
plt.xlabel("Speed", size=40)
plt.ylabel("route ID", size=40)
plt.title("Velocity stripplot", size=50)

Now, the thing is I want to have a different hue for each category, say speed greater than 50 kmh for first category, 30 kmh for second and so on. Is this possible? I tried to do it passing a list for hue:

hue=([("ROUTE 30">50),("ROUTE 104">0)])

but it marks: SyntaxError: invalid syntax
The thing is, I want to do it all at once (since the most obvious answer would be to plot separately) in the same plot, how can this be done?

EDIT: I followed the suggested answer. Used the same code:

plt.figure(figsize=(20,7))

my_palette = ['b' if x > 82 else 'g' for x in df.speed.values]

sns.stripplot(df.speed, df.routeID, jitter=0.2, alpha=0.5, size=8, edgecolor='black', palette = my_palette)

but didnt turned out like expected:

在此处输入图片说明

I dont understand what is wrong here. Any ideas?

I suggest to create separate column in df for dot color. try this:

# INITIAL DATA
n = 1000
df = pd.DataFrame()
df['speed'] = np.random.randint(10,90,n)
df['routeID'] = np.random.choice(['ROUTE_5','ROUTE_66','ROUTE_95','ROUTE_101'], n)

# set hue indices to match your conditions
df['hue'] = 'normal'  # new column with default value
df.loc[df.speed > 50, 'hue'] = 'fast'
df.loc[(df.routeID=="ROUTE_5") & (df.speed>40)|
       (df.routeID=="ROUTE_66") & (df.speed>30)|
       (df.routeID=="ROUTE_95") & (df.speed>60),
       'hue'] = 'special'
palette = {'normal':'g','fast':'r','special':'magenta'} 

sns.stripplot(x=df.speed, y=df.routeID, size=15,
    hue=df.hue, palette=palette)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM