Search code examples
rggplot2data-visualizationggridgesridgeline-plot

Add markings/labels to Ridgeline plot [R / ggplot2]


I've made a ridgeline plot, but I would like to add custom markers to it (pop in my added reprex). The best I can come up with is adding a label. This is not ideal.

I found this link, which is more in line from what I want. but I can't get the example to work for my case (using fill = to plot for levels of factor).

Below is some output with the best thing I could come up with.

Thanks.


library(tidyverse)
library(ggridges)

dfs <-
  data.frame(
    "estimate" = rnorm(300),
    "loading" = factor(rep(1:5, 60)),
    "set" = factor(rep(1:3, 100),),
    "pop" = rep(c(0.1, 0.15, 0.20, 0.05, 0.7), 60)
  )

ggplot(dfs, aes(x = estimate, y = loading, fill = set)) +
  geom_density_ridges(
    jittered_points = TRUE,
    point_shape = "|", point_size = 2, size = 0.25,
    position = position_points_jitter(height = 0), alpha = 0.6, scale = 1.2) 
#> Picking joint bandwidth of 0.395


loadsummary2 <- crossing("set" =  dfs$set, "loading" = dfs$loading)
loadsummary2$pop <- rep(c(0.1, 0.15, 0.20, 0.05, 0.7), 3)
  
ggplot(dfs, aes(x = estimate, y = loading, fill = set)) +
  geom_density_ridges(
    jittered_points = TRUE,
    point_shape = "|", point_size = 2, size = 0.25,
    position = position_points_jitter(height = 0), alpha = 0.6, scale = 1.2) + 
    geom_label(data = loadsummary2, aes(y = loading, x = pop), label = "*")
#> Picking joint bandwidth of 0.395

Created on 2020-03-13 by the reprex package (v0.3.0)


Solution

  • I found a solution with some help of someone over at the RStudio community page!

    
    library(tidyverse)
    library(ggridges)
    
    dfs <-
      data.frame(
        "estimate" = rnorm(300),
        "loading" = factor(rep(1:5, 60)),
        "set" = factor(rep(1:3, 100),),
        "pop" = rep(c(0.1, 0.15, 0.20, 0.05, 0.7), 60)
      )
    
    
    loadsummary2 <- crossing("set" =  dfs$set, "loading" = dfs$loading)
    loadsummary2$pop <- rep(c(0.1, 0.15, 0.20, 0.05, 0.7), 3)
    
    p <- ggplot(dfs, aes(x = estimate, y = loading, fill = set)) +
      geom_density_ridges(
        jittered_points = TRUE,
        point_shape = "|", point_size = 2, size = 0.25,
        position = position_points_jitter(height = 0), alpha = 0.6, scale = 1.2) + 
        geom_text(data = loadsummary2, 
                  aes(y = loading, x = pop, label = pop),
                  position=position_nudge(y= .25), 
                  colour="black", 
                  size=3.5)
    
    p + geom_segment(aes(
      x = pop,
      y = as.numeric(loading) - .05,
      xend = pop,
      yend = as.numeric(loading) + .15))
    #> Picking joint bandwidth of 0.437
    

    Created on 2020-03-14 by the reprex package (v0.3.0)