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

3

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

一种解决方法是通过在图例中使用cex参数来更改类型的大小。例如,尝试cex=0.9来减小大小。如果这还不够,请使用cex=0.8等更小的值。 - James Picerno
2个回答

4

你可能在绘制图表和图例后调整了图表的大小。如果是这种情况,并且想要保留框,一种选择是绘制图表,调整大小,然后生成图例。也许更好的选择是从一开始就将窗口大小调整为所需宽度:

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

3

图例宽度的一部分由您使用的标签的最长宽度决定,该宽度通过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")
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接