R 語言中的 legend() 函數用於向現有 Plot 添加圖例。圖例被定義為描述圖的每個部分的圖的一個區域。圖例圖用於以圖形形式顯示統計數據。
用法:
legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)
參數:
x and y:這些是用於定位圖例的坐標
legend:傳說中的文字
fill:用於填充圖例文本框的顏色
col:線條的顏色
bg:它定義圖例框的背景顏色。
title:圖例標題(可選)
文本字體:指定圖例字體樣式的整數(可選)
返回:圖例圖
範例1:
# Generate some data
x <- 1:8;
y1 = x; y2 = 2 * y1
plot(x, y1, type = "b", pch = 22,
col = "green",
xlab = "X", ylab = "Y")
# Add a line
lines(x, y2, pch = 18, col = "darkgreen",
type = "b", lty = 2)
# Add a legend
legend(1, 50, legend = c("Legend Line 1", "Legend Line 2"),
col = c("green", "darkgreen"), lty = 2:3, cex = 0.6)
輸出:
範例2:添加圖例框的標題、文字字體和背景色
makePlot<-function(){
x<-1:10;
y1 = x * x; y2 = 2 * y1
plot(x, y1, type = "b", pch = 19,
col = "green",
xlab = "X", ylab = "Y")
lines(x, y2, pch = 22, col = "darkgreen",
type = "b", lty = 6)
}
makePlot()
# Add a legend to the plot
legend(1, 95, legend = c(" Legend Line 1", "Legend Line 2"),
col = c("green", "darkgreen"), lty = 1:2, cex = 0.9,
title = "Line types", text.font = 6, bg = 'gray')
輸出:
在這裏,legend()
函數用於向繪圖添加圖例,makePlot() 函數用於操作字體、背景顏色。
範例3:創建圖例框邊框的另一個示例
用法:
legendx, y, fill, col, bg, lty, cex=0.8, box.lty, box.lwd, box.col)
參數:
box.lty、box.lwd 和 box.col:分別用於圖例框邊框的線型、寬度和顏色。
makePlot<-function(){
x<-1:10;
y1 = x * x; y2 = 2 * y1
plot(x, y1, type = "b", pch = 22,
col = "green",
xlab = "x", ylab = "y")
lines(x, y2, pch = 18, col = "darkgreen",
type = "b", lty = 4)
}
# Change the border
makePlot()
legend(1, 100, legend = c("Legend Line 1", "Legend Line 2"),
col = c("green", "darkgreen"), lty = 1:2, cex = 0.8,
box.lty = 4, box.lwd = 2, box.col = "green")
輸出:
範例4:下麵是在 legend() 函數中使用 box.lty = 0 去除圖例邊框的說明
用法:
legendx, y, fill, col, bg, lty, cex=0.8, box.lty=0)
參數:
box.lty:框線寬
makePlot<-function(){
x<-1:10;
y1 = x * x; y2 = 2 * y1
plot(x, y1, type = "b", pch = 22,
col = "green",
xlab = "x", ylab = "y")
lines(x, y2, pch = 18, col = "darkgreen",
type = "b", lty = 4)
}
# Remove legend border using box.lty = 0
makePlot()
legend(2, 100, legend = c("Legend Line 1",
"Legend Line 2"),
col = c("green", "darkgreen"),
lty = 1:2, cex = 0.8, box.lty = 0)
輸出:
例3和例4中box.lty、box.lwd和box.col可用於修改圖例框邊框的線型、寬度和顏色,分別用於修改參數。
相關用法
注:本文由純淨天空篩選整理自kaurbal1698大神的英文原創作品 Describe Parts of a Chart in Graphical Form in R Programming – legend() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。