在`for`循环内创建一系列地块

时间:2019-11-10 20:52:29

标签: r ggplot2

我需要显示15个地块,在for列表中进行迭代,如下所示:

### Plotting that does not work
plots <- c()
for (i in colnames(dataframeselect)){
  current_col <- dataframeselect[i]
  plots <- c(plots, ggplot(dataframeselect, aes_string(colnames(current_col))) + geom_histogram())
}
ggarrange(plotlist = plots)

虽然我可以逐个迭代并创建图,但我无法创建图列表,然后可以将其传递给ggarrange

我现在不得不求助于创建15个变量,这可以很好地完成工作,但是有点乏味并且不适合DRY:

### Plotting that works
my_plot <- function(column) ggplot(dataframeselect, aes_string(x = column)) + geom_histogram()

p1 <- my_plot("W3_f15771g")
p2 <- my_plot("W3_f15771a")
p3 <- my_plot("W3_f15771b")
#...
ggarrange(p1,p2,p3)

请注意,已经有一个问题在问,但是这些答案都没有使用for循环来获得所需的结果:Lay out multiple ggplot graphs on a page

我得到的警告如下:

  Cannot convert object of class FacetNullFacetggprotogg into a grob.
44: In as_grob.default(plot) :
  Cannot convert object of class environment into a grob.
45: In as_grob.default(plot) : Cannot convert object of class list into a grob.
46: In as_grob.default(plot) :
  Cannot convert object of class tbl_dftbldata.frame into a grob.
47: In as_grob.default(plot) : Cannot convert object of class list into a grob.
48: In as_grob.default(plot) :
  Cannot convert object of class ScalesListggprotogg into a grob.
49: In as_grob.default(plot) : Cannot convert object of class uneval into a grob.
50: In as_grob.default(plot) : Cannot convert object of class list into a grob.

有趣的是,每当我向列表中添加新图时,对象的数量就不会增加1,而是会增加9个元素。因此,通过查看plots变量,我发现这不是很多plot对象,而是所有我想添加的绘图中的所有片段的大混乱:

messed-up-data-soup

所以我想知道如何以某种方式将图放置在某个子容器中,然后ggarrange可以使用它。

3 个答案:

答案 0 :(得分:2)

一种选择是将ID1 = ['ABC123','ABC234','ABC345']初始化为df['ID1'] = df['ID1'].apply(lambda x: x.replace(x[:3],str(df['ID2']))),其长度与数据集的列数相同

plots

答案 1 :(得分:2)

简单的lapply而不是for循环怎么样?遵循

library(ggpubr)
library(tidyverse)

make_plot <- function(n) {
  tibble(x = rnorm(n), y = rnorm(n)) %>%
    ggplot(aes(x = x, y = y)) +
    geom_point()
}

plots <- lapply(1:15, make_plot)

ggarrange(plotlist = plots)

哪个生产

enter image description here

答案 2 :(得分:2)

如果您要使用ggarrange(),听起来您可以使用facet_wrap。最主要的是首先使数据集变长:

library(ggplot2)
library(tidyr)

 as.data.frame(volcano[, 1:10])%>%
  pivot_longer(everything())%>%
  ggplot(aes(value)) + 
  geom_histogram() + 
  facet_wrap(vars(name))

enter image description here

类似的基本方法是:

DF <- as.data.frame(volcano[, 1:10])
grps <- names(DF)

#make hists without plotting
hists <- lapply(DF, hist, plot = F)

#plot limits:
x_min <- min(DF)
x_max <- max(DF)

y_max <- max(unlist(lapply(hists, '[[', 'counts'), use.names = F))

#try to make it rectangular:
n_by_n <- ceiling(sqrt(length(grps)))
par(mfrow = c(if (n_by_n * (n_by_n-1) < length(grps)) n_by_n else n_by_n-1, n_by_n))

#loops through the elemnts
mapply(function(x, grp) plot(x, main = grp, xlim = c(x_min, x_max), ylim = c(0, y_max)),
       hists,
       grps)

base facet histogram