Melisa
Melisa

Reputation: 39

Stacked barplots

I imported my table, which included the information. It looks like this: Categories Number Gender 1 278 male 1 13 female 2 890 male 2 60 female 3 80 male 3 1029 female

I tried to do a stacked barplot, which should show me on the xaxis the categories (1,2,3), on the yaxis the numbers, but the barplots should also show me the females and males in the different categories.

Thank you in advance!

Upvotes: 0

Views: 494

Answers (1)

emilliman5
emilliman5

Reputation: 5966

Based on the data you provided I think you are looking for something like this, to me "stacked" means that the male and female number are on top of each other to also show the total. The beside argument buts the bars next to each other for male and female.

x <- "1 278 male 
      1 13 female 
      2 890 male 
      2 60 female 
      3 80 male 
      3 1029 female"

R <- read.table(textConnection(x))
colnames(R) <- c("Categories", "Number", "Gender")
dat <- reshape(R,direction = "wide", idvar = c("Gender"), timevar = c("Categories")) ##barplot requires a vector of heights or a matrix
colnames(dat) <- gsub("Number", "Category", colnames(dat))
barplot(as.matrix(dat[,2:4]), col=c(2,3))
legend("topleft", bty="n", col=c(2,3), legend=dat[, 1], pch=15)

Stacked barplot

enter image description here

Side-by-side

barplot(as.matrix(dat[,2:4]), col=c(2,3), beside = T)
legend("topleft", bty="n", col=c(2,3), legend=dat[, 1], pch=15)

enter image description here

Upvotes: 1

Related Questions