You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Seaborn Barplot指定城市高亮错误问题求助

Seaborn Barplot高亮指定城市出错的原因及解决办法

问题根源

你代码里的颜色列表cols是按原始df30的MSA顺序生成的,但调用sns.barplot时通过order参数对MSA按房价涨幅降序排了序,导致颜色列表的顺序和图表实际显示的柱子顺序完全错位,自然会高亮错城市。

解决办法

先把数据排序并保存成新的DataFrame,再基于这个排序后的DataFrame生成颜色列表,让颜色顺序和图表柱子顺序完全对应:

修改后的代码片段

df30 = df[df['pop03']>=1700000]
plt.figure(figsize=(30,20))
plt.title("Single-Family Home Price Appreciation from 1995Q1 to 2012Q3 for the 30 Largest Metropolitan Areas in the U.S.", fontsize = 30)

# 先对数据排序并保存为新变量
sorted_df = df30.sort_values("homepriceg", ascending=False)
# 基于排序后的DataFrame生成颜色列表
cols = ['red' if x == "Los Angeles" else 'green' for x in sorted_df.MSA]

sns.barplot(x="MSA", y="homepriceg", data=sorted_df, palette = cols, 
            order=sorted_df.MSA) 
plt.xlabel("")
plt.ylabel("%", size=30)
plt.xticks(fontsize=20, rotation=60)
plt.yticks(fontsize=20)
sns.set_style("whitegrid")
plt.show()

关键改动说明

  1. 新增sorted_df变量存储排序后的数据集,避免重复排序操作
  2. 颜色列表cols基于sorted_df.MSA生成,确保每个城市的颜色和它在图表中的位置对应
  3. barplot的data参数直接用sorted_df,和order参数保持一致

内容的提问来源于stack exchange,提问作者pandawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:45:05