Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R plot() Function - Drawing Scatter Plots

R plot() Function - Drawing Scatter Plots

R Language Examples R Language Examples

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:

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

print

(

"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 R Language Examples