简体   繁体   中英

R legend issue, symbols of points are masked by lines

Is there a way to draw the lines in such a way that they would start on the side of the points, or allow the symbols to be in foreground?

My solution was to make the symbols bigger and more visible.

Edit 1: it's for plot {graphics} of the R program.

Edit 2: the code per popular request.

legend(2,.4,bty='n', c('sugar','citrus','none'), pch=c('s','c','u'), pt.bg='white',lty= c(1,2,3), lwd=1.5, title="Condition",pt.cex=c(1.5),cex=1.5)

Edit 3: This is solved for plot(type='b') but somehow not for legend.

Thanks for reading!

The only thing I can come up with is to manually finagle the dash lengths until they end up looking the way you want them. For instance, this:

> plot(1,1)
> legend(c("A", "B"), col = 1:2, x = 1, y = .8, lty="99", pch=1:2)

produces the image below.

The lty parameter allows you to specify the lengths of lines and dashes as hex characters. In this case, it's saying to create a line of length 9 then create a space of length 9 then repeat. It looks like 9 is about the best fit to space around a normal pch symbol.

Note that you'd probably need to adjust this depending on the size of the image, symbol, etc. My advice ultimately would be to export the image from R and touch up the image to meet your needs in graphic editing software.

带有手动破折号长度的图形

You could also use the filled points offered by R (pch=21:25) and specify the fill color using pc.bg which gets passed to the points call when creating a legend.

plot(1,1)
legend(c("A", "B"), col = 1:2, x = 1, y = .8, lty=1, pt.bg=1:2, pch=21:22)

generates the following:

填充点图

Going with the suggestion by @JeffAllen, here is a way to get what I think you might want. It requires modifying the legend() function to return the position of the points (these are given by x1 and y1 in body(legend)[[46]] ).

legend2 <- legend
body(legend2)[[49]] <- quote(
  invisible(list(rect = list(w = w, h = h, left = left, top = top),
  text = list(x = xt, y = yt), points = list(x = x1, y = y1)))
)

Make a plot:

plot(-100:100, -100:100, type = "b")

While drawing the legend, draw white circles ( pch = 21 with pt.bg = 'white' ) over the lines, and assign the values invisibly returned by legend2() to an object. Note also the changes to pt.lwd and pt.cex .

myLegend <- legend2(1, .8, bty = 'n', c('sugar','citrus','none'), pch = 21,
  pt.bg = 'white', pt.lwd = 0, lty = c(1, 2, 3), lwd = 1.5, title = "Condition",
  pt.cex = c(1.8), cex = 1.5)

Finally, draw the characters you'd like to use in the legend using points() , supplying the x and y values from the object myLegend .

points(myLegend$points$x, myLegend$points$y, pch = c('s','c','u'), cex = 1.5)

And this should get you something like:

样例

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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