r - 如何在情节图例的线条顶部居中框?

标签 r plot legend

我想在图例中的线条顶部叠加透明框。

一个小例子:

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

它产生:

enter image description here

如您所见,框沿图例中的线条向左移动。

如何设置框的对齐方式,以便它们在图例中的线符号顶部水平居中?谢谢!

最佳答案

这里的线索是指定相同的 lwd在两者 legend调用,即也在调用框中 lty = 0 .

这是一个更简单的示例,仅包含与您的实际问题相关的参数:

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

enter image description here

如果您对框的彩色轮廓感到满意,一个 legend打电话就够了。只需使用 pch接受 pt.bg (此处: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)))

enter image description here

关于r - 如何在情节图例的线条顶部居中框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50960635/

相关文章:

r - 查找数据框中是否存在列

python - 有没有办法用 matplotlib 绘制 3d 笛卡尔坐标系?

从 ggplot2 中的图例中删除灰色

r - ggplot2 - 当点图不在同一坐标处着色点时,如何使用图例应用手动渐变

r - 在 R Shiny 中,可以使用 DT::dataframe 交互式突出显示单元格吗?

r - 如何找到多个栅格的像素最大值?

r - 为什么 r 中的 nrow(dataframe) 和 length(dataframe) 给出不同的结果?

r - 在图的子集之间添加额外的间距

matlab - 是否可以链接两个曲面图的轴以进行 3d 旋转?

python - 如何将图形图例重新定位到子图形中