1

enter image description here

From the above plot I want to remove labels displayed in the middle of each line and only keep labels at the starting and end of lines, but do not know how to do that. Below is the complete code of my plot.

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

Sample data

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

Hope this sample data is enough. Do let me know in comments if anything else is required.

Desired plot

enter image description here

Please suggest some ideas for this.

  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. You can either subset the data for that layer do it doesn't have those points or change those labels to "" – MrFlick Jul 06 '21 at 19:22
  • Thanks for the suggestion @MrFlick . I have edited my question. Let me know if this is helpful. – Hopping Buddha Jul 06 '21 at 19:54

1 Answers1

2

ggplot2 provides the ability to change the data used in each geom_* or layer. This can include ~-like functions. Perhaps this will work, untested:

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

(Replacing ... with the strings you want ... this can also be ! q_year %in% "Q 2 2020" or similar.) I'm using subset there, but you can also use dplyr::filter(., ...).

r2evans
  • 141,215
  • 6
  • 77
  • 149