我創建了一個(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