我创建了一个(gg)图形对象列表,然后尝试查看单个图形中的所有图形。从问题:How can I arrange an arbitrary number of ggplots using grid.arrange?和How do I arrange a variable list of plots using grid.arrange?,我希望下面的代码可以做到这一点(跳到最后几行代码,实际上是多图事)。在R/ggplot2中绘制多个图并保存结果
#!/usr/bin/Rscript
library(ggplot2)
library(reshape)
library(gridExtra)
args <- commandArgs(TRUE);
# Very first argument is the directory containing modelling results
setwd(args[1])
df = read.table('model_results.txt', header = TRUE)
df_actual = read.table('measured_results.txt', header = TRUE)
dfMerge = merge(df, df_actual, by = c("Clients", "MsgSize", "Connections"))
# All graphs should be stored in the directory pointed by second argument
setwd(args[2])
# Plot the results obtained from model for msgSize = 1, 1999
# and connections = 10, 15, 20, 25, 30, 50
msgSizes = c(1, 1999)
connVals = c(5, 10, 15, 20, 25, 30, 50)
cmp_df = data.frame(dfMerge$Clients, dfMerge$MsgSize, dfMerge$Connections, dfMerge$PThroughput, dfMerge$MThroughput)
colnames(cmp_df) = c("Clients", "MsgSize", "Connections", "ModelThroughput", "MeasuredThroughput")
cmp_df_melt = melt(cmp_df, id = c("Clients", "MsgSize", "Connections"))
colnames(cmp_df_melt) = c("Clients", "MsgSize", "Connections", "Variable", "Value")
plotList = list()
for (i in msgSizes) {
msg_Subset = subset(cmp_df_melt, MsgSize == i)
for (j in connVals) {
plotData = subset(msg_Subset, Connections == j)
filename = paste("Modelling.",i, ".", j, ".png", sep = '')
list_item = ggplot(data = plotData, aes(Clients, y = Value, color = Variable)) +
geom_point() +
geom_line() +
xlab("Number of Clients") +
ylab("Throughput (in ops/second)") +
labs(title = paste("Message Size = ", i, ", Connections = ", j), color = "Legend")
plotList = c(plotList, list_item)
# ggsave(file = filename)
}
}
# Plot all graphs together
pdf("Summary.pdf")
list_len = length(plotList)
nCol = floor(sqrt(list_len))
do.call(grid.arrange, c(plotList, list(ncol = nCol)))
dev.off()
相反,我打了以下错误:
Error in arrangeGrob(..., as.table = as.table, clip = clip, main = main, :
input must be grobs!
Calls: do.call -> <Anonymous> -> grid.draw -> arrangeGrob
Execution halted
我在做什么错,特别是因为两个相连的问题提出了同样的事情?另外,应该做些什么改变才能将图形保存在文件中?
不能真正考验你的代码,因为你没有提供的样本数据,但它看起来像在您引用'plotList'的例子是一个列表。 –
疯狂的猜测,但也许更改为'do.call(grid.arrange,c(plotList,ncol = nCol))'会有帮助吗? – TheComeOnMan
另外,试试'lapply(plotlist,class)'来确认每个元素是否实际上是一个阴谋。以防万一。 – TheComeOnMan