在r绘图图例中排列点和线

在r绘图图例中排列点和线,r,plot,legend,R,Plot,Legend,是否可以重新排列以下绘图的图例 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) 看起来像这样(“点-线-点”图案)? 通常,如果您想要对绘图元素进行这种级别的控制,您必须手动使用原语(点(),线()/段(),文本(),等等)并根据绘图参数仔细计算(例如par('usr'))。它不容易

是否可以重新排列以下绘图的图例

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)
看起来像这样(“点-线-点”图案)?

通常,如果您想要对绘图元素进行这种级别的控制,您必须手动使用原语(
点()
线()
/
段()
文本()
,等等)并根据绘图参数仔细计算(例如
par('usr')
)。它不容易。下面是一个如何做到这一点的示例:

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

point.line.point这里有一个与优雅相反的替代解决方案。它包括嵌入两个绘图(每个图例一个),以及大量手动操作(将“图例”设置在您想要的位置):

这将产生以下曲线图:

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's 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)