Search code examples
rplotcustomizationlegendlegend-properties

How can I plot legend symbols and labels on a different row in R?


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)


Solution

  • 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)