首页 > 解决方案 > 如何在 Seaborn barplot Python 中根据名称为单个条着色

问题描述

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

# 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不同的颜色(例如红色)突出显示条。是否有捷径可寻?

标签: pythonpandasmatplotlibseaborn

解决方案


在该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])

你得到 在此处输入图像描述


推荐阅读