R语言绘制冲积图

R语言绘图

第一篇 R语言绘制会议图

前言

冲积图,也叫桑基图。它是一种特定类型的流程图,延伸的分支的宽度对应数据流量的大小,充分展现了数据的流动情况。


一、加载R包和数据集

本文中绘制冲击图需要用到的R包如下所示,请在使用前确保安装完成:

install.packages("ggalluvial")
install.packages("ggplot2")
library(ggalluvial)
library(ggplot2)

本文利用的数据集为Titanic,使用前先将其转化为数据框格式:

df<-as.data.frame(Titanic)
df

二、绘制冲击图

1.函数解释

  • geom_alluvium()绘制冲积图
  • geom_stratum()获取冲积地块地层数据集,为给定宽度的地层绘制矩形
  • geom_text()向图形添加文本
  • scale_x_discrete()给x轴添加标签

2.图形输出

ggplot(as.data.frame(Titanic),
       aes(y = Freq,
      axis1 = Class, axis2 = Sex,axis3=Age)) +
  geom_alluvium(aes(fill=Survived))+
  geom_stratum() +
  geom_text(stat = "stratum", aes(label = after_stat(stratum))) +
  scale_x_discrete(limits = c("Class", "Sex","Age"),expand = c(.3, .05))+
  xlab("Alluvia across strata")+
  theme_minimal() +
  ggtitle("Variable:",
          "Class,Sex,Age,Survived")

在这里插入图片描述

3.分组绘制

如果要根据Age变量分别绘制冲积图,则只要加上一行参数
facet_wrap(~ Age, scales = “free_y”),对其他参数作相应修改

ggplot(as.data.frame(Titanic),
       aes(y = Freq,
      axis1 = Class, axis2 = Sex)) +
  geom_alluvium(aes(fill=Survived))+
  geom_stratum() +
  geom_text(stat = "stratum", aes(label = after_stat(stratum))) +
  scale_x_discrete(limits = c("Class", "Sex"),expand = c(.3, .05))+
  xlab("Alluvia across strata")+
  theme_minimal() +
  ggtitle("Variable:",
          "Class,Sex,Age,Survived")+
  facet_wrap(~ Age, scales = "free_y")

在这里插入图片描述

4.其它冲积图

  • 五次流的时间序列凸点图
gg <- ggplot(alluvial::Refugees,
             aes(y = refugees, x = year, alluvium = country))
gg + geom_alluvium(aes(fill = country, colour = country),
                   width = 1/4, alpha = 2/3, decreasing = FALSE,
                   curve_type = "sigmoid")

在这里插入图片描述

  • 基于国家分类的时间序列图
gg + geom_alluvium(aes(fill = country, colour = country),
                   decreasing = NA, width = 0, knot.pos = 0)

在这里插入图片描述

  • 变量之间间距不规则
refugees_sub <- subset(alluvial::Refugees, year %in% c(2003, 2005,2007, 2010, 2013))
gg <- ggplot(data = refugees_sub,
             aes(x = year, y = refugees, alluvium = country)) +
  theme_bw() +
  scale_fill_brewer(type = "qual", palette = "Set3")
gg +
  geom_alluvium(aes(fill = country),
                alpha = .75, decreasing = FALSE, width = 1/2) +
  geom_stratum(aes(stratum = country), decreasing = FALSE, width = 1/2)

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值