使用ggridges绘制梯度填充密度脊图时dwnom1未找到报错排查
问题描述
我用美国国会数据绘制历年政治极化程度(dwnom1指标)的多密度脊图,普通脊图能正常生成,但添加梯度填充时R报错“dwnom1未找到”;如果直接设置fill=dwnom1,又提示“无法推断分组结构”而丢弃fill美学。怀疑和我按year分组数据的方式有关,附上代码及错误信息:
cel_yr <- cel %>% group_by(year) p <- ggplot(data=cel_yr, mapping = aes(x=dwnom1, y=factor(year, levels=rev(unique(year))), group = year, fill=stat(dwnom1))) p + geom_density_ridges_gradient(scale=3, rel_min_height=0)+ scale_x_continuous(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) + scale_fill_viridis_c(option = "C") + labs( title="Degree of US Congressional Polarization over the Years", x="DW-Nominate Scores", y="Year of Congress" )
错误提示:
Error in `geom_density_ridges_gradient()`: ! Problem while mapping stat to aesthetics. ℹ Error occurred in the 1st layer. Caused by error: ! object 'dwnom1' not found
解决办法
核心问题分析
- 不必要的
group_by(year):ggplot通过y=year(转为因子后)已经能自动完成分组,提前分组会干扰stat层对变量的识别,导致找不到dwnom1。 - fill美学的stat映射错误:
geom_density_ridges_gradient的stat计算后,内部变量名是x(对应原始x轴的dwnom1),而非原始列名dwnom1,所以不能直接写stat(dwnom1)。
修正后的代码
# 无需提前分组,直接用原始数据 p <- ggplot(data=cel, mapping = aes( x = dwnom1, y = fct_rev(factor(year)), # 用forcats包的fct_rev简洁反转年份顺序 group = year )) + geom_density_ridges_gradient( scale=3, rel_min_height=0, fill = stat(x) # 用stat(x)映射原始x轴变量作为填充梯度 ) + scale_x_continuous(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) + scale_fill_viridis_c(option = "C", name = "DW-Nominate Score") + # 给填充色标添加名称 labs( title="美国国会历年政治极化程度", x="DW-Nominate 得分", y="国会年份" ) p
额外说明
- 如果未安装
forcats包,可替换为y=factor(year, levels=rev(sort(unique(year))))实现年份反转。 - 梯度填充按x轴的dwnom1值(极化得分)给密度曲线上色,能直观呈现不同得分区间的分布密度变化。
内容的提问来源于stack exchange,提问作者TCD
相关产品推荐
相关产品推荐

