Jolanda Kossakowski
Jolanda Kossakowski

Reputation: 461

How to plot a broken line in R?

So I have the following MWE, a horizontal line expresses the mean of a particular day and the points are measurements of emotion.

I'd like to draw a line instead of points within a day between the points, but the line must have breaks between days. I can't seem to figure out how to do this.
I tried the example on this page, but that does not seem to work for my data.
A friend of mine managed to do this for the horizontal lines (they have spaces between days), but I can't seem to change my code to let it work for my measurements within days.

MWE:

beeps.MWE <- c(91.188697, 87.846194, 93.166418, 96.249094, 95.495146, 99.362597, 94.373646, 
81.995712, 87.626009, 91.880172, 93.112647, 99.349234, 87.073372, 85.161982, 88.119728, 
89.738318, 68.891181, 62.504569, 75.131526, 56.035989, 66.035109, 56.012537)

day.MWE <- rep(c(91.35869, 63.17620), each = 11)

loc.MWE <- c(8, 15)

plot(day.MWE, type = "n", pch = 15, cex = 1.5, ylim = c(40, 110), bty = "n", 
ylab = "score on PA/NA", xlab = "days of person i", axes = FALSE)
dayUn <- unique(day.MWE)
for (i in seq_along(dayUn))
{
  points(which(day.MWE==dayUn[i]),day.MWE[day.MWE==dayUn[i]], type = 'l', lwd = "2")
}
points(1:length(beeps.MWE), beeps.MWE, type = "p")
lines(1:length(beeps.MWE), rep(mean(day.MWE), 22), lwd = "2", lty = 2)
axis(1, at = c(1, 20), labels = c("day 1", "day 2"))
axis(2, las = 1)

This is the output of the above code:

enter image description here

Upvotes: 0

Views: 2574

Answers (1)

koekenbakker
koekenbakker

Reputation: 3604

You're nearly there with the code provided. Just add a line to the loop to draw the lines between the points:

for (i in seq_along(dayUn)){

  # draw horizontal lines to show the mean per day
  points(which(day.MWE==dayUn[i]),day.MWE[day.MWE==dayUn[i]], type = 'l', lwd = "2")

  # draw a line that connects points within a day
  points(which(day.MWE==dayUn[i]),beeps.MWE[day.MWE==dayUn[i]], lwd = "2", type='l')
}

Also note that points(x,y,type='l') is the same as lines(x,y). Makes more sense ;) enter image description here

Upvotes: 1

Related Questions