How to place the legend outside the barplot in R




I wanted to plot a stacked bar plot using two columns of my dataset. I used->


and I get a plot like this->

I want the legend to be outside the plot and not on the plot. How can I do this?




Maybe what you need is par(xpd=TRUE) to enable things to be drawn outside the plot region. So if you do the main plot with bty=‘L’ you’ll have some space on the right for a legend. Normally this would get clipped to the plot region, but do par(xpd=TRUE) and with a bit of adjustment you can get a legend as far right as it can go:

and then edit the legend code below

so turn off clipping:

legend(2.8,-1,c(“group A”, “group B”), pch = c(1,2), lty = c(1,2))

but I need help, right

so I do this at the console


and find this

legend(x, y = NULL, legend, fill = NULL, col = par(“col”),
border = “black”, lty, lwd, pch,
angle = 45, density = NULL, bty = “o”, bg = par(“bg”),
box.lwd = par(“lwd”), box.lty = par(“lty”), box.col = par(“fg”), = NA, cex = 1, pt.cex = cex, pt.lwd = lwd,
xjust = 0, yjust = 1, x.intersp = 1, y.intersp = 1,
adj = c(0, 0.5), text.width = NULL, text.col = par(“col”),
text.font = NULL, merge = do.lines && has.pch, trace = FALSE,
plot = TRUE, ncol = 1, horiz = FALSE, title = NULL,
inset = 0, xpd, title.col = text.col, title.adj = 0.5,
seg.len = 2)

x, y
the x and y co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.coords: See ‘Details’.