R语言 为图画添加图例
图例对于为图表添加更多信息和提高用户可读性非常有用。它涉及到创建标题、索引、绘图框的位置,以便更好地理解所绘制的图形。内置的R函数 legend() 可以用来为绘图添加图例。
语法: legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)
参数
- x和y: 这些是用来定位图例的坐标。
- legend: 图例的文本
- fill: 用于填充图例文本框的颜色
- col: 线条的颜色
- bg: 它定义了图例框的背景颜色。
- title: 图例标题(可选
- text.font :一个整数,指定图例的字体样式(可选
返回: 图例情节
在对我们的绘图进行正常的可视化处理之后,为了给它添加图例,只需向 legend() 函数提供适当的参数和必要的值。
例子
# declaring the data to plot
x<-1:10
y=x^1/2
z= x^2
# plotting x and y coordinate
# line
plot(x, y, col="blue")
# adding another line on the
# coordinates involving y and z
lines(z, y ,col="red")
# Adding a legend to the graph
# defining the lines
legend(2, 4, legend=c("Equation 1", "Equation 2"),
fill = c("blue","red")
)
输出
图形中的图例框可以根据要求进行定制,以传达更多的信息,同时为图形增加美感。以下是图例的属性,它们可以被定制。
- title: 图例框的标题,可以被声明以了解其指示的索引。
- position : 图例框的位置指示器;可以有以下选项。”bottom right”, “bottom”, “bottomleft”, “left”, “top”, “topright”, “right “和 “center”。
- bty(默认值:o): 包围图例的盒子的类型。可以使用不同类型的字母,其中盒子的形状与字母的形状相当。例如,”n “可以用来表示没有方框。
- bg: 可以为图例框指定一个背景颜色。
- box.lwd : 图例框的线宽指示器
- box.lty : 图例框的线型指示器
- box.col : 图例框的线条颜色指示器
当适当的值应用于这些属性,然后将它们传递给 legend() 函数,就可以实现所需的定制。
例子
# declaring the data to plot
x<-1:10
y=x^1/2
z= x^2
# plotting x and y coordinate line
plot(x, y, col="blue")
# adding another line on the
# coordinates involving y and z
lines(z, y ,col="red")
# Adding a legend to the graph
# defining the lines
legend(x = "topleft", box.col = "brown",
bg ="yellow", box.lwd = 2 , title="EQUATIONS",
legend=c("Equation 1", "Equation 2"),
fill = c("blue","red"))
输出
图例函数的文本也可以使用以下属性进行定制,以获得更好的样式。
- text.font: 一个数值,表示图例文本的字体风格。它有以下值:(1-正常2-粗体,3-斜体,4-粗体和斜体)
- text.col : 用来指示用于书写图例文本的颜色。
- border(默认:黑色): 表示图例框内的边框颜色
- fill_color : 用于填充方框的颜色
例子
# declaring the data to plot
x<-20:1
y=x
z= x*(1/4)
# plotting x and y coordinate line
plot(x, y, lty = 4,col="blue")
# adding another line on the
# coordinates involving y and z
lines(y, z ,lty = 6,col="orange")
# Adding a legend to the graph
# defining the lines
legend(x = "topleft", lty = c(4,6), text.font = 4,
col= c("blue","orange"),text.col = "blue",
legend=c("Equation 1", "Equation 2"))
输出