R legend issue, symbols of points are masked by lines

☆樱花仙子☆ 提交于 2019-12-11 03:45:45

问题


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!


回答1:


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:




回答2:


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.




回答3:


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:



来源:https://stackoverflow.com/questions/9915527/r-legend-issue-symbols-of-points-are-masked-by-lines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!