我想在图例中的线条上方叠加透明框。
一个小例子:
xdata <- 1:7
y1 <- c(1,4,9,16,25,36,49)
y2 <- c(1, 5, 12, 21, 34, 51, 72)
y3 <- c(1, 6, 14, 28, 47, 73, 106 )
y4 <- c(1, 7, 17, 35, 60, 95, 140 )
plot(xdata, y1, type = 'l', col = "red")
lines(xdata, y2, type = 'l', col = "red", lty = 3)
lines(xdata, y3, type = 'l', col = "blue")
lines(xdata, y4, type = 'l', col = "blue", lty = 3)
# add legend with lines
legend("topleft", legend = c("Plot 1", "Plot 2", "Plot 3", "Plot 4"),
lty = c(1,3,1,3), lwd = rep(1.3 ,4),
col = c("blue", "blue", "red", "red") ,
pch = rep(NA, 4), cex = 0.8,
x.intersp = 0.7, y.intersp = 1.2, bty = 'n')
# add boxes
legend("topleft", legend = c("", "", "", ""), lty = rep(0, 4),
col = c(adjustcolor(blues9[3], alpha.f = 0.6),
adjustcolor(blues9[3], alpha.f = 0.6),
adjustcolor("red", alpha.f = 0.1),
adjustcolor("red", alpha.f = 0.1)),
pch = rep(15, 4), cex = 0.8, pt.cex = rep(2, 4),
x.intersp = 0.7, y.intersp = 1.2, bty = 'n')
产生:
如您所见,这些框沿图例中的线向左移动。
如何设置框的对齐方式,以使其在图例中的线符号上方水平居中?谢谢!
最佳答案
这里的提示是在两个lwd
调用中指定相同的legend
,即在lty = 0
框的调用中也指定相同的legend
。
这是一个简单的示例,仅包含与您的实际问题相关的参数:
plot(1)
# lines
legend(x = "topleft",
legend = c("Plot 1", "Plot 2", "Plot 3", "Plot 4"), bty = 'n',
lty = c(1, 3), lwd = 1,
pch = NA,
col = rep(c("blue", "red"), each = 2))
# boxes
legend(x = "topleft",
legend = rep("", 4), bty = "n",
lty = 0, lwd = 1, # <- lwd = 1
pch = 15, pt.cex = 2,
col = c(rep(adjustcolor(blues9[3], alpha.f = 0.6), 2),
rep(adjustcolor("red", alpha.f = 0.1), 2)))
如果您对方框的颜色轮廓满意,那么一个
pch
调用就足够了。只需使用接受pt.bg
的ojit_code(此处为22):plot(1)
legend(x = "topleft",
legend = c("Plot 1", "Plot 2", "Plot 3", "Plot 4"), bty = 'n',
lty = c(1, 3), col = rep(c("blue", "red"), each = 2),
pch = 22, pt.cex = 2,
pt.bg = c(rep(adjustcolor(blues9[3], alpha.f = 0.6), 2),
rep(adjustcolor("red", alpha.f = 0.1), 2)))