面對過多類別時的處理方式
有時圖表空間有限,卻需要同時呈現大量資料。這裡你想要在 pollution 資料集中,顯示每個城市中每一種污染物一年內的變化軌跡。每條污染物軌跡會以折線呈現,y 值代表相對於該年度平均值的標準差。也就是說,圖上會同時出現很多條線——遠超過能用顏色清楚區分的數量。
為了處理這點,你決定突顯一小部分城市與污染物的組合(wanted_combos)。這個子集合對你最重要,而其他軌跡則能提供比較時的背景脈絡。為了聚焦,你會將所有未被突顯的軌跡線設為相同的「other」顏色。
本練習屬於課程
用 Python 改善你的資料視覺化
練習說明
- 修改串列生成式,篩出目標的城市與污染物組合(
wanted_combos)。 - 在折線圖中,使用資料框中新建立的
color_cats欄位來指定每條線的顏色。 - 使用
units參數來決定「如何」將資料點連成各自的線,也就是指定要依據哪個欄位來連結。 - 使用
estimator參數關閉資料點的分箱處理。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Choose the combos that get distinct colors
wanted_combos = ['Vandenberg Air Force Base NO2', 'Long Beach CO', 'Cincinnati SO2']
# Assign a new column to DataFrame for isolating the desired combos
city_pol_month['color_cats'] = [x if x in ____ else 'other' for x in city_pol_month['city_pol']]
# Plot lines with color driven by new column and lines driven by original categories
sns.lineplot(x = "month",
y = "value",
hue = '____',
units = '____',
estimator = ____,
palette = 'Set2',
data = city_pol_month)
plt.show()