I have a data frame df in R, that looks like this:
D C B E K R
Rd 80 80 80 80 80 80
Sw 100 100 100 100 100 100
Sf 100 100 100 100 100 100
I'm trying to plot the data in a bar plot. I need the y axis to have the range 0-100, and the x axis to be the category names. Basically, I need it to look like this:
100 | _ _ _ _ _ _ _ _ _ _ _ _
|_ _ _ _ _ _ | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | |
0 |_|_|_|_|_|_|__|_|_|_|_|_|_|__|_|_|_|_|_|_|_
D C B E K R D C B E K R D C B E K R
Rd Sw Sf
With all of the Ds the same color, all of the Cs the same colour, and so on.
I'm not sure how to do this, or which libraries to use.
So far I have:
counts <- as.matrix(df$D, df$C, df$B, df$E, df$K, df$R)
barplot(counts, beside = TRUE, space = c(0, 0, 0, 0, 0, 0), xlab = "",
col = c("coral", "coral1", "coral2", "coral3", "coral4", "cornflowerblue"),
names.arg = c("D", "C", "B", "E", "K", "R"))
mtext(side = 1, text = "x label", line = 7)
But it only displays something like this:
100 | _ _ _ _
|_| | |_| | |
| | | | | | |
| | | | | | |
| | | | | | |
0 |_|_|_|_|_|_|_
D C B E K R
x label
I'm not sure why I'm getting only this.
Any help would be much appreciated.
Try this:
df2 <- t(as.matrix(df))
bp <- barplot(df2,beside=TRUE,col=1:6)
mtext(rownames(df2),1,at=bp)
If you would like to edit things to spin axis labels or exactly position the group/bar labels, then you can do something like the below code. Change the line=
arguments to affect the vertical position of the labels and the las=1
argument on the barplot
call to spin the labels as required.
df2 <- t(as.matrix(df))
bp <- barplot(df2,beside=TRUE,col=1:6,axisnames=FALSE,las=1)
mtext(rownames(df2),1,at=bp,line=0.6)
mtext(colnames(df2),1,at=colMeans(bp),line=2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With