每组 ggridges 颜色渐变

ggridges color gradient per group

我正在尝试制作一个包含两组的脊线图以及每组内的颜色渐变。因此,例如,Unionists 从深蓝色到浅蓝色,Indy 组从深红色到浅红色。

提前致谢!

library(dplyr)
library(forcats)
Catalan_elections %>%
  mutate(YearFct = fct_rev(as.factor(Year))) %>%
  ggplot(aes(y = YearFct)) +
  geom_density_ridges(
    aes(x = Percent, fill = paste(YearFct, Option)), 
    alpha = .8, color = "white", from = 0, to = 100
  ) +
  labs(
    x = "Vote (%)",
    y = "Election Year",
    title = "Indy vs Unionist vote in Catalan elections",
    subtitle = "Analysis unit: municipalities (n = 949)",
    caption = "Marc Belzunces (@marcbeldata) | Source: Idescat"
  ) +
  scale_y_discrete(expand = c(0.01, 0)) +
  scale_x_continuous(expand = c(0.01, 0)) +
  scale_fill_cyclical(
    breaks = c("1980 Indy", "1980 Unionist"),
    labels = c(`1980 Indy` = "Indy", `1980 Unionist` = "Unionist"),
    values = c("#ff0000", "#0000ff", "#ff8080", "#8080ff"),
    name = "Option", guide = "legend"
  ) +
  theme_ridges(grid = FALSE)

我没有 Catalan_elections 数据,所以我将尝试提供一个带有虚拟数据的最小示例。

要将多个 fill 变量映射到不同的尺度,您可以使用 ggnewscale 包。权衡是您必须为每个映射单独调用 geom_density_ridges_gradient

library(ggplot2)
library(ggridges)
#> 
#> Attaching package: 'ggridges'
#> The following object is masked from 'package:ggplot2':
#> 
#>     scale_discrete_manual
library(ggnewscale)

df <- data.frame(
  x = c(rnorm(100, -2), rnorm(100, 2)),
  y = rep(LETTERS[1:2], each = 100)
)

ggplot(df, aes(x, y)) +
  geom_density_ridges_gradient(data = df[df$y == "A", ],
                               aes(fill = stat(x)), scale = 1) +
  scale_fill_gradient(low = "lightblue", high = "darkblue",
                      name = "A") +
  # Note that a fill scale must exist already before a new one can be used
  new_scale_fill() +
  geom_density_ridges_gradient(data = df[df$y == "B", ],
                               aes(fill = stat(x)), scale = 1) +
  scale_fill_gradient(low = "lightcoral", high = "darkred",
                      name = "B")
#> Picking joint bandwidth of 0.324
#> Picking joint bandwidth of 0.343

reprex package (v0.3.0)

于 2019-12-03 创建

我相信将此示例扩展到您自己的数据不会太困难。