【问题标题】:How can I justify multiple parts of legend in R?如何证明 R 中图例的多个部分是合理的?
【发布时间】:2019-04-12 05:46:14
【问题描述】:

我想左对齐图例的一部分,右对齐其余部分。

代码如下:

plot(1:10, ty="n", axes=F, xlab = NA, ylab = NA)
legend(2,8,legend = c(paste("Muito baixo:", start), paste("Baixo:", middle[1]), paste("Médio:", middle[2]), paste("Alto:", middle[3]), paste("Muito alto:", end)), fill = RdYlGn, bty = "n", cex = 1.4)

现在我的传奇是这样的:

我想要这样的东西:

【问题讨论】:

  • 我不知道基础图形中有什么方法可以支持这一点;实际上,您要的是多列,因为字体是可变宽度的,并且没有“扩展空白”的概念。我认为您将需要走两个传奇的路线,类似于stackoverflow.com/q/29692288/3358272
  • Murillo,如果其中一个答案解决了您的问题,请accept it;这样做不仅为回答者提供了一些积分,而且还为有类似问题的读者提供了一些关闭。尽管您只能接受一个答案,但您可以选择对您认为有帮助的人进行投票。 (如果仍有问题,您可能需要编辑您的问题并提供更多详细信息。)

标签: r legend justify


【解决方案1】:

改编自this answer

plot(1:10, ty="n", axes=F, xlab = NA, ylab = NA)
foo <- legend(2,8,legend = c("Muito baixo:","Baixo:","Médio:","Alto:","Muito alto:"), bty = "n", cex = 1.4)
text(0.5 + foo$rect$left + foo$rect$w, foo$text$y, c("<58", "58-68", "68-74", "74-84", ">84"), cex = 1.4, pos = 2)

0.5 是一个需要调整的缓冲区。

【讨论】:

    【解决方案2】:

    类似于 Lyngbakr 的:

    leg <- round(aggregate(disp ~ cyl, data=mtcars, FUN=range))
    leg$disp <- apply(leg$disp, 1, paste, collapse="-")
    leg$txt <- c("Four Cylinders", "Six", "Eight")
    plot(disp~mpg, col=cyl, data=mtcars, pch=16)
    l <- legend("topright", title="Cyl ~ Disp",
                legend = leg$txt, pch = 16, col = leg$cyl,
                text.width = max(strwidth(paste(leg$txt, "   ", leg$disp))),
                xjust = 1, yjust = 1)
    text(l$rect$left + l$rect$w, l$text$y - 0.2*strheight("W"),
         leg$disp, pos=2)
    

    注意事项:

    • strwidth 中使用" " 是为了提供一点缓冲,可以根据口味进行更改;
    • 右栏文本与实际图例的文本垂直偏移了一点,所以我添加了一个缓冲区。由于这取决于字体大小和 y 轴的单位,因此我使用了 strheight 的倍数,用你自己的数据来玩吧。

    深受How to make labels in the legend align right in R?的影响

    【讨论】:

      猜你喜欢
      • 2020-02-15
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 2013-06-12
      • 1970-01-01
      相关资源
      最近更新 更多