如何在每条geom_density线上添加标签?

时间:2019-06-10 03:48:34

标签: r ggplot2

我有一个列DevicesValues,我正在为每个设备绘制密度曲线。

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

现在如何为每行添加标签? (我希望Device名称出现在图上的而不是图例中的的每个密度线旁边)

1 个答案:

答案 0 :(得分:0)

我专门为标签创建了一个新的摘要数据集。我通过选择x轴的最大值和y轴的最大密度,将标签放置在每个密度图的峰值处。希望这会有所帮助。

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