#Combine Multiple ggplots Using Patchwork
rm(list = ls())
library(patchwork)
# load tidyverse
library(ggplot2)
library(tidyr)
library(dplyr)
## 
## 载入程辑包:'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# load gapminder
library(gapminder)
#install.packages("gapminder")

p1 <- gapminder %>% 
  filter(year==1952) %>%
  ggplot(aes(x=gdpPercap, y=lifeExp, color = continent))+
  geom_point() + scale_x_log10() +
  labs(subtitle="1952")
p1

p2 <- gapminder %>% 
  filter(year==1952) %>%
  ggplot(aes(x=continent, y=lifeExp, group=continent, color = continent))+
  geom_boxplot() +
  geom_jitter(width=0.2, alpha=0.4)+
  labs(subtitle="1952") +theme(axis.text.x = element_text(angle = 45,vjust = 1, hjust = 1,size = 12, color = "red"))
p2

#############################
p1+p2

# two plots side by side
p1|p2

# two plots one over the other
p1/p2

p3 <- gapminder %>% 
  ggplot(aes(x=lifeExp, fill=continent))+
  geom_density(alpha=0.4) 
(p1 + p2)/p3

#############################
#How to Place Legends in a Common Place?
p1 + p2 + plot_layout(guides="collect")

p1 + p2 + plot_layout(ncol=2,widths=c(2,1),guides="collect")

# not working correctly!
p1 + plot_spacer() + p2

p1 + p2 - p3 + plot_layout(ncol=1)

#6. How to Tag each plot in a combined plot with patchwork?
patched <- (p1 + p2)/p3
#
patched + plot_annotation(tag_levels = 'A')

patched +
  plot_annotation(tag_levels = 'A') & 
  theme(plot.tag = element_text(size = 18,color = "red"))

#7. How to Combine a ggplot and table?
p1 + gridExtra::tableGrob(gapminder %>% 
                            group_by(continent) %>% 
                            summarize(lifeExp_Ave=mean(lifeExp)))

#https://gotellilab.github.io/GotelliLabMeetingHacks/NickGotelli/ggplotPatchwork.html
#ref https://cmdlinetips.com/2020/01/tips-to-combine-multiple-ggplots-using-patchwork/