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

R Plots - Scatter Plots

R Plots - Scatter Plots

A scatter plot displays all data as points on a Cartesian coordinate system to show the degree of mutual influence between variables. The position of each point is determined by the values of the variables, with each point corresponding to an X and Y axis coordinate.

A scatter plot can be drawn with the plot() function; the syntax is as follows:

plot(x, y, type="p", main, xlab, ylab, xlim, ylim, axes)

The selectable values of the type parameter are:

Create a simple line chart:

Example

x

<-

c

(

10

,

40

)

y

<-

c

(

20

,

60

)

Generate a png image

png

(

file

=

"runnob-test-plot2.png"

)

plot

(

x, y,

"l"

)

Create a simple line chart using the o parameter for type, drawing both points and lines with the line passing through the points:

Example

x

<-

c

(

10

,

40

)

y

<-

c

(

20

,

60

)

Generate a png image

png

(

file

=

"runnob-test-plot.png"

)

plot

(

x, y,

"o"

)

Next, we use R's built-in dataset mtcars for testing.

We use the wt and mpg columns of the mtcars dataset:

Example

input

<-

mtcars

[

,

c

(

'wt'

,

'mpg'

)

]

print

(

head

(

input

)

)

The output is:

wt  mpg

Mazda RX4         2.620 21.0

Mazda RX4 Wag     2.875 21.0

Datsun 710        2.320 22.8

Hornet 4 Drive    3.215 21.4

Hornet Sportabout 3.440 18.7

Valiant           3.460 18.1

Then we use the above data to generate a scatter plot

:

Example

Data

input

<-

mtcars

[

,

c

(

'wt'

,

'mpg'

)

]

Generate a png image

png

(

file

=

"scatterplot.png"

)

Set the x-axis range from 2.5 to 5 and the y-axis range from 15 to 30.

plot

(

x

=

input$wt,y

=

input$mpg,

   xlab

=

"Weight"

,

   ylab

=

"Milage"

,

   xlim

=

c

(

2.5

,

5

)

,

   ylim

=

c

(

15

,

30

)

,              

   main

=

"Weight vs Milage"

)

Scatter plot matrix

A scatter plot matrix is a plotting method based on two-variable scatter plots. It can be seen as a large square array of graphs, where each off-diagonal position holds a scatter plot of the variable in the corresponding row against the variable in the corresponding column, while the diagonal positions hold the variable names. In this way, the scatter plot matrix clearly shows the pairwise correlations among the multiple variables being studied.

A scatter plot matrix draws pairwise scatter plots for each numeric variable in the data set.

R uses the following function to create a scatter plot matrix:

pairs(formula, data)

Parameters:

Example

Output the image

png

(

file

=

"scatterplot_matrices.png"

)

A matrix of 4 variables, 12 plots

pairs

(

~wt

mpg

disp

cyl,

data

=

mtcars

, main

=

"Scatterplot Matrix"

)