[英]Grouped barchart in r with 4 variables
我是 r 的初學者,我一直在努力尋找如何 plot 這個圖形。
我有 4 個變量(礫石百分比、沙子百分比、五個地方的淤泥百分比)。 我正在嘗試 plot 這三種沉積物 (y) 在每個站 (x) 中的百分比。 所以它在 x 軸上有 5 個組,每組 3 個條形圖。
Station % gravel % sand % silt
1 PRA1 28.430000 70.06000 1.507000
2 PRA3 19.515000 78.07667 2.406000
3 PRA4 19.771000 78.63333 1.598333
4 PRB1 7.010667 91.38333 1.607333
5 PRB2 18.613333 79.62000 1.762000
我嘗試繪制一個分組條形圖
grao <- read_excel("~/Desktop/Masters/Data/grao.xlsx")
colors <- c('#999999','#E69F00','#56B4E9','#94A813','#718200')
barplot(table(grao$Station, grao$`% gravel`, grao$`% sand`, grao$`% silt`), beside = TRUE, col = colors)
但是此錯誤消息不斷發生:
'height' 必須是向量或矩陣
我也試過
ggplot(grao, aes(Station, color=as.factor(`% gravel`), shape=as.factor(`% sand`))) +
geom_bar() + scale_color_manual(values=c('#999999','#E69F00','#56B4E9','#94A813','#718200')+ theme(legend.position="top")
但它正在創造一個瘋狂的圖形。
有人可以幫我嗎? 我已經被困在這幾個星期了。
干杯
我認為這可能是您正在尋找的:
#install.packages("tidyverse")
library(tidyverse)
df <- data.frame(
station = c("PRA1", "PRA3", "PRA4", "PRB1", "PRB2"),
gravel = c(28.4, 19.5, 19.7, 7.01, 18.6),
sand = c(70.06, 78.07, 78.63, 91, 79),
silt = c(1.5, 2.4, 1.6, 1.7, 1.66)
)
df2 <- df %>%
pivot_longer(cols = c("gravel", "sand", "silt"), names_to = "Sediment_Type", values_to = "Percentage")
ggplot(df2) +
geom_bar(aes(x = station, y = Percentage, fill = Sediment_Type ), stat = "identity", position = "dodge") +
theme_minimal() #theme_minimal() is from the ggthemes package
提供:
您需要“更長”地“轉動”您的數據集。 部分整潔的方法是確保所有列都代表一個變量。 您會在最初的 dataframe 中注意到,每個列名都是一個變量(“Sediment_type”),每個列填充只是每個列的百分比(“Percentage”)。 function
pivot_longer()
采用數據集並允許收集所有列,然后將它們變成兩個 - 標識和值。
完成此操作后,ggplot 將允許您指定 x 軸,然后通過“填充”指定分組變量。 你可以切換這兩個。 如果您最終得到大量數據和分組變量,分面也是一個值得研究的選項!
希望這可以幫助,
布倫南
barplot
想要一個"matrix"
,理想情況下具有兩個維度名稱。 您可以像這樣轉換數據(在將第一列用於行名時刪除第一列):
dat <- `rownames<-`(as.matrix(grao[,-1]), grao[,1])
你會看到,那個barplot
已經為你做了制表。 但是,您也可以使用xtabs
( table
可能不適合您的方法 function)。
# dat <- xtabs(cbind(X..gravel, X..sand, X..silt) ~ Station, grao) ## alternatively
我建議您使用正確的變量名,因為特殊字符不是最好的主意。
colnames(dat) <- c("gravel", "sand", "silt")
dat
# gravel sand silt
# PRA1 28.430000 70.06000 1.507000
# PRA3 19.515000 78.07667 2.406000
# PRA4 19.771000 78.63333 1.598333
# PRB1 7.010667 91.38333 1.607333
# PRB2 18.613333 79.62000 1.762000
然后barplot
知道發生了什么。
.col <- c('#E69F00','#56B4E9','#94A813') ## pre-define colors
barplot(t(dat), beside=T, col=.col, ylim=c(0, 100), ## barplot
main="Here could be your title", xlab="sample", ylab="perc.")
legend("topleft", colnames(dat), pch=15, col=.col, cex=.9, horiz=T, bty="n") ## legend
box() ## put it in a box
數據:
grao <- read.table(text=" Station '% gravel' '% sand' '% silt'
1 PRA1 28.430000 70.06000 1.507000
2 PRA3 19.515000 78.07667 2.406000
3 PRA4 19.771000 78.63333 1.598333
4 PRB1 7.010667 91.38333 1.607333
5 PRB2 18.613333 79.62000 1.762000 ", header=TRUE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.