其他
ggplot2优雅的拆分堆砌条形图
欢迎关注R语言数据分析指南
❝本节来介绍如何「对堆砌条形图来进行图形拆分」;数据及代码已经上传小编的VIP群,
❞有需要的观众老爷欢迎加入小编的VIP群
,目前已经上传「公众号文档数据+代码约170余篇」,扫描文末尾二维码加小编微信「付费99元」后邀请进群,「由于群名额有限人满之后将不在添加新成员」,有需要的请尽早加入,早进早享受;R内置数据加载即可
加载R包
library(tidyverse)
library(patchwork)
定义主题
theme_niwot <- function(){
theme_minimal()+
theme(axis.text = element_text(color = "black",size = 6),
strip.text = element_text(color = "black",hjust = 0,
margin = margin(l = -0.5, b = 5)),
legend.key.size = unit(0.4, 'cm'),
legend.text = element_text(color = "black",size =6),
legend.margin = margin(),
legend.position = 'top',
plot.title.position = 'plot',
panel.grid.minor = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.major = element_line(size = 0.5,linetype = 3, color = "black"))
}
定义调色板
color_palette <- viridisLite::mako(6)[-c(1, 6)]
数据清洗
mpg_2008 <- mpg %>%
filter(year == 2008,!(class %in% c('2seater', 'minivan'))) %>%
mutate(class = case_when(
class %in% c('compact', 'subcompact') ~ '(Sub-)Compact',
class %in% c('pickup', 'suv') ~ 'Pickup/SUV',
T ~ str_to_title(class)),
manufacturer = str_to_title(manufacturer),
manufacturer = fct_infreq(manufacturer) %>% fct_rev())
绘制主图
unsplit_plot <- mpg_2008 %>%
ggplot(aes(y = manufacturer, fill = class)) +
geom_bar(position = position_stack(reverse = T)) +
scale_fill_manual(values = color_palette) +
scale_x_continuous(expand = expansion(mult = c(0, 0.1))) +
scale_y_discrete(expand = expansion(mult = 0)) +
geom_vline(xintercept = 0, size = 1) +
theme_niwot()+
labs(x = element_blank(),y=element_blank(),fill = element_blank())
拆分条形图
class_plots <- mpg_2008 %>%
ggplot(aes(y = manufacturer, fill = class)) +
geom_bar() +
scale_fill_manual(values =color_palette) +
facet_wrap(vars(class)) +
scale_x_continuous(expand = expansion(mult = c(0, 0.1))) +
scale_y_discrete(expand = expansion(mult = 0)) +
geom_vline(xintercept = 0, size = 1) +
labs(x = element_blank(),y=element_blank(),fill = element_blank())+
theme_niwot()
绘制总图
total_plot <- mpg_2008 %>%
ggplot(aes(y = manufacturer)) +
geom_bar(fill = color_palette[4]) +
scale_x_continuous(expand = expansion(mult = c(0, 0.1))) +
scale_y_discrete(expand = expansion(mult = 0)) +
geom_vline(xintercept = 0, size = 1) +
facet_wrap(vars('Total')) +
labs(x = element_blank(),y=element_blank(),fill = element_blank())+
theme_niwot()
拼图
split_plot <- wrap_elements(plot = class_plots + total_plot +
plot_layout(widths = c(0.75, 0.25)))
unsplit_plot / plot_spacer() / split_plot +
plot_layout(heights = c(0.425, 0.01, 0.575))
❝本节介绍到此结束细节还是蛮多的,但是通过此文你一定有所收获,喜欢本文档的欢迎分享转发,添加小编微信时「请备注一下个人信息及来意以便高效处理」,「当然更加推荐加入小编的VIP交流群」,绝让你体会到物超所值
❞
小编微信
关注下方公众号下回更新不迷路
往期推荐