首页 > 解决方案 > 为什么将 geom_text 添加到 ggplot 会更改图例线类型?

问题描述

我正在绘制一个图表,显示不同年龄组个体的健康平均值。我展示了在两个不同时期接受采访的两组人之间的差异:2006 年 8 月和 2009 年 12 月。正如您在下面的两个图中所看到的,一旦我将 geom_text 添加到我的代码中,图例线类型就会发生变化。有人可以告诉我如何在添加 geom_text 的同时保持实心和虚线吗?

这是没有 geom_text 的情节:

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

在此处输入图像描述 这是 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)

在此处输入图像描述

这是我的数据:

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

标签: rggplot2

解决方案


据我了解,ggplot 为每个 geom_ 创建一个图例......因此出现了这些小(有时是烦人的)“a”。有几个选项可以隐藏图例。添加show.legend = FALSEgeom_-call 可能是最简单的:

 ...
geom_text(aes(...label = round(mean_health, 0)),..., show.legend = FALSE)
...

推荐阅读