其他
ggplot2优雅的绘制径向条形图
欢迎关注R语言数据分析指南
❝本节来介绍如何使用「ggplot2」来绘制径向条形图,下面通过一个小例子来进行实际演示
❞
加载R包
package.list=c("tidyverse","ggsci","ggprism")
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") %>%
mutate(country_name = case_when(receiving_country_code == "EL" ~ "Greece",
receiving_country_code == "UK" ~ "United Kingdom",
receiving_country_code == "CZ" ~ "Czech Republic",
TRUE ~ country_name)) %>%
group_by(country_name) %>%
mutate(total = sum(participants)) %>%
filter(row_number() == 1) %>% # 根据分组只取1行
arrange(desc(total)) %>%
ungroup() %>%
mutate(percent = 100 * total / sum(total)) %>%
mutate(country_name = factor(country_name, levels = rev(country_name))) %>%
head(10)
# A tibble: 10 × 5
receiving_country_code participants country_name total percent
<chr> <dbl> <fct> <dbl> <dbl>
1 BE 1 Belgium 205 24.5
2 ES 1 Spain 93 11.1
3 LU 1 Luxembourg 84 10.0
4 DE 1 Germany 69 8.24
5 IT 1 Italy 65 7.77
6 UK 2 United Kingdom 38 4.54
7 CZ 1 Czech Republic 36 4.30
8 NL 1 Netherlands 31 3.70
9 RO 1 Romania 23 2.75
10 EE 1 Estonia 22 2.63
数据可视化
df %>% ggplot(aes(x = country_name, y = total, fill = country_name)) +
geom_bar(width = 0.9, stat = "identity", show.legend = FALSE) +
scale_fill_manual(values = rep(c("#3caea3", "#173f5f"),6)) +
coord_polar(theta = "y",start = 0) +
labs(x=NULL,y=NULL)+
geom_text(aes(x = country_name, y = 0,
label = paste0(country_name, " - ", round(percent, digits = 1)," %")),
hjust = 1.05,size=8, colour = rep(c("#173f5f","#3caea3"), 5)) +
ylim(c(0,250)) +
theme_void() +
theme(plot.background = element_rect(fill="#d6ecef",colour = "#d6ecef"),
panel.background = element_rect(fill="#d6ecef",colour = "#d6ecef"))
数据获取
❝非差简单的一个小案例,喜欢的小伙伴欢迎转发此文档附上一句话到朋友圈后台截图给我,即可获取对应的数据及代码
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
往期推荐