# Drawing multiple barplots on a graph in R [closed]

I would like to plot four barplots on a single graph in R. I have used the following code. Here, how can keep a legend on top of the graph, specifically the legend should be between 2 and 3 barplots. I also tried with par(mar=c(4.1,4.1,8.1,4.1) but there is no success. Moreover, I also tried to run legend() after the second barplot, but there is no use. The legend is for all the four barplots. Please help me in this.

    par(mfrow=c(1,4))
barplot(t(A), beside=T, ylim=c(-100,100),..)
barplot(t(B), beside=T, ylim=c(-100,100),..)
barplot(t(C), beside=T, ylim=c(-100,100),..)
barplot(t(D), beside=T, ylim=c(-100,100),..)
legend(...)

• Someone tag this with R Aug 11, 2011 at 3:31
• @Kevin This is a valid Q here; the fact that R has command line interface does not mean any R question is a programming one.
– user88
Aug 11, 2011 at 7:36
• @Brandon Sure; you can use suggested edits in future, you would also earn 2 rep for accepted suggestion.
– user88
Aug 11, 2011 at 7:37

## 2 Answers

Dr. Mike's answer is a good one, but I thought I'd provide solutions that take advantage of the faceting (or trellising) features of ggplot2 and lattice. First prep the data slightly:

mydata <- data.frame(Barplot1=rbinom(5,16,0.6), Barplot2=rbinom(5,16,0.25),
Barplot3=rbinom(5,5,0.25), Barplot4=rbinom(5,16,0.7))
mydata\$id <- 1:nrow(mydata)
dat <- reshape2::melt(mydata,id.vars = "id")


and then we can make the following in ggplot2:

ggplot(dat,aes(x=factor(id), y = value, fill=factor(id))) +
facet_wrap(~variable) +
geom_bar(stat="identity")


and using lattice:

barchart(~value|variable,group = factor(id),data=dat,
key = simpleKey(text = as.character(1:5),
rectangles = TRUE,points = FALSE,space = "right"))


• @Brandon - It's my new mission. These questions are better references for others if they contain examples from base, ggplot2 and lattice. Aug 11, 2011 at 3:38
• @Joran: Fantastic. Aug 11, 2011 at 3:39
• How to rename the label on "factor(id)" in the ggplot version?
– MLE
Aug 21, 2017 at 21:42

I think the most simple solution is to use barplot command's inherent capabilities to solve your problem. The following code does what I interpret that you want done.

mydata <- data.frame(Barplot1=rbinom(5,16,0.6), Barplot2=rbinom(5,16,0.25),
Barplot3=rbinom(5,5,0.25), Barplot4=rbinom(5,16,0.7))
barplot(as.matrix(mydata), main="Interesting", ylab="Total", beside=TRUE,
col=terrain.colors(5))
legend(13, 12, c("Label1","Label2","Label3","Label4","Label5"), cex=0.6,
fill=terrain.colors(5))


Hope this answers your question.