簡體   English   中英

在R中繪圖時如何更改圖例框寬度

[英]How to change the legend box width when plotting in R

在此輸入圖像描述

我使用以下腳本在R中生成圖例。但圖例框太小...如何增加框寬?

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

在繪制圖形和圖例后,您可能正在調整圖形大小。 如果是這種情況,並且您想要保留該框,則可以選擇繪制圖形,調整其大小,然后生成圖例。 也許更好的選擇是將窗口大小調整到所需的寬度,以便開始:

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

圖例寬度的一部分由您使用的標簽的最長寬度決定,這是通過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")
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM