我需要显示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
对象,而是所有我想添加的绘图中的所有片段的大混乱:
所以我想知道如何以某种方式将图放置在某个子容器中,然后ggarrange
可以使用它。
答案 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)
哪个生产
答案 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))
类似的基本方法是:
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)