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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。