美文网首页
ggplot2绘制小清新箭头图

ggplot2绘制小清新箭头图

作者: R语言数据分析指南 | 来源:发表于2022-05-12 09:39 被阅读0次

欢迎关注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))

数据获取

本节内容到此结束,喜欢的小伙伴欢迎分享转发,评论区留言交流可获取数据

相关文章

网友评论

      本文标题:ggplot2绘制小清新箭头图

      本文链接:https://www.haomeiwen.com/subject/isjsurtx.html