线未正确连接R中的绘图功能

Lines not connecting the right way with plot function in R

我正在使用Indometh数据集绘制数据。

有一条额外的线连接每个主题的第一个和最后一个数据点。如何删除该行?我的数据排序方式是否有问题?

我的代码:

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

编辑:

解决方案:

1
2
3
4
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"])

我们可以使用ggplot

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

enter image description here

或对于每个"主题"

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

enter image description here

base R中,可以使用matplot

完成此操作

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

更新

设置自定义颜色

1
2
3
4
5
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)


有多个组(主题编号),它们都被绘制为一行。因此,一旦到达一个主题的结束时间,它将把该点连接到下一个主题的第一次。

请参阅"分组数据"并绘制多条线以了解如何解决此问题。