其他
ggplot2优雅的绘制分类条形图
欢迎关注R语言数据分析指南
❝本节来介绍如何使用「ggplot2」来绘分组条形图,通过一些细节的调整来构建一个新的展示方式,下面具体来看小栗子
❞
加载R包
package.list=c("tidyverse","ggsci","ggbump")
for (package in package.list) {
if (!require(package,character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
}
数据清洗
df <- read_tsv("data.xls") %>%
select(1,2,3,4) %>%
mutate(year=as.character(year)) %>% as.data.frame() %>%
filter(continent %in% c("Europe","Americas"),year %in% c("1952","2007")) %>%
group_by(year,continent) %>%
mutate(percent=round(100*lifeExp/sum(lifeExp),digits=2)) %>%
top_n(3) %>%
arrange(year,continent) %>%
ungroup()
country continent year lifeExp percent
<chr> <chr> <chr> <dbl> <dbl>
1 Canada Americas 1952 68.8 5.16
2 United States Americas 1952 68.4 5.14
3 Uruguay Americas 1952 66.1 4.96
4 Iceland Europe 1952 72.5 3.75
5 Netherlands Europe 1952 72.1 3.73
6 Norway Europe 1952 72.7 3.76
7 Canada Americas 2007 80.7 4.38
8 Costa Rica Americas 2007 78.8 4.28
9 Puerto Rico Americas 2007 78.7 4.28
10 Iceland Europe 2007 81.8 3.51
11 Spain Europe 2007 80.9 3.47
12 Sweden Europe 2007 80.9 3.47
13 Switzerland Europe 2007 81.7 3.51
❝❞
top_n(3) 表示取每组中值最高的3个
df %>% ggplot()+
geom_bar(aes(fill = country, y =percent, x=year), position = "fill",
stat = "identity", width = .5,key_glyph="dotplot")+
geom_text(aes(y = percent, x =year, label = paste0(percent, "%")),
size = 3.5, position = position_fill(vjust = 0.5),color="white") +
geom_text(aes(x = year, y = -0.05, label = year),color="black",hjust = 1, nudge_y =-0.01, size = 4) +
geom_text(aes(x = 1.5, y = 0, label =continent), hjust = 0.5,nudge_y = -0.4, size = 5, stat = "unique",color="black") +
geom_sigmoid(aes(x = 2.25, xend = 1.5, y = -0.19, yend = -0.265),size = 0.2,direction = "y",color="black",smooth =8) +
geom_sigmoid(aes(x = 0.75, xend = 1.5, y = -0.19, yend = -0.265),size = 0.2,direction = "y",color="black",smooth =8)+
coord_flip(clip = "off", expand = FALSE) +
scale_fill_futurama()+
facet_wrap(vars(continent),ncol = 1) +
theme_void() +
theme(plot.margin = margin(30,30,30,50),
strip.text = element_blank(),
panel.spacing.y = unit(2,"lines"),
legend.title = element_blank(),
legend.key=element_blank(),
legend.text = element_text(color="black",size=10),
legend.spacing.x=unit(0.1,'cm'),
legend.key.width=unit(0.6,'cm'),
legend.key.height=unit(0.6,'cm'),
legend.background=element_blank(),
legend.box.background=element_rect(colour = "black"),
legend.box.margin = margin(0,2,0,0))
数据获取
❝非常简单的一个小案例,可以清楚直观的看出不同处理下数据的变化,喜欢的小伙伴欢迎转发此文档附上一句话到朋友圈后台截图给我,即可获取对应的数据及代码
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
往期推荐