rggplot2labelstacked-chartdensity-plot

labels on a stacked density plot


I'm generating a stacked density plot:

ggplot(data=tydy_rawdata, aes(x=timepoint, y=tpm, group=fct_inorder(names), 
    fill=fct_inorder(names))) +
         geom_density(position="fill",
                      stat="identity") +
         scale_fill_manual(values = rev(mycolors))

plot :

I would like to add label on each curve (or at least the top 3 or 4) basing on the "names" displayed on the right.

I'm trying adding geom_text but the result is this :

gplot(data=tydy_rawdata, aes(x=timepoint, y=tpm, group=fct_inorder(names), 
    fill=fct_inorder(names))) +
         geom_density(position="fill",
                      stat="identity") +
         geom_text(aes(label=names)) +
         scale_fill_manual(values = rev(mycolors))

plot :

Are there some way to do it?


Solution

  • First, your chart is a stacked area chart, i.e. geom_density with stat="identity" is equal to geom_area. Second, when adding labels via geom_text you have to take account of the position argument. As you use position="fill" for your density/area chart you also have to do the same for geom_text.

    As you provided no example data I created my own to make your issue reproducible:

    library(ggplot2)
    library(forcats)
    
    set.seed(123)
    
    tydy_rawdata <- data.frame(
      names = rep(LETTERS[1:10], each = 6),
      timepoint = factor(seq(6)),
      tpm = runif(6 * 10, 0, 80)
    )
    
    ggplot(data = tydy_rawdata, aes(
      x = timepoint, y = tpm,
      group = fct_inorder(names), fill = fct_inorder(names)
    )) +
      geom_area(
        position = "fill",
        color = "black"
      ) +
      geom_text(aes(label = names), position = "fill")