Drawing Plots
The most generic plotting command is plot(), which
automatically recognizes the type of R object(s) you are trying to
plot and selects the best type of plot. The most common graphs
returned by plot() are as follows:
- If X is a variable of length 2#2
, plot(X)
returns a scatter plot of 27#27
for
28#28
. If X is
unsorted, this procedure produces a messy graph. Use
plot(sort(X)) to arrange the plotted values of 27#27
from smallest to largest.
- With two numeric vectors X and Y, both of
length 2#2
, plot(X, Y) plots a scatter plot of each point
29#29
for
28#28
. Alternatively, if Z is an object
with two vectors, plot(Z) also creates a scatter plot.
Optional arguments specific to plot include:
- main creates a title for the graph, and xlab
and ylab label the x and y axes, respectively. For
example,
plot(x, y, main = "My Lovely Plot", xlab = "Explanatory Variable",
ylab = "Dependent Variable")
- type controls the type of plot you request. The
default is plot(x, y, type = "p"), but you may choose among
the following types:
"p" |
points |
"l" |
lines |
"b" |
both points and lines |
"c" |
lines drawn up to but not including the points |
"h" |
histogram |
"s" |
a step function |
"n" |
a blank plotting region ( with the axes specified) |
- If you choose type = "p", R plots open circles by default.
You can change the type of point by specifying the pch
argument. For example, plot(x, y, type = "p", pch = 19)
creates a scatter-plot of filled circles. Other options for pch include:
19 |
solid circle (a disk) |
20 |
smaller solid circle |
21 |
circle |
22 |
square |
23 |
diamond |
24 |
triangle pointed up |
25 |
triangle pointed down |
In addition, you can specify your own symbols by using, for example,
pch = "*" or pch = ".".
- If you choose type = "l", R plots solid lines by default.
Use the optional lty argument to set the line type. For
example, plot(x, y, type = "l", lty = "dashed") plots a dashed
line. Other options are dotted, dotdash, longdash, and twodash.
- col sets the color of the points, lines, or bars. For
example, plot(x, y, type = "b", pch = 20, lty = "dotted",
col = "violet") plots small circles connected by a dotted line,
both of which are violet. (The axes and labels remain black.) Use
colors() to see the full list of available colors.
- xlim and ylim set the limits to the 30#30
-axis and
31#31
-axis. For example, plot(x, y, xlim = c(0, 25), ylim =
c(-15, 5)) sets range of the 30#30
-axis to [0, 25] and the range of
the 31#31
-axis to 32#32
.
For additional plotting options, refer to help(par).
Gary King
2011-11-29