title: How to set the size of a legend in a barplot in R?
body: <p>I have created a grouped bar chart using <code>barplot</code> in R. Unfortunately, the legend appears abnormally huge and even gets cut off, as you can see from the figure.</p>
  
  <p><a href="https://i.stack.imgur.com/8GVv0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8GVv0.png" alt="enter image description here"></a></p>
  
  <p>Here is the code I have used.</p>
  
  <pre><code># data:
  #           a         b        c
  # U 0.4405316 0.6553628 0.646097
  # H 0.0544850 0.0283912 0.028300
  # L 0.0046512 0.0015773 0.003371
  # M 0.1860465 0.1064669 0.118002
  # O 0.2478405 0.1861199 0.179914
  # P 0.0006645 0.0007886 0.002350
  # T 0.0677741 0.0205047 0.021761
  
      data &lt;- cbind(c(0.4405316, 0.0544850, 0.0046512, 0.1860465, 0.2478405, 
                      0.0006645, 0.0677741),
              c(0.6553628, 0.0283912, 0.0015773, 0.1064669, 0.1861199, 
                0.0007886, 0.0205047),
              c(0.646097, 0.028300, 0.003371, 0.118002, 0.179914, 
                0.002350, 0.021761))
      data &lt;- data.frame(data)
      names(data) &lt;- c("a","b","c")
      rownames(data) &lt;- c("U","H","L","M","O","P","T")
  
      barplot(t(as.matrix(data)), beside=TRUE, 
              col=heat.colors(length(colnames(data))),ylim=c(0,1))
      legend("topright",cex=1,fill=heat.colors(length(colnames(data))), 
             legend=colnames(data),bty = "y")
  </code></pre>
  
  <p>Why is it so bad? The problem doesn't seem to occur <a href="https://stackoverflow.com/questions/13936223/legends-in-barplot-not-appearing-properly">here</a>, where setting the option "topright" does the job.
  I have tried setting the option cex lower than one, but the text of the legend becomes too small, while the problem here is the huge size of the rectangles in the legend.
  Any idea?</p>
  
  <p>Update: I realise now that a similar question was asked <a href="https://stackoverflow.com/questions/32543240/altering-the-margins-of-a-legend-in-r?rq=1">here</a> (basically unanswered).</p>