[英]How to plot a stacked bar plot in R?
我有一個這樣的示例數據:看起來很簡單,但我找不到出路,我是R的新手。請幫助!
clust4 catch
1 131711493
2 41683530
3 143101724
4 35849946
如何獲得堆積的條形圖,以catch列的值顯示每個群集的百分比? 並獲得以下圖例名稱:
group(legend name)
Cluster1
Cluster2
Cluster3
Cluster4
我已經嘗試了很多次,但它只顯示了4種不同的堆疊條形圖,並且也無法將圖例名稱從1,2,3,4更改為簇1,...)
很抱歉沒有插入任何照片,因為我沒有足夠的聲譽。
這是使用ggplot2庫在R中堆疊條形圖的基本代碼,請根據您的數據集更改變量並進行繪制
# library
library(ggplot2)
# create a dataset
specie=c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) ,
rep("triticum" , 3) )
condition=rep(c("normal" , "stress" , "Nitrogen") , 4)
value=abs(rnorm(12 , 0 , 15))
data=data.frame(specie,condition,value)
# Grouped
ggplot(data, aes(fill=condition, y=value, x=specie)) +
geom_bar(position="dodge", stat="identity")
# Stacked
ggplot(data, aes(fill=condition, y=value, x=specie)) +
geom_bar( stat="identity")
# Stacked Percent
ggplot(data, aes(fill=condition, y=value, x=specie)) +
geom_bar( stat="identity", position="fill")
解決方案1:ggplot2
library(tidyverse)
df %>% mutate(catch = catch / sum(catch),
clust4 = paste0("Cluster-", clust4)) %>%
ggplot(aes(x = "", y = catch, fill = clust4)) +
geom_bar(stat = "identity", color = "black") +
coord_flip()
解決方案2:圖形
prop <- df$catch / sum(df$catch)
color <- RColorBrewer::brewer.pal(4, "Set2")
barplot(as.matrix(prop), horiz = T, col = color,
xlim = c(0, 1.2), ylim = c(-0.5, 2),
legend.text = paste0("Cluster-", 1:4),
args.legend = list(x = "right", bty = "n"))
顏色比例
clust4 catch
1 Cluster-1 0.3738122
2 Cluster-2 0.1183026
3 Cluster-3 0.4061390
4 Cluster-4 0.1017462
數據
df <- read.table(text = "clust4 catch
1 131711493
2 41683530
3 143101724
4 35849946", header = T)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.