猿问

for循环中的多个图忽略par

我试图生成10对图,每页几个图,并使用for循环来构建对。但是,这些图是作为单独的图而不是页面发送到设备的。


下面的MWE具有相同的基本图形和ggplot版本结构,但基本图形有效,ggplot但没有。在第二个版本中,我需要做什么才能使分页正确?


library(ggplot2)

attach(mtcars)


# correct configuration

par(mfrow=c(2,2))

for (ii in 1:3){

  vars <- c("wt", "disp", "wt")

  plot(get(vars[ii]), mpg)

  hist(get(vars[ii]))

}


# places each on separate plot

par(mfrow=c(2,2))

for (ii in 1:3){

  vars <- c("wt", "disp", "wt")

  p <- ggplot(mtcars, aes(get(vars[ii]), mpg)) + geom_point(size=4)

  plot(p)

  p <- ggplot(mtcars, aes(get(vars[ii]))) + geom_histogram()

  plot(p)

}


detach(mtcars)


RISEBY
浏览 618回答 2
2回答

撒科打诨

这是一种方法cowplot::plot_grid。该plot_duo函数使用tidyeval方法ggplot2 v3.0.0# install.packages("ggplot2", dependencies = TRUE)library(rlang)library(dplyr)library(ggplot2)library(cowplot)plot_duo <- function(df, plot_var_x, plot_var_y) {&nbsp; if (is.character(plot_var_x)) {&nbsp; &nbsp; print('character column names supplied, use ensym()')&nbsp; &nbsp; plot_var_x <- ensym(plot_var_x)&nbsp; } else {&nbsp; &nbsp; print('bare column names supplied, use enquo()')&nbsp; &nbsp; plot_var_x <- enquo(plot_var_x)&nbsp; }&nbsp; if (is.character(plot_var_y)) {&nbsp; &nbsp; plot_var_y <- ensym(plot_var_y)&nbsp; } else {&nbsp; &nbsp; plot_var_y <- enquo(plot_var_y)&nbsp; }&nbsp; pts_plt <- ggplot(df, aes(x = !! plot_var_x, y = !! plot_var_y)) + geom_point(size = 4)&nbsp; his_plt <- ggplot(df, aes(x = !! plot_var_x)) + geom_histogram()&nbsp; duo_plot <- plot_grid(pts_plt, his_plt, ncol = 2)}### use character column namesplot_vars1 <- c("wt", "disp", "wt")plt1 <- plot_vars1 %>% purrr::map(., ~ plot_duo(mtcars, .x, "mpg"))#> [1] "character column names supplied, use ensym()"#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.#> [1] "character column names supplied, use ensym()"#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.#> [1] "character column names supplied, use ensym()"#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.plot_grid(plotlist = plt1, nrow = 3)### use bare column namesplot_vars2 <- alist(wt, disp, wt)plt2 <- plot_vars2 %>% purrr::map(., ~ plot_duo(mtcars, .x, "mpg"))#> [1] "bare column names supplied, use enquo()"#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.#> [1] "bare column names supplied, use enquo()"#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.#> [1] "bare column names supplied, use enquo()"#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.plot_grid(plotlist = plt2, nrow = 3)要将图分成多个页面,我们可以使用gridExtra :: marrangeGrobml1 <- marrangeGrob(plt, nrow = 2, ncol = 1)# Interactive useml1&nbsp;# Non-interactive use, multipage pdfggsave("multipage.pdf", ml1)
随时随地看视频慕课网APP
我要回答