试图创建多行图表Rstudio

时间:2018-01-29 21:38:46

标签: r plot

您好我正在尝试根据三行创建一个多色彩的折线图。

基本上我有数据通过变量Person_Index识别不同的人。我想为每个Person_Index标识创建一个带有不同颜色线条的图。

The following is a screen shot of the data structure

以下是我试图用我的代码完成此代码的片段。 (抱歉,我在格式化方面遇到了问题,因此必须将其作为图像包含在内)

Code snippet

然而,当我去绘图时,我明白了吗?

Plot output

它正在绘制所有要点。但它并没有通过person_index ID来区分它们。我错过了什么?还有我如何让Rstudio返回趋势线方程?

2 个答案:

答案 0 :(得分:0)

在你的循环中,你不是由人索引数据。所以它只是一次又一次地绘制所有数据。你可以这样做:

for (i in 1:length(unique(PersonID_num))) {
  lines(Timestamp_num[PersonID_num==unique(PersonID_num)[i]], 
        boundx[PersonID_num==unique(PersonID_num)[i]], type = "b", lwd = 1.5, lty = linetype[i], col = colors[i])
}

或者,使用ggplot2可能更方便。在那里,您可以使用时间戳,边界x和人员ID指定数据框,然后按照

的顺序执行某些操作。
ggplot(data, aes(x = Timestamp_num, y = boundx, color = PersonID_num)) + geom_line()

答案 1 :(得分:0)

似乎OP正在寻找基于plot库的基础解决方案。我创建了类似的data.frame,它的值略有不同。

#Data
df <- data.frame( person_index = c(1,1,0,2,0,1,0,1,0,2,2,2,1,1,1,0),
                  timestamp = c(300, 350, 375, 380, 385, 395, 399, 410, 425, 430, 442, 450, 455, 460, 499, 510),
                  Xmiddle = c(550, 600, 610, 620, 500, 700, 650, 800, 750, 850, 725, 786, 765, 500, 700, 750))

# Segregate the datasets for each index
index_0 <- which(df$ person_index == 0)
index_1 <- which(df$ person_index == 1)
index_2 <- which(df$ person_index == 2)

#First draw for index_0 using plot. The range is on whole date
plot(df$timestamp[index_0], df$Xmiddle[index_0], type = "o", pch = 1,
     xlim = range(df$timestamp), ylim = range(df$Xmiddle),
     xlab = "Time", ylab = "xmiddle")

#Draw for index_1. Using lines
lines(df$timestamp[index_1], df$Xmiddle[index_1], type = "o", pch = 2)

#Draw for index_2. Using lines
lines(df$timestamp[index_2], df$Xmiddle[index_2], type = "o", pch = 16)

legend("topleft", pch = c(1, 2, 16), legend = c("Index 0", "Index 1", "Index 2"))

enter image description here