rnso
rnso

Reputation: 24593

How to add title to the legend in this barplot in R

I have following data and code to make this barplot:

tt = structure(c(21.5, 19.75, 15.05, 26.925, 19.75, NA, 28.2, 19.7, 
15.4), .Dim = c(3L, 3L), .Dimnames = list(c("4", "6", "8"), c("3", 
"4", "5")))

tt
      3      4    5
4 21.50 26.925 28.2
6 19.75 19.750 19.7
8 15.05     NA 15.4

barplot(tt, beside=T, legend=rownames(tt))

enter image description here

I want to add a title (say "Test") to the legend box. I tried following but it does not work:

barplot(tt, beside=T, legend=rownames(tt), legend.text="Test")

also:

barplot(tt, beside=T, legend=rownames(tt))
legend("topright", legend="test")

Thanks for your help.

Upvotes: 4

Views: 9707

Answers (1)

Joris Meys
Joris Meys

Reputation: 108583

You can use the argument args.legend to pass extra arguments to the function legend(), like this:

barplot(tt, beside=TRUE, legend=rownames(tt),args.legend=list(title="aTitle"))

Gives:

barplot

Note that you can also pass other arguments of the legend() function in the same way, so you can adjust the appearance further with the arguments you find on the help page ?legend.

Upvotes: 5

Related Questions