R语言 以图形的形式描述图表的部分内容 – legend()函数

R语言 以图形的形式描述图表的部分内容 – legend()函数

R编程语言中的legend()函数 用于向现有的图谱添加图例。图例被定义为描述图表中每个部分的区域。图例图是用来以图形形式显示统计数据的。

语法: legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)

参数

  • x和y: 这些是用来定位图例的坐标。
  • legend: 图例的文本
  • fill: 用于填充图例文本框的颜色
  • col: 线条的颜色
  • bg: 它定义了图例框的背景颜色。
  • title: 图例标题(可选
  • text.font :一个整数,指定图例的字体样式(可选

返回: 图例情节

R – legend() 示例

例1: R语言中legend()函数的基本例子

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

输出

在R编程中以图形的形式描述图表的部分内容 - legend()函数

例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')
R

输出

在R编程中以图形的形式描述图表的部分内容 - legend()函数

这里,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")
R

输出

在R编程中以图形的形式描述图表的部分内容 - legend()函数

例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)
R

输出

在R编程中以图形的形式描述图表的部分内容 - legend()函数

在例3和例4中box.lty、box.lwd和box.col可以用来修改线型、宽度和颜色,用于图例框的边框,分别用来修改参数。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册