ggridges color gradient per group

Wesley Rademaker

I am trying to make a ridgeline plot with two groups and a color gradient within each group. So from dark blue to light blue for the Unionists and dark red to light red for the Indy group, for example.

Thanks in advance!

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

I didn't have the Catalan_elections data, so I'll try to provide a minimal example with dummy data.

For mapping multiple fill variables to different scales, you could use the ggnewscale package. A trade-off would be that you'd have to call seperate geom_density_ridges_gradient for each mapping.

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

Created on 2019-12-03 by the reprex package (v0.3.0)

I'm sure it would not be too difficult to extend this example to your own data.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related