如何让gganimate中连续填充图例显示为离散样式
解决方案
要兼顾平滑过渡效果和离散型图例,可通过自定义图例映射+强制离散图例的方式实现:
- 保留
fill的连续型映射以触发scale_fill_continuous_sequential的平滑过渡 - 替换数值标签为原因子名称,同时强制图例显示为离散框
修改后的代码如下:
library(tidyverse) library(colorspace) library(gganimate) library(ggplot2) set.seed(42) SIMS <- 1e3 df <- tibble( a = rbeta(SIMS, 600, 400), b = rbeta(SIMS, 650, 350) ) |> pivot_longer( everything(), names_to = 'distribution', values_to = 'values' ) |> mutate(distribution = factor(distribution, levels = c('a','b'))) df |> ggplot(aes( x = values, fill = as.integer(distribution) )) + geom_density() + colorspace::scale_fill_continuous_sequential( palette = "Blues 3", begin = 0.1, end = .9, breaks = c(1,2), labels = c("a", "b"), # 将数值标签替换为原分布名称 guide = guide_legend(title = "Prior") # 强制使用离散图例样式 ) + transition_states( states = distribution, transition_length = 1, state_length = 1, wrap = TRUE)
效果说明
- 动画仍保留
scale_fill_continuous_sequential提供的平滑颜色过渡 - 图例将显示为两个对应
a、b的离散颜色框,与scale_fill_discrete的样式一致
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

