r - 如何在ggplot的图形上写出某个变量的值?
问题描述
我正在绘制 2018 年至 2021 年间受不同教育程度的人的压力水平。
我使用以下代码,它工作正常:
ggplot(x, aes(year, stress)) +
geom_line(aes(group = education, linetype= education)) +
labs(group= "Education", linetype="Education")
然而,读者并不清楚初始值是从什么压力水平开始的。例如,它显示 2018 年受教育程度低的压力水平从 5 到 6 开始,但我希望读者以图形方式查看两个教育组的 2018 年值。这意味着它应该在图表上为低学历写“5.6”,为高学历写“4.3”。最好的方法是什么?
这是可重现的示例:
structure(list(stress = structure(c(4.30000019073486, 4.5, 6,
7.40000009536743, 5.59999990463257, 6.19999980926514, 8.80000019073486,
8.80000019073486), format.stata = "%9.0g"), year = structure(c(2018,
2019, 2020, 2021, 2018, 2019, 2020, 2021), format.stata = "%9.0g"),
education = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("High",
"Low"), class = "factor")), row.names = c(NA, -8L), class = c("tbl_df",
"tbl", "data.frame"))
解决方案
一种方法是创建一个标签列并stress
使用geom_text
.
library(dplyr)
library(ggplot2)
x %>%
mutate(label = replace(round(stress, 2), year != 2018, '')) %>%
ggplot(aes(year, stress, label = label)) +
geom_line(aes(group = education, linetype= education)) +
labs(group= "Education", linetype="Education") +
geom_text(vjust = -0.5)
推荐阅读
- javascript - Nativescript(角度)找不到延迟加载的模块
- linux - Azure Pipeline Agent 无法使用代理并出现 Curl 错误:CURLE_RECV_ERROR
- javascript - 使用redux登录后如何在反应路由器dom中重定向到主页?
- scala - 如何将火花数据框转换为 SQL 查询?
- c# - DbUpdateConcurrencyException 在尝试从 DbSet 中删除条目而不先加载它时发生删除
- java - 将数组分成3块并将它们放入数组数组中?
- java - 简单的 java 布尔值。为什么这会返回假?
- mysql - 快速估计 MySQL 中查询扫描的行数
- reactjs - 跨域读取阻塞 (CORB) 阻止了 React 应用程序上的跨域响应
- apache - 如何在浏览器上为 xampp htdocs 项目启用简单名称