Search code examples
rggplot2geom-text

How to put the text for each point of plan in r


I am new to R and I have problem with adding the text for each point in the coordinate xoy: assume that I have dataframe below:

library (dplyr)
library(ggplot2)

dat <- data.frame(
  time = factor(c("Breakfast","Breakfast","Breakfast","Lunch","Lunch","Lunch","Dinner","Dinner","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
  total_bill_x = c(12.75,14.89,20.5,17.23,30.3,27.8,20.7,32.3,25.4), total_bill_y= c(20.75,15.29,18.52,19.23,27.3,23.6,19.75,27.3,21.48)
)

and here is my code:

dat %>% 
  group_by(time) %>% 
  summarise(
    x = sum(total_bill_x),
    y = sum(total_bill_y) 
  )%>%
  ggplot(.,aes(x,y, col = time)) + 
  geom_point() 

I know that we will use geom_text but i dont know which argument to add into it to know that which point represent breakfast, lunch, dinner.

Any help for this would be much appreciated.


Solution

  • You can use geom_text(aes(label = time), nudge_y = 0.5). nudge_y will vertical adjust the labels. If you want to move horizontally, you must use nudge_x.

    dat %>% 
      group_by(time) %>% # group your data 
      summarise(
        x = sum(total_bill_x),
        y = sum(total_bill_y) # compute median YOU ARE NOT COMPUTING MEDIAN HERE
      )%>%
      ggplot(.,aes(x,y, col = time)) + 
      geom_point() +
      geom_text(aes(label = time), nudge_y = 0.5)
    

    enter image description here