R plot() Function - Drawing Scatter Plots
The R plot() function is the most basic plotting function, used to create scatter plots, line plots, and many other types of plots.
plot() is the entry point of R's graphics system; almost all visualizations start with it.
The syntax of the plot() function is as follows:
plot(x, y, type = "p", main = "", xlab = "", ylab = "", col = "black")
Parameter Description:
-
x, y The coordinates of the data points.
-
type Plot type: "p" (points), "l" (lines), "b" (points and lines), "o" (overlaid).
-
main Plot title.
-
xlab, ylab Labels for the x and y axes.
-
col Color.
Example
Create data
height
<-
c
(
160
,
165
,
170
,
175
,
180
,
158
,
172
,
168
,
178
,
182
)
weight
<-
c
(
55
,
60
,
65
,
70
,
80
,
52
,
68
,
62
,
75
,
85
)
Draw a scatter plot
plot
(
height, weight,
main
=
"Height vs. Weight"
,
xlab
=
"Height (cm)"
,
ylab
=
"Weight (kg)"
,
col
=
"blue"
,
pch
=
16
)
pch=16 for solid circles
Add a trend line
abline
(
lm
(
weight ~ height
)
,
col
=
"red"
, lwd
=
2
)
Running the above code displays the scatter plot and a red trend line.
plot() can also be used directly on a data frame, automatically generating a scatter plot matrix of the variables:
Example
View the relationships among variables in the iris dataset
(
"iris scatter plot matrix:"
)
plot
(
iris
[
,
1
:
4
]
,
col
=
iris
$Species,
main
=
"Iris Dataset Scatter Plot Matrix"
)
Running the above code generates a 4x4 scatter plot matrix, where points of different colors represent different iris species.
R Language Examples