【发布时间】:2020-08-17 17:10:55
【问题描述】:
我有一些看起来像这样的数据
# Generate example data
exampleData <- data.frame(Month = sample(1:5, 500, replace = T),
Product = sample(LETTERS[1:10], 500, replace = T),
Site = sample(letters[1:5], 500, replace = T),
Used = sample(1:100, 500, replace = T))
exampleData <- aggregate(. ~ Month + Product + Site, data = exampleData, sum) # Consolidating any duplicates
exampleData <- exampleData[order(exampleData$Month, exampleData$Product, exampleData$Site, exampleData$Used),]
我想看看不同网站不同产品的趋势,所以创建了这个功能
# Funciton to retrieve info about a product and site
productSiteInfo <- function(p, s) {
return(exampleData[intersect(which(exampleData$Product == p), which(exampleData$Site == s)),])
}
为了使我的比较更容易,我想制作一个线图网格,其中网格由所有站点上特定产品的图组成。所以我尝试了这段代码
# Plotting the data
prods <- unique(exampleData$Product) # All products
prod <- sample(prods,1) # Select a product of interest
sites <- unique(exampleData$Site) # All sites
par(mfrow=c(3,2)) # Create grid
lapply(head(sites), function(site) { # Plot trend of prod at all sites
aDF <- productSiteInfo(prod, site)
ggplot() +
geom_line(data = aDF, aes(x = Month, y = Used), color = "black") +
xlab("Month") +
ylab("Units") +
ggtitle(paste("Consumption of", prod, "at", site))
})
但它没有按预期工作。我没有得到一个地块网格,而只是单个地块。我想知道为什么会这样,以及我能做些什么来获得那个网格。我的实际数据有大约 10 个产品和大约 160 个网站,所以它会比这个例子大得多。
感谢您的帮助!
【问题讨论】:
-
par(mfrow=...)仅与基本图形兼容,而不与任何基于grid的图形兼容(例如,lattice、ggplot2)。如果你想组合,你可以尝试gridExtra::grid.arrange或cowplot包。如果数据兼容,另一种选择是使用ggplot::facet_*。 -
@r2evans 感谢您的提示。我最终将我的 lapply 保存到一个变量 lst,并尝试使用 grid.extra 安排 lst 中的图。但它看起来只有在我做
grid.arrange(lst[[1]], lst[[2]], lst[[3]], lst[[4]], lst[[5]], ncol = 3)时才会起作用,这实际上并不可行,因为我有大约 160 个地块。我不想在上述函数中写出所有 160 个参数。你知道我如何用 grid.arrange 来排列它们而不必写出每个 ysingle plot 参数吗?谢谢 -
哦,现在我看到了 160,我的答案可能并不完全适合……奥利弗的答案可能比我的更接近。