尝试将多个ggplot放入一张图像中,但所有图都是相同的

问题描述 投票:0回答:1

我正在尝试将多个 ggplot 图表放入一个图表中,但所有图表都是相同的,请帮助以下示例:

```
library(tidyverse)
library(gridExtra)

url <- paste("https://raw.githubusercontent.com/fivethirtyeight/",
  "data/master/college-majors/recent-grads.csv",
  sep = ""
)
df <- read_csv(url)
cols_to_factor <- c("Major", "Major_code", "Major_category")
df <- df %>%
  mutate_at(cols_to_factor, factor)
df_clean <- df %>% drop_na()

plot_list <- list()
i <- 0
for (variable in colnames(select_if(df_clean, is.numeric))) {
  i <- i + 1
  g <- ggplot(df_clean) +
    geom_histogram(aes(unlist(df_clean[, variable])),
      bins = 20,
      fill = "royalblue", color = "gray"
    ) +
    ggtitle(paste("Histogram of", variable)) +
    labs(x = variable)
  plot_list[[i]] <- g
}
grid.arrange(grobs = plot_list, ncol = 5)
```

plot_list里面确实有值,但我不知道为什么它们都是一样的。每个循环的值应该不同。如果我在

plot(g)
之前添加
plot_list[[i]]<-g
,它就可以绘制正确的图表。我没有想法,请帮忙。谢谢!

r ggplot2 gridextra
1个回答
0
投票

您可以通过

facet_wrap()

达到想要的结果
library(tidyverse)

df_clean %>% 
  select(where(is.numeric)) %>% 
  pivot_longer(everything()) %>% 
  ggplot(aes(x = value)) + 
  geom_histogram(bins = 20, fill = "royalblue", color = "gray") + 
  facet_wrap(~ name, scales = "free")

© www.soinside.com 2019 - 2024. All rights reserved.