3

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"]) 
user12310746
  • 279
  • 1
  • 10

2 Answers2

3

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • @user12310746 In the first solution, you can create a column of colors by mapping the values to that 'Subject' and then use `color = ` that column – akrun Apr 05 '20 at 21:32
  • @user12310746 for me it is showing different colors `ggplot(Indometh, aes(x = time, y = conc)) + geom_line(aes(color = colors))` – akrun Apr 05 '20 at 22:42
  • @user12310746 if it is for the matplot, just do `matplot(xtabs(conc ~ time + Subject, Indometh), type = 'l', ylab = 'conc', col = rainbow(6))` – akrun Apr 05 '20 at 23:08
1

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.

RyanFrost
  • 1,400
  • 7
  • 17