我正在绘制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"))
发布于 2021-03-29 17:53:54
一种方法是创建一个label列,并使用geom_text
显示2018年的stress
值。
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)
https://stackoverflow.com/questions/66851783
复制相似问题