Plotting
If you plot a Date
on the axis of a plot, you expect the dates to be in calendar order, and that's exactly what happens with plot()
or ggplot()
.
In this exercise you'll make some plots with the R version releases
data from the previous exercises using ggplot2
. There are two big differences when a Date
is on an axis:
If you specify limits they must be
Date
objects.To control the behavior of the scale you use the
scale_x_date()
function.
Have a go in this exercise where you explore how often R releases occur.
This exercise is part of the course
Working with Dates and Times in R
Exercise instructions
- Make a plot of releases over time by setting the
x
argument of theaes()
function to thedate
column. - Zoom in to the period from 2010 to 2014 by specifying limits from
"2010-01-01"
to"2014-01-01"
. Notice these strings need to be wrapped inas.Date()
to be interpreted asDate
objects. - Adjust the axis labeling by specifying
date_breaks
of"10 years"
anddate_labels
of"%Y"
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
library(ggplot2)
# Set the x axis to the date column
ggplot(releases, aes(x = ___, y = type)) +
geom_line(aes(group = 1, color = factor(major)))
# Limit the axis to between 2010-01-01 and 2014-01-01
ggplot(releases, aes(x = date, y = type)) +
geom_line(aes(group = 1, color = factor(major))) +
xlim(as.Date(___), as.Date(___))
# Specify breaks every ten years and labels with "%Y"
ggplot(releases, aes(x = date, y = type)) +
geom_line(aes(group = 1, color = factor(major))) +
scale_x_date(date_breaks = ___, date_labels = ___)