Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make R legend with 2 columns?

Tags:

plot

r

legend

I want to make a legend on my graph, which is generated by plot() function. The original legend() function will generate a list which has only 1 column. How can I make a legend which has 2 columns?

Wanted legend

like image 607
Felix Chan Avatar asked Apr 17 '15 06:04

Felix Chan


People also ask

How do I show multiple columns in R?

R – Get Multiple Columns of Matrix To get multiple columns of matrix, specify the column numbers as a vector preceded by a comma, in square brackets, after the matrix variable name. This expression returns the required columns as a matrix.

Can you have two columns with the same name in R?

Because, usually R dataframes do not allow exact same names (when you create them using data. frame() ). Which means dataframes should not have the same column names.


2 Answers

I could not find a way to do that within a single call to legend for standard plots.

Here's an option, drawing two separate legends: one with lines and points, one with labels. x.intersp can be used to tweak distance between labels and lines.

plot(cumsum(runif(n = 100)))

# draw legend with lines and point but without labels and box. x.intersp controls horizontal distance between lines
L = legend(x = 'bottom', legend = rep(NA,4), col=1:2, lty=c(1,1,2,2), ncol=2, bty='n', x.intersp=0.5, pch=c(1,2,1,2), inset=0.02)

# use position data of previous legend to draw legend with invisble lines and points but with labels and box. x.intersp controls distance between lines and labels
legend(x = L$rect$left, y = L$rect$top, legend = c('Group A', 'Group B'), col=rep(NA,2), lty=c(1,1), ncol=1, x.intersp = 3, bg = NA)

enter image description here

like image 130
koekenbakker Avatar answered Sep 22 '22 07:09

koekenbakker


Check this:

library(lattice)

myPCH <- 15:17
Data  <- rnorm(50)
Index <- seq(length(Data))

xyplot(Data ~ Index, 
       pch = myPCH, col=1:2,
       key = list(space = "right", adj=1,
                  text = list(c("a", "b", "c"), cex=1.5),
                  points = list(pch = myPCH),
                  points = list(pch = myPCH,col=2)))

enter image description here

like image 23
Prasanna Nandakumar Avatar answered Sep 22 '22 07:09

Prasanna Nandakumar