【问题标题】:How to color a single bar based off name in a Seaborn barplot Python [duplicate]如何在Seaborn barplot Python中根据名称为单个条着色[重复]
【发布时间】:2020-10-01 19:02:57
【问题描述】:

我有以下数据框产生以下情节:

# Import pandas library 
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# initialize data
data = [['tom', 10,1,'a'], ['matt', 15,5,'a'], ['Nick', 14,1,'a']]

# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Score','Category']) 
print(df.head(3))

   Name  Attempts  Score Category
0   tom        10      1        a
1  matt        15      5        a
2  Nick        14      1        a

# Initialize the matplotlib figure
sns.set()
sns.set_context("paper")
sns.axes_style({'axes.spines.left': True})

f, ax = plt.subplots(nrows=3,figsize=(8.27,11.7))

# Plot
sns.set_color_codes("muted")
sns.barplot(x="Attempts", y='Name', data=df,
            label="Total", color="b", ax=ax[0])
sns.scatterplot(x='Score',y='Name',data=df,zorder=10,color='k',edgecolor='k',ax=ax[0],legend=False)
ax[0].set_title("title")
plt.show()

我想以不同的颜色(例如红色)突出显示条Nick。有没有简单的方法可以做到这一点?

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    barplot 方法中,您可以使用palette 代替参数color 并循环检查您要更改的值。

    sns.barplot(x="Attempts", y='Name', data=df,
                label="Total", palette=["b" if x!='Nick' else 'r' for x in df.Name], ax=ax[0])
    

    然后你得到

    【讨论】:

    • 感谢@Ben.T 非常感谢!
    猜你喜欢
    • 2020-06-27
    • 2020-10-13
    • 2021-12-31
    • 1970-01-01
    • 2021-03-04
    • 2015-11-06
    • 1970-01-01
    • 2017-06-11
    • 2019-11-12
    相关资源
    最近更新 更多