R plot:在图例中显示点类型和线类型

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

我用 plot 函数生成了一个图。我用 pch() 添加了点标记,用 lty 添加了线型。在图例部分,我想将点和线合并在一起。我使用了 merge=TRUE 但它没有用。它仅显示线型。 merge=FALSE 也一样。在这两种情况下,框图例框的宽度都只有轻微的变化。这就对了。有什么想法吗?

示例代码如下:

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)

人们要求您输入一些玩具代码。这很重要,因为它为人们提供了帮助您的起点。其实做到这一点并不难。考虑以下因素:

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

使用NA控制您要显示的内容。


跟进

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?

太棒了!现在您已将代码包含在问题中。问题在于您对 legend() 的最终调用。不要 use/set 参数 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"))

这会做你想做的事。