首页 > 解决方案 > 如何在同一图表中将(n 个未知)数据系列数绘制为 geom_line

问题描述

我在这里的第一个Q,所以如果我在任何地方不合时宜,请轻点。

我正在尝试对 R 进行编码以生成包含多个数据系列行的单个图表。数据系列的数量可能会有所不同,但将在数据框中提供。我试图将另一个线程的内容重新排列到 printgeom_line但没有成功。

逻辑是:

#desire to replace loop of 1:5 with ncol(df)
 print(ggplot(df,aes(x=time))
for (i in 1:5) { 
   print (+ geom_line(aes(y=df[,i])) 
}
#functioning geom point loops ggplot production:
for (i in 1:5) { 
   print(ggplot(df,aes(x=time,y=df[,i]))+geom_point()) 
} 
#functioning multi-line ggplot where n is explicit:
ggplot(data=df, aes(x=time), group=1) +
  geom_line(aes(y=df$`3`))+
  geom_line(aes(y=df$`4`))

功能示例代码生成 n 个点图,在本例中为 5 个。我只想要一个包含 n 行系列的图表。

这可能类似于如何绘制 n 维矩阵?目前没有相关答案

任何贡献都非常感谢,谢谢

标签: rggplot2

解决方案


你可以使用gatherfrom tidyverse"world" 来做到这一点。由于您没有提供我使用的示例数据mtcars。我创建了两个 data.frames,一个有 3 列,一个有 9 列。在每个数据帧中,我将所有变量与变量 mpg 进行了对比。

library(tidyverse)

df3Columns <- mtcars[, 1:4]
df9Columns <- mtcars[, 1:10]


df3Columns %>% 
  gather(var, value, -mpg) %>% 
  ggplot(aes(mpg, value, group = var, color = var)) + 
  geom_line()

在此处输入图像描述

df9Columns %>% 
  gather(var, value, -mpg) %>% 
  ggplot(aes(mpg, value, group = var, color = var)) + 
  geom_line()

在此处输入图像描述

编辑 - 在评论中使用示例数据。

library(tidyverse)

df %>% 
  rownames_to_column("time") %>%
  gather(var, value, -time) %>%
  ggplot(aes(time, value, group = var, color = var)) + 
  geom_line()

在此处输入图像描述

样本数据:

df <- structure(list("39083" = c(96, 100, 100), "39090" = c(99, 100, 100), "39097" = c(99, 100, 100)), row.names = 3:5, class = "data.frame") 

推荐阅读