![](/img/trans.png)
[英]R ggplot2: complex stacked barchart with multiple categorical variables
[英]Stacked barchart same type of variables in ggplot2
我正在嘗試創建一個代表此數據的堆疊條 plot。 變量 n_paper 是使用該方法的論文總數,變量 paper_ui 是有多少論文使用了上升流指數。
n_papers paper_ui methods
1 6 3 AR
2 4 2 ARMA
3 5 4 ARIMA
4 1 0 SARIMA
5 6 1 Loess decomposition
6 2 1 Classical decomposition
7 1 0 Exponential smoothing
ggplot(df,aes(x = methods, y = n_papers)) +
geom_bar(stat="identity", color="dodgerblue4", fill="dodgerblue4")+
scale_x_discrete() + xlab("Time series methods") +
ylab("Nº of papers") +
theme(
axis.title.x = element_text(size=15),
axis.title.y = element_text(size=15),
axis.text = element_text(size=12),
axis.text.x = element_text(angle=45, hjust=1)
)
plot 是這樣的,但我想要該圖中的變量 paper_ui。 謝謝!
嘗試這個。 您必須將數據重新整形為 long 然后 plot:
library(ggplot2)
library(dplyr)
library(tidyr)
#Code
df %>% pivot_longer(-methods) %>%
ggplot(aes(x = methods, y = value,color=name,fill=name)) +
geom_bar(stat="identity")+
scale_x_discrete() + xlab("Time series methods") +
ylab("Nº of papers") +
theme(
axis.title.x = element_text(size=15),
axis.title.y = element_text(size=15),
axis.text = element_text(size=12),
axis.text.x = element_text(angle=45, hjust=1)
)
Output:
使用的一些數據:
#Data
df <- structure(list(n_papers = c(6L, 4L, 5L, 1L, 6L, 2L, 1L), paper_ui = c(3L,
2L, 4L, 0L, 1L, 1L, 0L), methods = c("AR", "ARMA", "ARIMA", "SARIMA",
"Loess decomposition", "Classical decomposition", "Exponential smoothing"
)), row.names = c(NA, -7L), class = "data.frame")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.