【问题标题】:Different hue for each category seaborn每个类别的不同色调 seaborn
【发布时间】:2021-02-09 07:28:04
【问题描述】:

所以,我用 seaborn 最简单的方法做了一个脱衣舞,有 5 个不同的类别:

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)

现在,我想为每个类别设置不同的色调,比如第一类的速度大于 50 kmh,第二类的速度大于 30 kmh,以此类推。这可能吗?我试图通过一个色调列表来做到这一点:

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

但它标记:SyntaxError: invalid syntax
问题是,我想在同一个情节中一次完成所有事情(因为最明显的答案是单独绘制),这怎么做?

编辑:我遵循了建议的答案。使用相同的代码:

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)

但结果并没有像预期的那样:

我不明白这里有什么问题。有什么想法吗?

【问题讨论】:

  • 我遗漏了一个逗号(就在“色调列表”之后),之后消息变为:类型错误:“str”和“int”实例之间不支持“>”
  • 您的speed 列似乎不包含数字。
  • 速度列不是问题。在您的示例中进行第一个比较:("Route 30" > 50) 您将字符串“Route 30”与没有意义的数字 50 进行比较。

标签: python pandas seaborn


【解决方案1】:

我建议在df 中为点颜色创建单独的列。 试试这个:

# 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)

【讨论】:

  • 这根本没有解决,但我非常感谢您的帮助。
  • 嗨,John Doe,我更改了解决方案示例 - 检查一下。它应该可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 2021-12-19
  • 2018-09-20
  • 2018-12-15
相关资源
最近更新 更多