如何将计划中每个点的文本放入 r

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

我是 R 的新手,我在为坐标 xoy 中的每个点添加文本时遇到问题:假设我有以下数据框:

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)
)

这是我的代码:

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

我知道我们将使用 geom_text 但我不知道要添加哪个参数才能知道哪个点代表早餐、午餐、晚餐。

如有任何帮助,我们将不胜感激。

您可以使用 geom_text(aes(label = time), nudge_y = 0.5)nudge_y 将垂直调整标签。如果要水平移动,必须使用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)