繁体   English   中英

在r图传奇中排列点和线

[英]Arrange points and lines in an 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)

看起来像这样( “点线点”模式)? 在此输入图像描述

通常,如果您希望对绘图元素进行此级别的控制,则必须使用基元( points()lines() / segments()text()等)手动执行此操作,并根据绘图参数进行仔细计算(例如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);

情节

这是一个与优雅相反的替代解决方案。 它涉及嵌入几个图(每个图例一个),以及大量的手动操作(设置你想要它们的'传说'):

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)

这产生了以下情节:

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM