Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R plot: Displaying both point type and line type in legend

Tags:

plot

r

legend

I have generated a plot with plot function. I added the point markers with pch() and the line type with lty. In the legend section I wanted to merge the points and lines together. I used merge=TRUE but it didn't work. It is displaying the line type only. The same thing with merge=FALSE. In both cases there is only slight change in the box legend box width. That is it. Any idea?

Here is the sample code:

m<-1:10
n<-runif(1:5)

plot(m,type = "o", col="blue",main = "plot",xlab = "distance",ylab = "height")
lines(n+2,type="o", pch=22,lty=6,col="red")
lines(m-3,type="o", pch=17,lty=5,col="forestgreen")

legend(x=2,y=8,c("R","S","T"),lty=c(1,6,5),pch=c(5,22,17),
       cex=.8, col=c("blue","red","forestgreen"),merge = FALSE)
like image 685
G1124E Avatar asked Jun 18 '16 14:06

G1124E


1 Answers

People have asked you to put in some toy code. This is important as it gives people a starting point to help you. Actually it is not difficult to do this. Consider the following:

set.seed(0); x1 <- rnorm(10); x2 <- rnorm(10); x3 <- rnorm(10)
plot(x1, type = "b", pch = 19, lty = 1, col = 1,
     ylim = range(c(x1,x2,x3)))  ## both points and lines
points(x2, pch = 19, col = 2)  ## only points
lines(x3, lty = 2, col = 3)  ## only lines
legend(6, 0.9*max(c(x1,x2,x3)), legend = c("x1", "x2", "x3"),
       pch = c(19, 19, NA), lty = c(1, NA, 2),
       col = c(1,2,3), text.col = c(1,2,3))

test

Use NA to control what you want to display.


Follow-up

I forgot to include the pch in the legend(). When I included that the point are displaying at the right tip of each line in the legend. Is there some way of centring them?

Great! Now you have included your code in your question. The problem is with your final call to legend(). Do not use/set argument merge:

legend(x=2,y=8,c("R","S","T"),lty=c(1,6,5),pch=c(5,22,17),
       cex=.8, col=c("blue","red","forestgreen"))

This will do what you want.

like image 69
Zheyuan Li Avatar answered Oct 14 '22 13:10

Zheyuan Li