首页 > 解决方案 > 删除 geom_text_repel() 中的选定标签

问题描述

在此处输入图像描述

从上面的图中,我想删除显示在每行中间的标签,只在行的开头和结尾保留标签,但不知道该怎么做。下面是我的情节的完整代码。

income_data %>% 
 drop_na(quarter) %>% 
 ggplot(aes(x = q_year, y = household_final_consumption_expenditure, group = quintile, color = quintile))+
 geom_point()+
 geom_line()+
 labs(title = "Household Final Consumption Expenditure 2019-2020",
      caption = "Source: Statistics Canada",
      x = "",
      y = "")+
 theme(axis.text.y  = element_blank(),
       axis.ticks.y = element_blank())+
 ggrepel::geom_text_repel(aes(label = household_final_consumption_expenditure))

样本数据

structure(list(q_year = c("Q 1 2020", "Q 2 2020", "Q 3 2020", 
"Q 1 2020", "Q 2 2020", "Q 3 2020", "Q 1 2020", "Q 2 2020", "Q 3 2020", 
"Q 1 2020", "Q 2 2020", "Q 3 2020"), quintile = structure(c(1L, 
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L), .Label = c("Lowest income quintile", 
"Second income quintile", "Third income quintile", "Fourth income quintile", 
"Highest income quintile"), class = "factor"), household_final_consumption_expenditure = c(15050, 
13932, 15660, 15460, 14580, 16415, 18285, 17095, 19484, 21124, 
19531, 22436)), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

希望这个样本数据就足够了。如果需要其他任何内容,请在评论中告诉我。

所需的情节

在此处输入图像描述

请为此提出一些想法。

标签: rggplot2ggrepel

解决方案


ggplot2提供更改每个geom_*或层中使用的数据的能力。这可以包括~类似的功能。也许这会起作用,未经测试:

... +
 ggrepel::geom_text_repel(aes(label = household_final_consumption_expenditure),
                          data = ~ subset(., q_year %in% c(...)))

...用你想要的字符串替换......这也可以是! q_year %in% "Q 2 2020"或类似的。)我在subset那里使用,但你也可以使用dplyr::filter(., ...).


推荐阅读