2

I'm trying to plot a legend in base R with the symbols horizontally and the corresponding labels underneath the symbols on the next row. The legend will be plotted in the margins (not included in example data). Is there a way to use graphical parameters to solve this with the legend() function? Otherwise I will try the text labels, but I prefer a more manageable approach.

I have this example data:

plot(c(1,2,3,4,5), c(1,2,3,4,5), xlim=c(0,5), ylim=c(0,5),  main = "", xlab = "", ylab = "")

legendEntries <- c(0.05, 0.1, 0.15, 0.2, 0.25) # which values in legend
legendSizes   <- sqrt( legendEntries / pi ) * 10 # calculate pch size 
legend(1, 2, title="", horiz = T,  legend=legendEntries, col="black", pch=rep(21,5), 
   pt.bg = "#ff166c", pt.cex = legendSizes, bty = "n")

And want to create something like this:

legend example

Thanks!

Paul

(edit: added picture in text and extra info)

Community
  • 1
  • 1
romepa
  • 23
  • 6

1 Answers1

1

You can plot separately points and text.

Something like:

# Make the basic plot
    plot(c(1,2,3,4,5), c(1,2,3,4,5), xlim=c(0,5), ylim=c(0,5),  main = "", xlab = "", ylab = "")
    # set up the legend entries and sizes
    legendEntries <- c(0.05, 0.1, 0.15, 0.2, 0.25) # which values in legend
    legendSizes   <- sqrt( legendEntries / pi ) * 10 # calculate pch size 

# plot the legend points
    points(y = rep(1, 5), x = seq(3,4, 0.25), pch = 21, cex = sqrt( legendEntries / pi ) * 10,
           bg = "#ff166c")
# plot the text
    text(y = rep(0.7, 5), x = seq(3,4, 0.25),
         labels = legendEntries)

For Plotting outside of the plot region (i.e. on the margins), you can use the xpd parameter as xpd = TRUE:

plot(c(1,2,3,4,5), c(1,2,3,4,5), xlim=c(0,5), ylim=c(0,5),  main = "", xlab = "", ylab = "")

legendEntries <- c(0.05, 0.1, 0.15, 0.2, 0.25) # which values in legend
legendSizes   <- sqrt( legendEntries / pi ) * 10 # calculate pch size 

points(y = rep(-0.8, 5), x = seq(1,2, 0.25), pch = 21, cex = sqrt( legendEntries / pi ) * 10,
       bg = "#ff166c", xpd = TRUE)
text(y = rep(-1, 5), x = seq(1,2, 0.25),
     labels = legendEntries, xpd = TRUE)
ira
  • 2,542
  • 2
  • 22
  • 36
  • Thanks, but I'm trying to plot the legend in the plot margins. This seems to work only in the plot area. I can try to combine the "plot the text" part with a legend(), but I was hoping there was a way of using graphical parameters to solve it. – romepa Feb 20 '17 at 14:17
  • Nice, thanks. I can work with that. Since the legend I want is quite basic, I don't really need the legend() function. – romepa Feb 20 '17 at 14:42