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

如何在ggridges中基于height美学映射填充图形颜色

解决方法

你原来的代码失效是因为geom_density_ridges_gradient默认填充梯度沿x轴(日期)计算,若要按病例数(山脊高度)映射填充颜色,需要将fill映射到统计层生成的高度值即可,修正后的可运行代码如下:

library(tidyverse)
library(lubridate)
library(ggridges)

# 数据读取逻辑保持不变
df_ind_stacked_daily <- read.csv(url("https://raw.githubusercontent.com/johnsnow09/covid19-df_stack-code/main/df_ind_stacked_daily.csv")) %>% 
  mutate(Date = ymd(Date))

# 修正后的绘图代码
df_ind_stacked_daily %>%
  filter(Daily_cases_type == "Daily_confirmed",
         State.UnionTerritory != "India") %>% 
  ggplot(aes(x = Date, y = State.UnionTerritory, 
             height = Daily_cases_counts, group = State.UnionTerritory,
             fill = after_stat(height))) + 
  geom_density_ridges_gradient(stat = "identity", scale = 2, 
                               rel_min_height = 0.01, gradient_lwd = 1.) +
  scale_fill_viridis_c(name = "每日确诊数", option = "plasma") + # 可自行更换色阶方案
  coord_cartesian(clip = "off") +
  theme_ridges(grid = FALSE)

如果使用的是3.3.0版本以下的ggplot2,把after_stat(height)替换为..height..即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:42:03