亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

for循環中的多個圖忽略par

for循環中的多個圖忽略par

RISEBY 2019-09-06 16:36:06
我試圖生成10對圖,每頁幾個圖,并使用for循環來構建對。但是,這些圖是作為單獨的圖而不是頁面發送到設備的。下面的MWE具有相同的基本圖形和ggplot版本結構,但基本圖形有效,ggplot但沒有。在第二個版本中,我需要做什么才能使分頁正確?library(ggplot2)attach(mtcars)# correct configurationpar(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 plotpar(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)
查看完整描述

2 回答

?
撒科打諢

TA貢獻1934條經驗 獲得超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) {


  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)


查看完整回答
反對 回復 2019-09-06
  • 2 回答
  • 0 關注
  • 640 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號