allenfrostline

How to Get Legends Out of the Plotting Area in R

2017-09-30


Recently when writing a course report, I encountered a tricky problem in R programming: how can I include the legends while making sure that they don’t overlay the plots?

This is easy to tackle in Python, but for the default plotting function in R I did struggle for quite a while.

# `percentage.table()` is a function defined by me.
# `f` is a vector of all classes and `len` is the length of `f`.
barplot(percentage.table(clusters),col=heat.colors(len),
        legend.text=f,
        args.legend=list(x="topright",
                         inset=c(-.2,0),
                         xpd=T,
                         fill=heat.colors(len),
                         bty="n"))
title("Barchart of Clusters")

Based on such constructions you can get plots like this:

I hope this helps if you have the same question:)