【R语言】--- 面积图

2023-07-16  本文已影响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.

上一篇下一篇

猜你喜欢

热点阅读