如何控制插图R绘图图例的方式

时间:2018-09-26 19:18:15

标签: r legend

我正试图迫使我的图例位于右下角并与两个轴齐平。现在,图例默认情况下要比我希望的图例插入得更远(围绕x轴的中间位置)。我在这里和R文档中四处摸索,发现“ inset =”是可在图例函数中使用的可选参数。我认为这就是我可以完成自己想要的事情的方式。但是,当我尝试仅输入一个数字值(inset = 0)时,图例与默认值位于同一位置。当我尝试输入两个数值参数(inset = c(0,-2))时,图例根本不会显示。我以为我可能使用了不正确的语法,并尝试了inset = 0:-2,但这也不起作用。我尝试过使用更高的值,这会使图例变得更加嵌入,所以我知道这是正确的论据,但也许我没有给它正确的值?我还尝试过更改“ xjust =”和“ yjust =”参数的值,但这些值似乎没有显着影响。有人对我可能做错的事有任何建议吗?随附的是我的代码和当前的绘图输出(以及显示我想要图例的位置的箭头):

layout(matrix(c(2,1), 1, 2, byrow = FALSE))
par(pty="s", mar= c(1,3,1,3), mgp=c(1.5,0.5,0))

plot(x1, y1, 
     xlab="Total X1", 
     ylab="Total X2", 
     type= "n",
     ylim = c(-3,2),
     xlim = c(-2.5,2.5),
     cex.lab= 0.7,
     cex.axis= 0.7)
text(x1, y1, labels = SedCombined2$Site,
     col= c("#D55E00", "#000000", "#009E73", "#0072B2")[as.factor(SedCombined2$Event)],
     cex=0.7,
     font = 2)
legend("bottomright",
       border = "black",
       bty= "n",
       legend= c("November 2014", "April 2015","November 2015","April 2016"),
       text.col = c("#D55E00", "#000000", "#009E73", "#0072B2"),
       cex=0.6,
       x.intersp = 0.5,
       y.intersp = 0.5,
       inset = 0)

x2 <- fitSedCombinedISO$points[,1]
y2 <- fitSedCombinedISO$points[,2]
plot(x2, y2,
     xlab="Toxic X1", 
     ylab="Toxic X2", 
     type= "n",
     ylim = c(-3,2),
     xlim = c(-2.5,2.5),
     cex.lab= 0.7,
     cex.axis= 0.7)
text(x2, y2, labels = SedCombined2$Site,
     col= c("#D55E00", "#000000", "#009E73", "#0072B2")[as.factor(SedCombined2$Event)],
     cex=0.7,
     font = 2)
legend("bottomright",
       border = "black",
       bty= "n",
       legend= c("November 2014", "April 2015","November 2015","April 2016"),
       text.col = c("#D55E00", "#000000", "#009E73", "#0072B2"),
       cex=0.6,
       x.intersp = 0.5,
       y.intersp = 0.5,
       inset = 0)

Current Plot Output

1 个答案:

答案 0 :(得分:0)

这需要一点技巧,将图例分配给一个变量,然后使用该变量创建一个文本框:

temp <- legend("bottomright",
       border = "black",
       bty= "n",
       legend=c('','','',''),
       text.width=max(strwidth(c("November 2014", "April 2015","November 2015","April 2016"))),
       text.col = c("#D55E00", "#000000", "#009E73", "#0072B2"),     
       xjust=1, yjust=1)

text(
    temp$rect$left + temp$rect$w, 
    temp$text$y, 
    c("November 2014", "April 2015","November 2015","April 2016"), 
    pos=2, 
    c("#D55E00", "#000000", "#009E73", "#0072B2"))

一般来说,如果对图样外观的这种控制水平很重要,我强烈建议使用ggplot。