Data visualization in R: Show legend outside of the plotting area

If you add a legend to a plot, it will be placed inside the plotting area by default. The following example creates a stacked bar plot with the sales data of books, magazines and newspapers. In such type of plots you will normally use a legend to describe the data.

months = c(’01/2014′, ’02/2014′, ’03/2014′)
 
sales = data.frame(
books = c(15,17,11),
magazines = c(8,8,9),
newspapers = c(11,10,9))
 
sales <- do.call(rbind,sales)
 
barplot(sales, ylim=c(0,50), legend.text = rownames(sales), args.legend = list(x = ‚topright‘, bty=’n‘), names.arg = months)

 
With the parameter x = ‚topright‘ the legend is placed at the top right position inside the plot. The parameter bty=’n‘ hides the box around the legend. The following plot will be created.
 
R16_a
 
As you can see the legend is shown inside the plotting area. This may be acceptable if the legend doesn’t need much space. In this example the legend is not very large so I have increased the upper limit of the y row a little bit to create some space for the legend.

 
Place legend outside the plotting area

As already mentioned it could be adversely to place the legend inside the plot. But luckily it’s very easy to move the legend outside the plot. For example you may place it on the right side of the graphic. The following code shows the above example with some minor modifications.

months = c(’01/2014′, ’02/2014′, ’03/2014′)
 
sales = data.frame(
books = c(15,17,11),
magazines = c(8,8,9),
newspapers = c(11,10,9))
 
sales <- do.call(rbind,sales)
 
par(mar = c(5,4,4,8))
 
barplot(sales, ylim=c(0,40),
legend.text = rownames(sales),
args.legend = list(x = ‚right‘, bty=’n‘, inset=c(-0.50,0), xpd = TRUE),
names.arg = months)

 
R16_b

 
The following parameters where changed or added:

  • x = ‚right‘: to move the legend to the right side inside the plot
  • inset: to move the legend (in this case by 50% of the graphic width)
  • xpd=TRUE: to allow positioning of the legend outside of the plot

 
Furthermore you have to create some space for legend at the right side of the plot. So I have increased the margin at the right side by using the par(mar = …) command.

Werbung
Dieser Beitrag wurde unter R veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit deinem WordPress.com-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s