How to wrap a wrapped plot plus another plot?

Viewed 272

I want the six plots in one plot. And I would like to specify the titles of each plot. How can I do that?

p<-ggplot(df, aes(x=COD_NEIGHB))+
  geom_bar(stat="count", width=0.3, fill="steelblue")+
  theme_minimal()
# histogram of the strata in the whole dataset
s<-ggplot(data = df, mapping = aes(x = COD_NEIGHB)) +
  geom_bar(stat="count", width=0.3, fill="steelblue")+
  facet_wrap(~ fold)
plot_grid(p, s, ncol=2,label_size = 2)

enter image description here

After that, I did the suggestion

df$fold <- as.character(df$fold)
# Duplicate data. Set category in the duplicated dataset to "all"
df_all <- df 
df_all$fold <- "all"
# Row bind the datasets
df_all <- rbind(df, df_all)

ggplot(df_all, aes(x=COD_NEIGHB)) +
  geom_bar(stat="count", width=0.3, fill="steelblue")+
  facet_wrap(~fold)

But now the problem is the scale. y-axis has to be on the proper scale.

enter image description here

any idea for that?

Thanks in advance!!!!

2 Answers

If I got you right you want a plot with facets by categories plus an additonal facet showing the total data. One option to achieve this is to duplicate your dataset to add an addtional category "all".

As no example data was provided I make use of mtcars to show you the basic idea:

library(ggplot2)

mtcars$cyl <- as.character(mtcars$cyl)
# Duplicate data. Set category in the duplicated dataset to "all"
mtcars_all <- mtcars 
mtcars_all$cyl <- "all"
# Row bind the datasets
mtcars_all <- rbind(mtcars, mtcars_all)

ggplot(mtcars_all, aes(hp, mpg)) +
  geom_point() +
  facet_wrap(~cyl)

Here is another useful tool with the help of the ggarrange() function from the ggpubr package. You can arrange multiple plots on one page or multiple pages. You can also create a common, unique legend once you merge all your plots together.

Similar to previous answers, I used mtcars to demonstrate a simple use case:

#install.packages("ggpubr")
#library(ggpubr)

p1 <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  theme_minimal()

p2 <- ggplot(mtcars, aes(y = mpg, x = cyl)) +
  geom_boxplot() +
  theme_minimal()

ggarrange(p1, p2, ncol = 2)

multiple plots - ggarrange

Related