R Plotting
R Plotting
Plot
At its simplest, you can use the plot() function to plot two numbers against each other:
Example
Draw one point in the diagram, at position (1) and position (3):
plot(1, 3)
Example
Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):
Multiple Points
You can plot as many points as you like, just make sure you have the same number of points in both axis:
Example
For better organization, when you have many values, it is better to use variables:
Example
x <- c(1, 2, 3, 4, 5)
plot(x, y)
Sequences of Points
If you want to draw dots in a sequence, on both the x-axis and the y-axis, use the : operator:
Example
plot(1:10)
Draw a Line
The plot() function also takes a type parameter with the value l to draw a line to connect all the points in
the diagram:
Example
plot(1:10, type="l")
Plot Labels
The plot() function also accept other parameters, such as main, xlab and ylab if you want to customize
the graph with a main title and different labels for the x and y-axis:
Graph Appearance
There are many other parameters you can use to change the appearance of the points.
Colors
Example
plot(1:10, col="red")
Size
Use cex=number to change the size of the points (1 is default, while 0.5 means 50% smaller, and 2 means
100% larger):
Example
plot(1:10, cex=2)
Point Shape
Use pch with a value from 0 to 25 to change the point shape format:
Example
A line graph has a line that connects all the points in a diagram.
To create a line, use the plot() function and add the type parameter with a value of "l":
Example
plot(1:10, type="l")
Scatter Plots
You learned from the Plot chapter that the plot() function is used to plot numbers against each other.
A "scatter plot" is a type of plot used to display the relationship between two numerical variables, and
plots one dot for each observation.
It needs two vectors of same length, one for the x-axis (horizontal) and one for the y-axis (vertical):
Example
x <- c(5,7,8,7,2,2,9,4,11,12,9,6)
y <- c(99,86,87,88,111,103,87,94,78,77,85,86)
plot(x, y)