Graphics Reference
In-Depth Information
Solution
Map a column of class
Date
to the x- or y-axis. We'll use the
economics
data set for this ex-
ample:
# Look at the structure
str(economics)
'data.frame'
:
478
obs. of
6
variables:
$ date : Date, format:
"1967-06-30" "1967-07-31"
...
$ pce : num
508 511 517 513 518 ...
$ pop : int
198712 198911 199113 199311 199498 199657 199808 199920 ...
$ psavert : num
9.8 9.8 9 9.8 9.7 9.4 9 9.5 8.9 9.6 ...
$ uempmed : num
4.5 4.7 4.6 4.9 4.7 4.8 5.1 4.5 4.1 4.6 ...
$ unemploy: int
2944 2945 2958 3143 3066 3018 2878 3001 2877 2709 ...
The column
date
is an object of class
Date
, and mapping it to
x
will produce the result shown
in
Figure 8-37
:
ggplot(economics, aes(x
=
date, y
=
psavert))
+
geom_line()
Figure 8-37. Dates on the x-axis
Discussion
ggplot2 handles two kinds of time-related objects: dates (objects of class
Date
) and date-times
(objects of class
POSIXt
). The difference between these is that
Date
objects represent dates and
have a resolution of one day, while
POSIXt
objects represent moments in time and have a resol-
ution of a fraction of a second.