user11916948
user11916948

Reputation: 954

Stacked and grouped barplots

I want to make a stacked and grouped barplot. I would like to manage in base R. As my output I would like to present "R", and "W" next to each other for each id. I want each stack to be named R/W and underneath it should say which id it belongs to. Does anyone have a suggestion of how to manage this? Thanks!

 id <- rep(1:10,each=2)

trt <- rep(c("R","W"), 2)
set.seed(1)
A <- sample(100,10)
set.seed(2)
B <- sample(100,10)

df <- data.frame(id,trt,A,B)
df

dfR <- df[df$trt=="R",]
rownames(dfR) <- dfR$id

par(mar=c(3,2,2,5))
par(mfrow=c(2,1))
  
co <- c("red", "blue")
dfR_ <- t(as.matrix(dfR[,-c(1,2)]))
barplot(dfR_, main="R",
        xlab="nmol/L", col=co)


r<- rev((rownames(dfR_)))
legend("topright", inset=c(-0.1,0.15), legend=r, pch=15, col=rev(co))


dfR <- df[df$trt=="W",]
rownames(dfR) <- dfR$id

co <- c("red", "blue")
dfR_ <- t(as.matrix(dfR[,-c(1,2)]))
barplot(dfR_, main="W",
        xlab="nmol/L", col=co)

par(mar=c(3,2,2,5))

r<- rev((rownames(dfR_)))
legend("topright", inset=c(-0.1,0.15), legend=r, pch=15, col=rev(co))

enter image description here

Upvotes: 1

Views: 86

Answers (1)

jay.sf
jay.sf

Reputation: 73802

Transpose your data matrix and use the space= option to define nice spaces, let them recycle. barplot invisibly outputs the bar positions b that we exploit to give the R and W labels. For the IDs we may easily use the means between.

m <- t(as.matrix(df[-(1:2)]))
clr <- c("red", "blue")
prange <- c(0, max(colSums(m)))

b <- barplot(m, space=c(1.25, .25), col=clr, main="My Plot", ylim=prange*1.05)
mtext( rep(c("R", "W"), 10), 1, -.15, at=b, cex=.7, font=2)
mtext(1:10, 1, 1, at=rowMeans(matrix(b, ncol=2, b=T)))
legend("topleft", leg=c("A", "B"), col=1, pt.bg=clr, pch=22, horiz=T, bty="n")
box()

enter image description here


Data:

df <- structure(list(id = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 5L, 5L, 
6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 10L, 10L), trt = c("R", "W", 
"R", "W", "R", "W", "R", "W", "R", "W", "R", "W", "R", "W", "R", 
"W", "R", "W", "R", "W"), A = c(68L, 39L, 1L, 34L, 87L, 43L, 
14L, 82L, 59L, 51L, 68L, 39L, 1L, 34L, 87L, 43L, 14L, 82L, 59L, 
51L), B = c(85L, 79L, 70L, 6L, 32L, 8L, 17L, 93L, 81L, 76L, 85L, 
79L, 70L, 6L, 32L, 8L, 17L, 93L, 81L, 76L)), class = "data.frame", row.names = c(NA, 
-20L))

Upvotes: 4

Related Questions