Search code examples
rplotgeom-text

Adding geom_text or annoation to stat_density_ridges plot


I have a stat_density_ridges plot and I'd like to add some text (in this case a z-score) to each individual ridge in the plot. If I could get the text in the top right of the plot even better.

As an example, this code 'as written' will plot a ridge plot but it tries to put all the z-scores on ridge 'A' and runs out of room so only adds the first then produces warnings.

I have discovered that if I make the 'value' col of data_df character class (change the # from line 4 to line 3) I get the correct z-score on the correct ridge, but of course I don't get any ridges because the data type is wrong.

Any help getting both ridges and annotation on the same plot would be much appreciated.

data_df <- data.frame(group=c(rep("A",26),rep("B",26),rep("C",26),rep("D",26)),
                     sample=rep(letters,4),
                     value=rnorm(26*4, mean=0, sd=1))
                     #value=as.character(rnorm(26*4, mean=0, sd=1)))

z_scores_df <- data.frame(group=c("A","B","C","D"),
                             z_score=runif(n=4, max=1, min=0))

plot = ggplot(data_df, aes(x=value, y=group)) +

  stat_density_ridges(aes(fill=after_stat(quantile)), 
             geom = "density_ridges_gradient", scale=1,
             calc_ecdf = TRUE) +

  geom_point(data=data_df[data_df$sample=='w',],
               color="green", size=2) +

  geom_text(data=z_scores_df,
            aes(label = format(z_score,digits = 3), x= Inf, y=1), 
            position = position_stack(vjust = 1.1),
            inherit.aes = F) + 
  NULL

plot

Solution

  • One way is to add vjust= and hjust= in the aes() from geom_text() to adjust the position of z scores (you can play with the values to adjust the positions). Also the y value in the aes() should be group to add z-score values by group:

    plot = ggplot(data_df, aes(x=value, y=group)) +
      
      stat_density_ridges(aes(fill=after_stat(quantile)), 
                          geom = "density_ridges_gradient", scale=1,
                          calc_ecdf = TRUE) +
      
      geom_point(data=data_df[data_df$sample=='w',],
                 color="green", size=2) +
      
      geom_text(data=z_scores_df,
                aes(label = format(z_score,digits = 2), x= Inf, y=group,vjust = -8,hjust=1), 
                position = position_stack(),
                inherit.aes = T) + 
      
    NULL
    plot
    

    enter image description here