0

我正在尝试制作包含两组和每组内的颜色渐变的山脊线图。例如,工会主义者从深蓝色到浅蓝色,印地集团从深红色到浅红色。

提前致谢!

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)
4

1 回答 1

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 包(v0.3.0)于 2019 年 12 月 3 日创建

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

于 2019-12-03T08:31:31.703 回答