其他
ggplot2优雅绘制小清新版箭头图
欢迎关注R语言数据分析指南
❝常见的条形图看腻了,试试这种小清新的「箭头图」吧,一点细微的改动赋予图新的美感,下面来看具体案例
❞
安装并加载R包
package.list=c("tidyverse","magrittr","cowplot")
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")
数据清洗
df %<>% filter(alt!="Total") %>%
pivot_longer(-alt) %>%
filter(alt %in% c("E85","HEVs","PEVs","CNG")) %>%
group_by(alt) %>%
mutate(diff = (value/lag(value) - 1)) %>%
filter(!is.na(diff)) %>%
mutate(col=case_when(diff<0~"Decrease", diff>0~"Increase"),
name=parse_number(name))
数据可视化
df %>% ggplot(aes(x=name, y=diff)) +
geom_hline(yintercept=0, size=.3) +
geom_segment(aes(y=0, yend=diff, x=name, xend=name, color=col),
arrow = arrow(type = "closed", length = unit(1.5, "mm")),
size=1, key_glyph = draw_key_rect) +
scale_y_continuous(breaks=seq(-.5,2,.5), labels=scales::percent_format()) +
scale_color_manual(values=c("#D68E24","#139E56")) +
facet_wrap(~alt, scales="free_x") +
cowplot::theme_minimal_hgrid(11) +
theme(legend.position="top",
legend.text=element_text(size=10,color="black"),
legend.justification = "center",
panel.spacing.x = unit(1, "lines"),
panel.spacing.y = unit(1, "lines"),
legend.title=element_blank(),
axis.title = element_blank(),
axis.text=element_text(color="black"),
strip.text=element_text(size=11.5,color="black",face="bold"),
plot.margin=margin(.5,.75,.5,.5,unit="cm"),
plot.background = element_rect(fill="#fafafa", color=NA),
axis.ticks.length=unit(.25, "cm"),
) +guides(color=guide_legend(reverse=T))
数据获取
❝本节内容到此结束,可以看到图表非常的清爽,喜欢的小伙伴欢迎转发此文档附上一句话到朋友圈「30分钟后后台截图给我」,即可获取对应的数据及代码,如未及时回复可添加我的微信
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
往期推荐