首页 > 解决方案 > 如何在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")) 
  

标签: rggplot2

解决方案


一种方法是创建一个标签列并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)

在此处输入图像描述


推荐阅读