Graphics Reference
In-Depth Information
Solution
Use
geom_tile()
or
geom_raster()
and map a continuous variable to
fill
. We'll use the
presidents
data set, which is a time series object rather than a data frame:
presidents
Qtr1 Qtr2 Qtr3 Qtr4
1945
NA
87
82
75
1946
63
50
43
32
...
1973
68
44
40
27
1974
28
25
24
24
str(presidents)
Time
-
Series [
1
:
120
] from
1945
to
1975
:
NA
87 82 75 63 50 43 32 35 60 ...
We'll first convert it to a format that is usable by
ggplot()
—a data frame with columns that are
numeric:
pres_rating
<-
data.frame(
rating
=
as.numeric(presidents),
year
=
as.numeric(floor(time(presidents))),
quarter
=
as.numeric(cycle(presidents))
)
pres_rating
rating year quarter
NA
1945
1
87 1945
2
82 1945
3
...
25 1974 2
24 1974 3
24 1974 4
one variable to
x
, one to
y
, and one to
fill
:
# Base plot
p
<-
ggplot(pres_rating, aes(x
=
year, y
=
quarter, fill
=
rating))
# Using geom_tile()
p
+
geom_tile()