Determining which group each line belongs to in "geom_vline" ggplot2

48 views Asked by At

I want to add some text in the lines, I know I can use the code below,

mu<-starwars%>%group_by(gender)%>%
    summarize(mean_height=mean(height,na.rm=T))
  mu
  ggplot(starwars,aes(height,fill=gender))+
    geom_histogram(bins=20,position="dodge")+
    geom_vline(data=mu,aes(xintercept=mean_height,col=gender))+
    geom_text(x=mu$mean_height[1],y=0,label=round(mu$mean_height[1],2),size=3,vjust=1)+
    geom_text(x=mu$mean_height[2],y=0,label=round(mu$mean_height[2],2),size=2,vjust=1)+
    geom_text(x=mu$mean_height[3],y=0,label=round(mu$mean_height[3],2),size=2.5,vjust=1)

enter image description here

but I want to know if there is a way I can change the color of the lines and add the text without using "group_by" to determine which line it belongs to Is it for men or women? I went the following way, but I could not continue. I hope there is a way that is short so I don't have to repeat the "geom_text" for the label like the above code

 ggplot(starwars,aes(height,fill=gender))+
  geom_histogram()+
  geom_vline(xintercept = by(starwars$height,starwars$gender,mean,na.rm=T))

enter image description here

1

There are 1 answers

0
Rui Barradas On

Change the data argument to the computed summary statistic data set and set x, y and labels as aesthetics.

geom_text(
    data = mu,
    mapping = aes(x = mean_height, y = 0, label = round(mean_height, 2)),
    size = 3, vjust = 1
  )

Note that now size is always 3. To change this create a new column in the pipe and then move size to aes().

mu <- starwars %>%
  group_by(gender)%>%
  summarize(mean_height=mean(height,na.rm=T)) %>%
  mutate(size = c(3, 2, 2.5))
mu

ggplot(starwars,aes(height,fill=gender))+
  geom_histogram(bins=20,position="dodge")+
  geom_vline(data=mu,aes(xintercept=mean_height,col=gender))+
  geom_text(
    data = mu,
    mapping = aes(x = mean_height, y = 0, label = round(mean_height, 2), size = size),
    vjust = 1,
    show.legend = FALSE
  )