其他
ggplot2优雅的绘制曲面条形图
欢迎关注R语言数据分析指南
❝本节来介绍如何使用「ggplot2」来绘制带有曲面的条形图,一点小小的改动整个图形别有一番新的意味
❞
安装R包并加载
package.list=c("tidyverse","rvest")
for (package in package.list) {
if (!require(package,character.only=T, quietly=T)) {
install.packages(package)
library(package, character.only=T)
}
}
导入数据
food_consumption <- readr::read_csv('food_consumption.csv')
构建绘图数据集
food_co2 <- food_consumption %>%
filter(country !="Hong Kong SAR. China") %>%
group_by(country) %>%
summarise(co2 = sum(co2_emmission)) %>%
top_n(., 15, co2) %>%
arrange(co2) %>%
mutate(n = -5:9) %>%
rowwise() %>%
mutate(x = list(c(-20, 0, 0, -20)),
y = list(c(n*4 - 1.4, n*2 - 0.7, n*2 + 0.7, n*4 + 1.4))) %>%
unnest(cols = c(x, y)) %>% as.data.frame()
数据可视化
ggplot(food_co2) +
geom_rect(aes(xmin = -42, ymin = n*4 - 1.4,
xmax = -20, ymax = n*4 + 1.4), fill = "grey80", color = NA) +
geom_polygon(aes(x, y, group = n), fill = "grey70", color = NA) +
geom_rect(aes(xmin = 0, ymin = n*2 - 0.7,
xmax = co2/30, ymax = n*2 + 0.7), fill = "grey", color = NA) +
geom_text(aes(-40.5, n*4, label = country),color = "white", hjust = 0, size =6,
check_overlap = TRUE) +
geom_text(aes(co2/30-1, n*2, label = co2),color = "black",hjust = 1,
size = 4, check_overlap = TRUE) +
scale_x_continuous(breaks = seq(0,80,20),labels = seq(0,2000,500)) +
theme_minimal() +
theme(
axis.title.x = element_blank(),
axis.text.x = element_text(size = 12),
axis.title.y = element_blank(),
axis.text.y = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_line(color = "grey80", size = 0.2),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
plot.margin = margin(10,10,10,10))
数据获取
❝可以看到通过一些细节的调整,常见的条形图给人一种新的视觉冲击,转发此文档附上一句话到朋友圈后台截图给我,即可获取对应的数据及代码
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
2022-02-28
2022-02-21
2022-02-18
2022-02-17
2022-02-07
2022-02-11
2022-02-06
2022-01-28
2022-01-26
2022-01-25
2022-01-24