Lines not connecting the right way with plot function in R

Viewed 585

I'm working on plotting data with the Indometh data set.

There's an extra line connecting the first and last data points of each subject. How do I remove this line? Is it an issue with how my data is sorted?

My code:

plot(Indometh$time, Indometh$conc, type = "l") 

Edited:

Solution:

plot(Indometh$time[Indometh$Subject == "1"], Indometh$conc[Indometh$Subject == "1"]) 

## Line for subject 2
lines(Indometh$time[Indometh$Subject == "2"], Indometh$conc[Indometh$Subject == "2"]) 
2 Answers

We could use ggplot

library(ggplot2)
ggplot(Indometh, aes(x = time, y = conc)) + 
        geom_line()

enter image description here

Or for each 'Subject

ggplot(Indometh, aes(x = time, y = conc)) +
        geom_line(aes(color = Subject))

enter image description here


In base R, this can be done with matplot

matplot(xtabs(conc ~ time + Subject, Indometh), type = 'l', ylab = 'conc')

Update

To set a custom color

colr_set <- rainbow(6)[as.integer(levels(Indometh$Subject))]
matplot(xtabs(conc ~ time + Subject, Indometh), type = 'l',
   ylab = 'conc', col =colr_set)
legend("left", legend = levels(Indometh$Subject), 
          lty = c(1, 1), lwd = c(2.5, 2.5), col = colr_set)

There are multiple groups (Subject number), and they are all being plotted as one line. So once it gets to the end time for one subject, it connects that point to the first time for the next subject.

See Group data and plot multiple lines for how to fix this.

Related