r - 如何在同一图表中将(n 个未知)数据系列数绘制为 geom_line
问题描述
我在这里的第一个Q,所以如果我在任何地方不合时宜,请轻点。
我正在尝试对 R 进行编码以生成包含多个数据系列行的单个图表。数据系列的数量可能会有所不同,但将在数据框中提供。我试图将另一个线程的内容重新排列到 print
,geom_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 维矩阵?目前没有相关答案
任何贡献都非常感谢,谢谢
解决方案
你可以使用gather
from 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")
推荐阅读
- c# - 如何让 Windows 服务在重复过程之前完成所有代码
- python - 我怎样才能摆脱这些“\xb0”之类的字符串
- r - 在 y 轴 ggplot2 上使用括号表示负值
- string - Pandas 通过查看两个列表是否具有共同值来累积计数
- .net - 邮递员和角度都出现错误
- install4j - 如何使用 install4j 为套件创建安装程序?
- kubernetes - 设置 extraEnvs 入口变量
- apache-spark - Spark 2.0+:spark.sql.files.maxPartitionBytes 不工作?
- ios - DateComponentFormatter 翻译
- python - 使用 PyQt 的精确计时器