第七十八題 2021年2月6日
ggplot2一頁多圖(組合圖)
suppressMessages(library(dplyr))
suppressMessages(library(ggplot2))
#繪製第一幅圖p1
p1 <- diamonds %>%
ggplot(aes(x = color, y = price, fill = color)) +
geom_violin() +
facet_grid(clarity ~ .) +
theme_classic() +
scale_fill_brewer(palette = 'Set1')
p1
#繪製第二幅圖p2
p2 <- diamonds %>%
ggplot(aes(x = color, fill = clarity)) +
geom_bar(stat = 'count') +
scale_fill_brewer(palette = 'Set1') +
theme_bw()
p2
#繪製第三幅圖p3
p3 <- diamonds %>%
ggplot(aes(x = color, fill = clarity)) +
geom_bar(stat = 'count', position = 'fill') +
scale_fill_brewer(palette = 'Set3') +
theme_bw()
p3
#繪製第四幅圖p4
p4 <- diamonds %>%
ggplot(aes(x = color, fill = clarity)) +
geom_bar(stat = 'count') +
coord_polar() +
scale_fill_brewer(palette = 'Set2') +
theme_bw()
p4
png("multi.png", width = 800, height = 800)
p5 <- cowplot::plot_grid(p1, p2, p3, p4, nrow = 2, labels = LETTERS[1:4])
#將p1-p4四幅圖組合成一幅圖,按照兩行兩列排列,標籤分別為A、B、C、D。(LETTERS[1:4] 意為提取26個大寫英文字母的前四個:A、B、C、D)
p5
dev.off()
png("multi1.png", width = 800, height = 800)
p6 <- ggpubr::ggarrange(p1, p2, p3, p4, nrow = 2, ncol = 2, labels = c('A', 'B', 'C', 'D'), font.label = list(color = 'red'))
#將p1-p4四幅圖組合成一幅圖,按照兩行兩列排列,標籤分別為A、B、C、D,顏色為紅色(通過font.label = list()修改),無法通過label.color = 'red'或其他方式修改。
p6
dev.off()