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.

    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),..)
  • 1
    $\begingroup$ Someone tag this with R $\endgroup$ Aug 11, 2011 at 3:31
  • $\begingroup$ @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. $\endgroup$
    – user88
    Aug 11, 2011 at 7:36
  • $\begingroup$ @Brandon Sure; you can use suggested edits in future, you would also earn 2 rep for accepted suggestion. $\endgroup$
    – user88
    Aug 11, 2011 at 7:37

2 Answers 2


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) +

enter image description here

and using lattice:

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

enter image description here

  • $\begingroup$ @Brandon - It's my new mission. These questions are better references for others if they contain examples from base, ggplot2 and lattice. $\endgroup$
    – joran
    Aug 11, 2011 at 3:38
  • $\begingroup$ @Joran: Fantastic. $\endgroup$
    – samarasa
    Aug 11, 2011 at 3:39
  • $\begingroup$ How to rename the label on "factor(id)" in the ggplot version? $\endgroup$
    – 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, 
legend(13, 12, c("Label1","Label2","Label3","Label4","Label5"), cex=0.6, 


Hope this answers your question.


Not the answer you're looking for? Browse other questions tagged or ask your own question.