【问题标题】:Overlapping legend in r plotr图中的重叠图例
【发布时间】:2018-02-02 14:48:56
【问题描述】:

我已尝试使用此代码,但图例与情节重叠。我想把图例放在图片的底部(在图下方居中),我还想调整图例中示例行的大小,因为它们也会重叠文本。

plot(Portfolio.z, plot.type ="single", main ="Portfolio",
          col =c("red", "blue", "green", "black", "yellow", "purple"),
          lty =c("solid", "solid", "solid", "solid", "solid", "solid"),
          lwd =2, ylab = "Price")
par(xpd=TRUE)
legend("bottom",legend = c("JP Morgan", "Goldman Sachs",
          "BP", "ExxonMobil", "Lockheed Martin", "Boeing"),
          text.width = min(sapply(c("JP Morgan", "Goldman Sachs",
          "BP", "ExxonMobil", "Lockheed Martin", "Boeing"), strwidth)),
          col=c("red", "blue", "black", "green", "purple",
          "yellow"), lwd=5, horiz = TRUE)

【问题讨论】:

  • 你必须使用基础R地块吗? ggplot2 库有一个更好的 API 来创建和调整绘图。
  • 是的,很遗憾,我必须坚持基本情节。

标签: r plot graphics


【解决方案1】:

您应该阅读图例的手册页 - ?legend:您可以完全控制布局和字体大小的各个方面。首先,除非您移除 x 轴标签或增加底部的边距(?par,参数mar=),否则您没有空间放置 x 轴下方的图例。图例中的inset= 参数会调整位置,因此inset=c(0, -.15) 之类的东西会将其置于轴下方,但您可能需要向上或向下调整-.15。您还需要包含 xpd=TRUE 以便 R 知道可以将图例放在图下方的空白处。最后,cex= 控制文本的扩展,默认为 1:

plot(NA, xlim=c(0, 1), ylim=c(0, 1), xlab="")
legend("bottom", "A very long legend under the plot",
    xpd=TRUE, inset=c(0, -.15), cex=.8)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 2019-01-31
    相关资源
    最近更新 更多