每组ggridges颜色渐变

时间:2019-12-03 08:04:12

标签: r ggplot2 ggridges

我正在尝试绘制具有两个组的岭线图,并在每个组内绘制颜色渐变。例如,对于工会主义者,从深蓝色到浅蓝色,对于印地族,从深红色到浅红色。

谢谢!

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)

1 个答案:

答案 0 :(得分:0)

我没有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创建

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