首页 > 解决方案 > 线条没有以正确的方式与 R 中的绘图功能连接

问题描述

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

有一条额外的线连接每个主题的第一个和最后一个数据点。如何删除这条线?我的数据如何排序有问题吗?

我的代码:

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

编辑:

解决方案:

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"]) 

标签: rplot

解决方案


我们可以使用ggplot

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

在此处输入图像描述

或者对于每个“主题

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

在此处输入图像描述


base R中,这可以通过matplot

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

更新

设置自定义颜色

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)

推荐阅读