Samrat
Samrat

Reputation: 89

How to make three different bar charts of similar type clustered in the same plot?

I need to map my Erosion values for different levels of tillage (colomns) with three levels of soil depth (rows (A1, A2, A3)). I want all of this to be shown as a barchart in a single plot.

Here is a reproducible example:

a<- matrix(c(1:36), byrow = T,  ncol = 4)
rownames(a)<-(c("A1","B1","C1","A2","B2","C2","A3","B3","C3"))
colnames(a)<-(c("Int_till", "Redu_till", "mulch_till", "no_till"))

barplot(a[1,], xlab = "A1", ylab = "Erosion") 
barplot(a[4,], xlab = "A2", ylab = "Erosion")
barplot(a[7,], xlab = "A3", ylab = "Erosion")
##I want these three barchart side by side in a single plot
## for comparison 

### and need similar plots for all the "Bs" and "Cs"  
### Lastly, i want these three plots in the same page.

I have seen people do similar things using "fill" in ggplot (for lines) and specifying the factor which nicely separates the chart for different categories but I tried doing it but always run into error maybe because my data is continuous.

If any body could help me with these two things.. It will be a great help. I will appreciate it.

Thank you!

Upvotes: 1

Views: 203

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270348

Set mfcol to specify a 3x3 grid and then for each row generate its bar plot. Also, you could consider adding the barplot argument ylim = c(0, max(a)) so that all graphs use the same Y axis. title and mtext can be used to set the overall title and various margin text as we do below. See ?par, ?title and ?mtext for more information.

opar <- par(mfcol = c(3, 3), oma = c(0, 3, 0, 0))
for(r in rownames(a)) barplot(a[r, ], xlab = r, ylab = "Erosion")
par(opar)

title("My Plots", outer = TRUE, line = -1)
mtext(LETTERS[1:3], side = 2, outer = TRUE, line = -1, 
  at = c(0.85, 0.5, 0.17), las = 2)

screenshot

Upvotes: 1

akrun
akrun

Reputation: 887961

We can use ggplot

library(reshape2)
library(ggplot2)
library(dplyr)
melt(a) %>%
      ggplot(., aes(x = Var2, y = value, fill = Var1)) + 
         geom_bar(stat = 'identity',
              position = position_dodge2(preserve = "single")) + 
         facet_wrap(~ Var1)

Upvotes: 1

Related Questions