Skip to main content
 首页 » 编程设计

python之如何解决 python 中的图例颜色问题

2024年11月24日8leader

我使用 seaborn 绘制了两个点图。当我使用plt.legend时,legend的颜色是一样的,不区分。问题是图例中 so2 和 no2 的颜色都是蓝色。我认为它只是选择第二行查询的颜色。

ax=plt.subplots(figsize=(15,5)) 
sns.pointplot(x='Year', y='no2', data=AP_trend) 
sns.pointplot(x='Year', y='so2', data=AP_trend, color = 'r') 
plt.legend(labels=['no2', 'so2']) 

请您参考如下方法:

我认为 hue 参数是您正在寻找的参数,事先进行了一些数据操作。 我将只使用 2 列作为 x 和 y 轴,第三列作为图例。 所以这样的事情应该有效:

# data manipulation 
x = df['Year'].values 
x = np.hstack((x, x))  # stacking 2 times the same x as no2 and so2 vectors share the same Year vector 
 
y = df['no2'].values 
y = np.hstack((y, df['so2'].values)) # stacking so2 and no2 values 
 
z1 = ['no2' for i in range(len(df))] 
z2 = ['so2' for i in range(len(df))] 
z = np.hstack((z1, z2)) # first part of the dataframe correspond to no2 values, the remaining correspond to so2 values 
 
df2 = pd.DataFrame(data= {'Year': x, 'y' : y, 'legend' : z}) 
 
sns.pointplot(x='Year', y='y', hue='legend', data=df2) 

编辑: 在 seaborn 中,没有理由像您一样制作 2 个图。色调参数是执行此操作的方法。