gpt4 book ai didi

r - for循环中的多个图忽略par

转载 作者:行者123 更新时间:2023-12-04 10:54:20 26 4
gpt4 key购买 nike

我正在尝试生成 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)

最佳答案

这是使用 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) {

if (is.character(plot_var_x)) {
print('character column names supplied, use ensym()')
plot_var_x <- ensym(plot_var_x)
} else {
print('bare column names supplied, use enquo()')
plot_var_x <- enquo(plot_var_x)
}

if (is.character(plot_var_y)) {
plot_var_y <- ensym(plot_var_y)
} else {
plot_var_y <- enquo(plot_var_y)
}

pts_plt <- ggplot(df, aes(x = !! plot_var_x, y = !! plot_var_y)) + geom_point(size = 4)
his_plt <- ggplot(df, aes(x = !! plot_var_x)) + geom_histogram()

duo_plot <- plot_grid(pts_plt, his_plt, ncol = 2)
}

### use character column names
plot_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 names
plot_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::marrangeGrob

ml1 <- marrangeGrob(plt, nrow = 2, ncol = 1)

# Interactive use
ml1




# Non-interactive use, multipage pdf
ggsave("multipage.pdf", ml1)

关于r - for循环中的多个图忽略par,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50929344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com