美文网首页
【R语言】--- 面积图

【R语言】--- 面积图

作者: 生态数据 | 来源:发表于2023-07-16 10:54 被阅读0次

    基本简介

    面积图(Area chart)结合了折线图和条形图,以显示一个或多个组的数值如何随第二个变量(通常是时间)的变化而变化。面积图与折线图的区别在于在线和基线之间增加了阴影,就像条形图一样。在R中,可以用ggplot2包的geom_area()函数进行绘制。

    示例代码

    #调用需要的R包
    library(ggplot2)
    library(dplyr)
    
    #创建数据集
    time <- as.numeric(rep(seq(1,7),each=7))  # x Axis
    value <- runif(49, 10, 100)               # y Axis
    group <- rep(LETTERS[1:7],times=7)        # group, one shape per group
    data <- data.frame(time, value, group)
    #查看数据集(前6行)
    head(data)
    
    # 绘制基本的面积图(堆叠)
    ggplot(data, aes(x=time, y=value, fill=group)) + 
        geom_area()
    
    #
    # 设置group的顺序
    data$group <- factor(data$group , levels=c("B", "A", "D", "E", "G", "F", "C") )
    
    # 绘图
    ggplot(data, aes(x=time, y=value, fill=group)) + 
        geom_area()
    
    #计算百分比(dplyr包)
    library(dplyr)
    data <- data  %>%
      group_by(time, group) %>%
      summarise(n = sum(value)) %>%
      mutate(percentage = n / sum(n))
    
    # 设置group的顺序
    data$group <- factor(data$group , levels=c("B", "A", "D", "E", "G", "F", "C") )
    
    # 绘图
    ggplot(data, aes(x=time, y=percentage, fill=group)) + 
      geom_area(alpha=0.6 , size=1, colour="black")
    

    参考文献

    [1] https://r-graph-gallery.com/index.html
    [2] https://www.modb.pro/db/509252
    [3] https://www.data-to-viz.com/graph/stackedarea.html#:~:text=A%20stacked%20area%20chart%20is%20the%20extension%20of,numeric%20variable%2C%20and%20the%20importance%20of%20each%20group.

    相关文章

      网友评论

          本文标题:【R语言】--- 面积图

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