【问题标题】:Seaborn set color for specific bar in barplotSeaborn 为条形图中的特定条设置颜色
【发布时间】:2021-08-18 21:54:20
【问题描述】:

对于下面的代码,我正在尝试创建一个条形图。如果 ACQUISITION_CHANNEL 列中的列名 = 'Referral',则该条应为红色,否则为灰色。

g = sns.catplot(
    data=df, kind="bar",
    x="CITY", y="CUSTOMERS", hue="ACQUISITION_CHANNEL",
    ci="sd", palette=clrs, alpha=.6, height=8
)
g.despine(left=False)
g.set_axis_labels("", "Share Total Customers for each City (%)")
g.legend.set_title("")

这是我迄今为止尝试过的,但没有奏效

values = df.Customers
clrs = ['grey' if (x < max(values)) else 'red' for x in values ]

【问题讨论】:

标签: python seaborn


【解决方案1】:

您可以指定一个dict,将用于hue 参数的值映射到matplotlib 颜色,请参阅second example under point plots

df = sns.load_dataset("tips")
palette = {c: "grey" if c != "Male" else "r" for c in df["sex"].unique()}
# {'Female': 'grey', 'Male': 'r'}

g = sns.catplot(
    data=df, 
    kind="bar",
    x="day", 
    y="total_bill", 
    hue="sex",
    ci="sd", 
    palette=palette, 
    alpha=.6, 
)

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 2012-10-18
    • 2019-05-06
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    相关资源
    最近更新 更多