如何在 R 中绘制堆积条形图?

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)