1

I am plotting a figure that shows the mean in health across individuals with different age groups. I display the difference between two groups of people interviewed at two different periods: 2006-08 and 2009-12. As you can see in the two plots below, once i add geom_text to my code, the legend line type changes. Could someone tell me how to keep it solid and dashed while still adding geom_text?

Here is the plot without geom_text:

ggplot(df, aes(age, mean_health, linetype= Year, color= Year))+
  geom_line()

enter image description here Here is the plot with geom_text:

ggplot(df, aes(age, mean_health, linetype= Year, color= Year))+
  geom_line()+
  geom_text(data = filter(a, mean_health == max(a$mean_health[Year == "2009-12"])), 
                  aes(age, mean_health, label = round(mean_health, 0)), hjust = 1.20, vjust=0, size=4)

enter image description here

Here is my data:

structure(list(age = c(18, 18, 19, 19, 20, 20, 21, 21, 22, 22
), Year = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("2006-08", 
"2009-12"), class = "factor"), mean_health = c(85.8131067961165, 
87.0587925403013, 84.7693574958814, 86.5121248004943, 84.5478434971219, 
86.1607839060144, 84.0793845077811, 85.5619426238315, 83.6882757389053, 
85.0810204193354), mean_chr = c(9.0427240603919, 8.95552835577315, 
9.70889575540738, 9.31401831939466, 9.82768571193009, 9.45283585075522, 
10.5885398688298, 9.52824332712601, 9.979633401222, 9.86532875627145
)), row.names = c(NA, -10L), groups = structure(list(age = c(18, 
19, 20, 21, 22), .rows = structure(list(1:2, 3:4, 5:6, 7:8, 9:10), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, 5L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))
Jack
  • 813
  • 4
  • 17

1 Answers1

2

As far as I understand, ggplot creates a legend for each geom_... Therefore these little (and at times annoying) "a"s appear. There are several options to hide a legend. Adding show.legend = FALSE in the geom_-call is probably most straightforward:

 ...
geom_text(aes(...label = round(mean_health, 0)),..., show.legend = FALSE)
...
Wolfgang Arnold
  • 1,252
  • 8
  • 17