Home > database >  Add label to geom_vline within a ggplot2 figure
Add label to geom_vline within a ggplot2 figure

Time:08-29

so far I can manage to build the following geom_density figure using ggpot2:

cuts1 <- data.frame(Ref="p", vals=c(140))
cuts2 <- data.frame(Ref="s", vals=c(300))
cuts3 <- data.frame(Ref="m", vals=c(250))
cuts <- rbind(cuts1, cuts2, cuts3)

ggplot(mtcars, aes(x=disp))  
     geom_density(color = "black",
               fill = 4,
               alpha = 1)  
   geom_vline(data = cuts , aes(xintercept=vals, color= Ref) )

enter image description here

And I wondered if someone knew a way to plot the geom_vline much more like that :

enter image description here

Where the lines do not reach the top and bottom of the figure and where the labels are all displayed with a rotation.

CodePudding user response:

Here is one potential solution:

library(ggplot2)

cuts1 <- data.frame(Ref="p", vals=c(140))
cuts2 <- data.frame(Ref="s", vals=c(300))
cuts3 <- data.frame(Ref="m", vals=c(250))
cuts <- rbind(cuts1, cuts2, cuts3)

ggplot(mtcars, aes(x=disp))  
  geom_density(color = "black",
               fill = 4,
               alpha = 1)  
  geom_segment(data = cuts, aes(x=vals, xend = vals,
                                y = 0, yend = max(density(mtcars$disp)[[2]]),
                                color= Ref), key_glyph = "vpath")  
  geom_text(data = cuts, aes(x = vals, y = max(density(mtcars$disp)[[2]]) * 1.02,
                             label = Ref), nudge_x = 5, angle = 45)

Created on 2022-08-29 by the reprex package (v2.0.1)

CodePudding user response:

Take a look at geom_segment, you can set the yend parameter to where you want your lines to end.

  • Related