基本簡介
面積圖(Area chart)結(jié)合了折線圖和條形圖狡刘,以顯示一個或多個組的數(shù)值如何隨第二個變量(通常是時間)的變化而變化脖镀。面積圖與折線圖的區(qū)別在于在線和基線之間增加了陰影潘懊,就像條形圖一樣易核。在R中匈织,可以用ggplot2包的geom_area()函數(shù)進行繪制。
示例代碼
#調(diào)用需要的R包
library(ggplot2)
library(dplyr)
#創(chuàng)建數(shù)據(jù)集
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)
#查看數(shù)據(jù)集(前6行)
head(data)
# 繪制基本的面積圖(堆疊)
ggplot(data, aes(x=time, y=value, fill=group)) +
geom_area()
#
# 設(shè)置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))
# 設(shè)置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.