I have a sample data like this: It looks simple but I can't figure the way out, I'm new to R. Please help!
clust4 catch
1 131711493
2 41683530
3 143101724
4 35849946
How can I get a stacked bar plot which shows the percentage of each cluster by the value of the catch column? and get the legend name like this below:
group(legend name)
Cluster1
Cluster2
Cluster3
Cluster4
I have tried many times but it just showed 4 different stacked bar plots and also couldn't change the legend name from 1,2,3,4 to cluster 1,...)
Sorry for not inserting any photo because I don't have enough reputation to do that.
This is the basic code for stacked bar plot in R using ggplot2 library change the variables according to your dataset and plot it
# 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")
Solution1: 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()
Solution2: graphics
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"))
Color Proportion
clust4 catch
1 Cluster-1 0.3738122
2 Cluster-2 0.1183026
3 Cluster-3 0.4061390
4 Cluster-4 0.1017462
Data
df <- read.table(text = "clust4 catch
1 131711493
2 41683530
3 143101724
4 35849946", header = T)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.