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.

1
2
3
4
5
6
7
8
9
10
# `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:)