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

如何为ggridridges脊线图设置连续型point_colour图例(viridis配色)

脊线图连续型point_colour美学实现(Viridis配色)

我绘制了一幅脊线图(ridge plot),其中点的颜色由一个不影响脊线的分组变量控制。希望使用Viridis配色创建一个连续型的point_colour图例,但不知如何实现。以下是我成功实现离散型point_colour美学与图例控制的示例代码,请问如何改为连续型point_colour美学?

原示例代码:

iris %>% 
    mutate(Group = sample(1:4, n(), replace = TRUE)) %>%
    ggplot() +
    geom_density_ridges(aes(x = Sepal.Length, y = Species, point_colour = as.factor(Group), group = Species),
            rel_min_height = 0.005, jittered_points = TRUE) +
    scale_y_discrete(expand = c(0.01, 0)) +
    scale_x_continuous(expand = c(0.01, 0)) +
    theme_ridges() +
    scale_discrete_manual("point_colour",
                        values = viridis::viridis(n = 4,
                                                  begin = 0, end = 1, direction = 1),  name = "Group") +
    guides(point_colour = guide_legend(override.aes = list(fill = "white", colour = "white")))

解决方案

只需对原代码做3处关键修改,即可实现连续型point_colour美学:

  • 移除Group变量的因子转换:在aes中将point_colour = as.factor(Group)改为point_colour = Group,让ggplot识别这是连续变量。
  • 替换离散刻度为连续Viridis刻度:把scale_discrete_manual换成scale_colour_viridis_c,这个函数专门用于连续型变量的Viridis配色映射,会自动生成渐变图例。
  • 调整图例设置:连续型图例使用guide_colorbar而非guide_legend,原代码中针对离散图例的override.aes设置可以移除,也可按需调整色条样式。

修改后的完整代码:

library(tidyverse)
library(ggridges)
library(viridis)

iris %>% 
    mutate(Group = sample(1:4, n(), replace = TRUE)) %>%
    ggplot() +
    geom_density_ridges(
        aes(x = Sepal.Length, y = Species, point_colour = Group, group = Species),
        rel_min_height = 0.005, 
        jittered_points = TRUE
    ) +
    scale_y_discrete(expand = c(0.01, 0)) +
    scale_x_continuous(expand = c(0.01, 0)) +
    theme_ridges() +
    scale_colour_viridis_c(
        name = "Group",
        begin = 0, 
        end = 1, 
        direction = 1
    ) +
    guides(point_colour = guide_colorbar(
        barwidth = 1,
        barheight = 10
    ))

补充说明

  • scale_colour_viridis_c会根据Group的连续数值自动分配Viridis色系的渐变颜色,无需手动指定values参数。
  • 如果你的Group变量原本是分类变量,需要先通过as.numeric()将其转换为连续数值,才能实现连续配色映射。
  • 若需要限制色条的数值范围,可在scale_colour_viridis_c中添加limits = c(min_val, max_val)参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 03:07:36