应对过多类别
有时图表空间有限,但需要同时展示大量数据。这里,您想要展示 pollution 数据集中每个城市的每种污染物在一年内的变化轨迹。每条污染物轨迹用折线表示,y 值为相对于当年平均值的标准差。这意味着图上会同时出现很多条线——远超出仅靠颜色就能清晰区分的数量。
为了解决这个问题,您决定仅高亮显示一小部分城市与污染物的组合(wanted_combos)。这部分对您最重要,其他轨迹则作为有价值的对比背景。为了聚焦注意力,您将把所有未高亮的轨迹线设为相同的「other」颜色。
本练习是课程的一部分
用 Python 提升数据可视化
练习说明
- 修改列表推导式,筛选出目标城市与污染物组合(
wanted_combos)。 - 在折线图中,将线条颜色映射到 DataFrame 中新创建的
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()