I can't seem to wrap my mind around the way R requires the data for a stacked barplot although I have search the net and the available resources.
I have the following data
df<-c("III", "III", "I", "I", "I", "II", "I", "I", "I", "I", "I",
"II", "I", "I", "I", "I", "I", "I", "I", "II", "I", "III", "II",
"II", "III", "I", "II", "II", "I", "I", "IV", "I", "III", "I",
"III", "I", "I", "II", "I", "II", "II", "I", "II", "I", "II",
"II", "II", "II", "I", "I", "II", "I", "I", "I", "I", "I", "I",
"II", "II", "III", "I", "III", "I", "I", "I", "I", "II", "I",
"II", "III", "I", "I", "I", "I", "III", "II", "II", "I", "I",
"II", "I", "II", "III", "II", "III", "II", "III", "I", "III",
"III")
I would like to create a single bar stacked barplot with the percentages of I, II, III, IV. I can only get R to do the following
barplot(table(df)*100/90, col=c("white", "gray70", "gray40", "black"), ylim=c(0,100))
Is there any way to make this a single bar stacked barplot? Please baseR solutions only. Thanks
Here's a solution using ggplot
, which does not require numerical vector/matrix as input for a bar plot.
library(ggplot2)
ggplot(data.frame(df))+geom_bar(aes(x="df",fill=df),position="stack")
Here is one possibility (inspired by http://r.789695.n4.nabble.com/How-to-add-marker-in-Stacked-bar-plot-td4635946.html ):
df<-c("III", "III", "I", "I", "I", "II", "I", "I", "I", "I", "I",
"II", "I", "I", "I", "I", "I", "I", "I", "II", "I", "III", "II",
"II", "III", "I", "II", "II", "I", "I", "IV", "I", "III", "I",
"III", "I", "I", "II", "I", "II", "II", "I", "II", "I", "II",
"II", "II", "II", "I", "I", "II", "I", "I", "I", "I", "I", "I",
"II", "II", "III", "I", "III", "I", "I", "I", "I", "II", "I",
"II", "III", "I", "I", "I", "I", "III", "II", "II", "I", "I",
"II", "I", "II", "III", "II", "III", "II", "III", "I", "III",
"III")
freq <- table(df)
df <- data.frame(names=names(freq), freq=as.vector(freq))
barplot(as.matrix(df[,2]), col=cm.colors(length(df[,2])), legend=df[,1], xlim=c(0,6), width=1)
Following will work for you but it wont look good
barplot(as.matrix(table(df)*100/90),
col=c("white", "gray70", "gray40", "black"),
ylim=c(0,100))
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.