首页 > 解决方案 > 根据变量设置水平线范围

问题描述

我有以下df:

aema = structure(list(MAEImprove = c(0.6262, -0.1413, -0.4477, 0.7005, 
-2.5644, 0.0087, 0.0027, 1.0048, 0.6925, -0.1582, -1.9058, 0.6909, 
0.416, -0.7901, 0.0054, 2.9682, 0.5899, 0, -2.3013, 0.0254, 1e-04, 
-0.0025, -2.0339, -0.0036, -0.0398, 0.3313, -0.0024, -0.0209, 
-0.961, -0.0022, -6.7423, 0, 0.8595, -0.6245, 0.7873, -0.4805, 
0.5182, -0.1366, 0.1799, 0.0042, 1.3768, 1.3158, 1.0448, 0.0214, 
-1.0634, -1.9322, 2.2249, 1.0547), MAE_Factor = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("aEMA", 
"pEMA", "fEMA"), class = "factor"), ParticipantNr = 1:48), row.names = c(NA, 
48L), class = "data.frame")

我制作了以下情节:

ggplot(aema) +
  geom_vline(xintercept=c(0), lty=2) +  # add a dotted line at x=1 after flip

  geom_hline(aes(yintercept = participants))  +
  ylab("Participant") + xlab("Improvement aEMA") +
  theme_bw()  # use a white background

如何根据变量“MAEImprove”设置 x 轴上每条水平线的范围?每条线应从 0“开始”,并取决于 MAEImprove 达到其相关的负值或正值。

标签: rggplot2

解决方案


您可以使用geom_segment. 由于与 相比,在 中geom_line采用geom_segment两个映射aes,因此您可以设置xend = 0并让段的另一端根据参与者而变化。然后 和 的值yyend可以映射到参与者因子水平。

ggplot(aema) +
  geom_vline(xintercept=c(0), lty=2) + 
  geom_segment(aes(y = ParticipantNr, yend = ParticipantNr,
                   x = MAEImprove, xend = 0)) +
  ylab("Participant") + xlab("Improvement aEMA") +
  theme_bw()

在此处输入图像描述


推荐阅读