R legend() Function - Adding a Legend
The R legend() function is used to add a legend to a graph, helping readers identify different data series.
When a graph contains multiple groups of data, a legend is an indispensable element.
The syntax of the legend() function is as follows:
legend(x, y = NULL, legend, col, pch, lty, lwd, fill, title = NULL)
Parameter Description:
-
x, y Legend position: keywords such as "topright", "bottomleft", or coordinates.
-
legend Text labels for the legend.
-
col The colors of each data series.
-
pch Point symbol types.
-
lty Line types.
Example
Monthly sales trends of three product categories
month
<-
1
:
6
product_a
<-
c
(
100
,
120
,
115
,
135
,
145
,
160
)
product_b
<-
c
(
85
,
90
,
95
,
100
,
105
,
110
)
product_c
<-
c
(
60
,
70
,
80
,
75
,
90
,
88
)
Draw a line chart
plot
(
month, product_a, type
=
"o"
,
col
=
"steelblue"
, lwd
=
2
, pch
=
16
,
ylim
=
c
(
50
,
170
)
,
main
=
"Monthly sales trend of each product"
,
xlab
=
"Month"
, ylab
=
"Sales"
)
lines
(
month, product_b, type
=
"o"
,
col
=
"coral"
, lwd
=
2
, pch
=
17
)
lines
(
month, product_c, type
=
"o"
,
col
=
"seagreen"
, lwd
=
2
, pch
=
18
)
Add a legend
legend
(
"topleft"
,
legend
=
c
(
"Product A"
,
"Product B"
,
"Product C"
)
,
col
=
c
(
"steelblue"
,
"coral"
,
"seagreen"
)
,
pch
=
c
(
16
,
17
,
18
)
,
lwd
=
2
,
title
=
"Product category"
)
Running the above code will display three sales lines, with a legend distinguishing them by color.
R Language Examples