Sort points and lines in the r-chart legend

Is it possible to rearrange the legend about the next schedule

plot(1,1, type="n") legend("topleft", c("1", "2"), col=c("darkblue", "darkred"), pch = 1, bty = "n", horiz = T, lwd=1.25, cex=1.8) 

to look like this (point-line-point pattern)? enter image description here

+5
source share
2 answers

Usually, if you need this level of control over plot elements, you will have to do it manually using primitives ( points() , lines() / segments() , text() , etc.) and careful calculations from the graph parameters (for example , par('usr') ). It is not simple. Here is an example of how this can be done:

 point.line.point <- function(x1,y1,x2=x1,y2=y1,...) { points(c(x1,x2),c(y1,y2),...); segments(x1,y1,x2,y2,...); }; legend.plp <- function(x,y,labels,col,linewidth=diff(par('usr')[1:2])/10,textgap=diff(par('usr')[1:2])/20,...) { comb <- cbind(labels,col); xc <- x; for (i in seq_len(nrow(comb))) { x2 <- xc+linewidth; point.line.point(xc,y,x2,col=comb[i,'col'],...); text(x2+textgap,y,comb[i,'labels'],...); xc <- x2+textgap*1.5+strwidth(comb[i,'labels']); }; }; plot(1,1,type="n"); legend.plp(par('usr')[1]+diff(par('usr')[1:2])/20,par('usr')[4]-diff(par('usr')[3:4])/20,1:2,c('darkblue','darkred'),font=2,cex=1.5); 

plot

+3
source

Here is an alternative solution, the opposite of elegant. This includes nesting several plots (one for each legend) and a lot of manual manipulation (to set the "legends" where you want them to be):

 library(Hmisc) data(mtcars) #plots the one in blue plot(mtcars$cyl, type="o", col="darkblue") #plots the one in red lines(mtcars$carb, type="o", col="darkred") #name the legends text(6.5,7, "Cyl", font=2) text(14,7, "Carb", font=2) #add the subplots, it actually a normal plot wrapped around the subplot with the x and y positions subplot(plot(c(1,0),c(1,1), xlab=NA, ylab=NA, xaxt="n", yaxt="n", col="darkblue", type="o", axes=FALSE), 3, 7) subplot(plot(c(1,0),c(1,1), xlab=NA, ylab=NA, xaxt="n", yaxt="n", col="darkred", type="o", axes=FALSE), 10, 7) 

This gives the following graph:

enter image description here

+3
source

All Articles