简体   繁体   English

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

[英]R plot: Displaying both point type and line type in legend

I have generated a plot with plot function. 我已经生成了一个带有plot功能的plot I added the point markers with pch() and the line type with lty . 我用pch()添加了点标记,用lty添加了lty In the legend section I wanted to merge the points and lines together. 在图例部分,我想将点和线合并在一起。 I used merge=TRUE but it didn't work. 我使用merge=TRUE但它没有用。 It is displaying the line type only. 它仅显示线型。 The same thing with merge=FALSE . 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)

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

测试

Use NA to control what you want to display. 使用NA控制要显示的内容。


Follow-up 跟进

I forgot to include the pch in the legend() . 我忘了将pch包含在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() . 问题出在你对legend()最后调用上。 Do not use/set argument merge : 不要使用/ 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"))

This will do what you want. 这将做你想要的。

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

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