繁体   English   中英

尝试创建多个折线图Rstudio

[英]Trying to create multiple lines chart Rstudio

嗨,我正在尝试创建基于三条线的多色折线图。

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

以下是数据结构的屏幕截图

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

程式码片段

但是,当我绘图时,我明白了吗?

绘图输出

它正在绘制所有点。 但这并没有通过person_index ID分隔它们。 我想念什么? 另外,如何使Rstudio返回趋势线方程式?

在您的循环中,您并没有按人员索引数据。 因此,它只是一次又一次地绘制所有数据。 您可以执行以下操作:

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可能更方便。 在这里,您可以指定一个带有时间戳记,边界和人ID的数据框,然后按照以下步骤进行操作:

ggplot(data, aes(x = Timestamp_num, y = boundx, color = PersonID_num)) + geom_line()

这似乎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"))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM