在R中绘图时如何更改图例框宽度

时间:2016-07-06 21:18:01

标签: r plot

enter image description here

我使用以下脚本在R中生成图例。但图例框太小...如何增加框宽?

legend("topleft", lty = 1, legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),col = c("black","red","blue"))

2 个答案:

答案 0 :(得分:2)

在绘制图表和图例后,您可能正在调整图表的大小。如果是这种情况,并且您想要保留该框,则可以选择绘制图形,调整其大小,然后生成图例。也许更好的选择是将窗口大小调整到所需的宽度:

# on Windows, you can use the `windows` function. elsewhere, try quartz or X11
windows(height = 7, width = 3.5)
plot(hp ~ mpg, data = mtcars)

leg <- legend("topleft", lty = 1,
    legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),
    col = c("black","red","blue"),
    #plot = FALSE,
      #bty = "n")
)

您还可以通过为legend函数提供一对x和y坐标来准确定义框的下降位置。这些值表示框的左上角和右下角。 legend函数实际上会生成框左上角的坐标以及宽度和高度。默认情况下,它会以不可见的方式返回它们,但您可以将它们分配给对象,如果使用plot = FALSE,legend选项,您可以捕获这些坐标并根据需要进行修改,而无需实际绘图传说。

windows(height = 7, width = 3.5)
plot(hp ~ mpg, data = mtcars)

legend(x = c(9.46, 31), y = c(346.32, 298),
    legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),
    col = c("black","red","blue"),
    lty = 1)

legend函数实际上会生成框左上角的坐标(我得到9.46和346.62的坐标)以及框的宽度和高度。默认情况下,它会以不可见的方式返回它们,但您可以将它们分配给一个对象,如果使用plot = FALSE,legend选项,您可以捕获这些坐标并根据需要进行修改,而无需实际绘图传说。

plot(hp ~ mpg, data = mtcars)
leg <- legend("topleft", lty = 1,
    legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),
    col = c("black","red","blue"),
    plot = FALSE)

# adjust as desired
leftx <- leg$rect$left
rightx <- (leg$rect$left + leg$rect$w) * 1.2
topy <- leg$rect$top
bottomy <- (leg$rect$top - leg$rect$h) * 1

# use the new coordinates to define custom
legend(x = c(leftx, rightx), y = c(topy, bottomy), lty = 1,
    legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),
    col = c("black","red","blue"))

答案 1 :(得分:1)

图例宽度的一部分由您使用的标签的最长宽度决定,该最长宽度是通过strwidth计算的。在一个简单的示例下面,如何使用legend(..., text.width = ...)将大小减半或翻倍。

plot(1)
text =  c("Sub_metering_1","Sub_metering_2","Sub_metering_3")
legend("topleft"
       ,lty = 1
       ,legend = text
       ,col = c("black","red","blue")
       )
strwidth(text)
# [1] 0.1734099 0.1734099 0.1734099
# half the length
legend("bottomleft"
       ,lty = 1
       ,legend = text
       ,text.width = strwidth(text)[1]/2
       ,col = c("black","red","blue")
       )
# double the length
legend("center"
       ,lty = 1
       ,legend = text
       ,text.width = strwidth(text)[1]*2
       ,col = c("black","red","blue")
)