r - 为什么将 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()
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"))
解决方案
据我了解,ggplot 为每个 geom_ 创建一个图例......因此出现了这些小(有时是烦人的)“a”。有几个选项可以隐藏图例。添加show.legend = FALSE
geom_-call 可能是最简单的:
...
geom_text(aes(...label = round(mean_health, 0)),..., show.legend = FALSE)
...
推荐阅读
- asp.net-core - 如果用户发布 http 请求后令牌过期,则刷新令牌概念如何工作
- sharepoint - 从 SPX 库组件 Projext 中的列表中获取 LisItem
- javascript - CodeSignal 不同的平方更有效
- python - 我可以在控制台错误中访问请求对象吗?
- java - 在所有 Junit 测试类中使用方法
- c# - 如何防止在大约 1000 个请求中发生 1 个的 HttpClient TaskCancelled 异常?
- javascript - 访问第三级 JSON 对象的 Google App 脚本
- python - Python:如何将声音设备麦克风输入发送到烧瓶
- php - 没有特殊字符的php文件搜索
- linux - 有没有办法像自动热键一样将字符串作为击键发送?