Björn Butter
Björn Butter

Reputation: 169

set range of horizontal lines depending on variable

I have the following 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")

And I produce the following plot:

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

How can I set the range for each horizontal line on the x-axis depending on the variable "MAEImprove"? Each line should "start" at 0 and depending on MAEImprove reach to its associated negative or positive value.

Upvotes: 0

Views: 21

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24818

You can use geom_segment. Since, in comparison to geom_line, geom_segment takes two mappings in aes, you can set xend = 0 and have the other end of the segment vary based on the participant. Then both values of y and yend can be mapped to the participant factor level.

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()

enter image description here

Upvotes: 2

Related Questions