【问题标题】:Plot more than 10 graphs at once from columns of a single large data frame从单个大型数据框的列中一次绘制 10 多个图形
【发布时间】:2016-02-06 00:14:33
【问题描述】:

从我做的一个实验中,我得到了包含时间序列数据的大文件。每列代表一个我想在图表中绘制的系列。 X 和 Y 轴的范围并不重要,因为我只需要它作为概览。

问题是,我每个数据帧有 150-300 列(和 400 行),而且我无法弄清楚如何一次绘制超过 10 个图。

library(ggplot2)
library(reshape2)
csv <- read.csv(file = "CSV-File-path", header = F, sep = ";", dec = ".")[,1:10]
df <- as.data.frame(csv)
plot.ts(df)

当我将 [,1:10] 更改为 [,1:11] 时出现错误:

绘图错误(x = x,y = y,plot.type = plot.type,xy.labels = xy.labels, : 不能将超过 10 个系列绘制为“多个”

理想情况下,我希望输出一个多页 PDF 文件,每页至少包含 10 个图表。我对R相当陌生,希望您能帮助我。

【问题讨论】:

  • 你得到什么错误?
  • 添加了我收到的错误消息
  • 显然plot.ts 不能绘制超过 10 个系列。您可以使用ggplot2base plotlines 函数。您介意在您的示例中添加name(csv) 吗?
  • How to make a great R reproducible example?,另见PDF()apply() 循环函数。

标签: r pdf plot ggplot2


【解决方案1】:

这是一种 ggplot2 方法:

library(ggplot2)
library(reshape2)

nrow <- 200
ncol <- 24
df <- data.frame(matrix(rnorm(nrow*ncol),nrow,ncol))

# use all columns and shorten the measure name to mvar
mdf <- melt(df,id.vars=c(),variable.name="mvar") 

gf <- ggplot(mdf,aes(value,fill=mvar)) + 
         geom_histogram(binwidth=0.1) + 
         facet_grid(mvar~.)

print(gf) # print it out so we can see it

ggsave("gplot.pdf",plot=gf)   # now save it as a PDF

剧情是这样的:

【讨论】:

  • 你也可以使用facet_wrap()来获得更多的y空间。
  • 是的,好主意,在这种情况下看起来会好很多,但我不知道他的数据实际上是什么样的。
【解决方案2】:

这是一种方法。这个将列分组为 5 组,然后将它们作为单独的页面写入单个 PDF。但如果是我,我会使用 ggplot2 并在一个情节中完成它们。

nrow <- 18
ncol <- 20
df <- data.frame(matrix(runif(nrow*ncol),nrow,ncol))

plots <- list()

ngroup <- 5
icol <- 1
while(icol<=ncol(df)){
   print(icol)
   print(length(plots))
   ecol <- min(icol+ngroup-1,ncol(df))
   plot.ts(df[,icol:ecol])
   plots[[length(plots)+1]] <- recordPlot()
   icol <- ecol+1
}
graphics.off()

pdf('plots.pdf', onefile=TRUE)
for (p in plots) {
  replayPlot(p)
}
graphics.off()

【讨论】:

猜你喜欢
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
相关资源
最近更新 更多