0

I have a column for Devices, and Values and I'm plotting a density curve for each Device.

library (ggplot2)
library(magritrr) # for the pipe operator  
df %>% ggplot(aes(x = Value, group = Device)) + geom_density()

Now how do I add a label to each line? (I want the Device name to appear beside each density line on the graph and not in the legend)

mnm
  • 1,962
  • 4
  • 19
  • 46
user10621247
  • 13
  • 1
  • 5
  • 2
    When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jun 10 '19 at 04:01
  • Try the `directlabels` package: http://directlabels.r-forge.r-project.org/motivation.html – Jon Spring Jun 10 '19 at 06:32

1 Answers1

1

I created a new summary dataset specifically for the labels. I positioned the labels at the peak of each density plot by picking the max Value for the x-axis and the max density for the y-axis. Hopefully this is helpful.

library(ggplot2)
library(dplyr)

Device = c("dev1","dev2","dev3","dev1","dev2","dev3","dev1","dev2","dev3")
Value = c(10,30,77,5,29,70,12,18,76)
df <- data.frame(Device, Value)

labels <- df %>% 
  group_by(Device) %>%  
  summarise(xPos = max(Value),
            yPos = max((density(Value))$y))

ggplot() + 
  geom_density(data=df, aes(x = Value, group = Device, colour=Device)) +
  geom_label(data=labels, aes(x=xPos, y=yPos, colour=Device, label=Device)) +
  theme_light() +
  theme(legend.position = "None")

enter image description here

olorcain
  • 1,230
  • 1
  • 9
  • 12