LoslegenKostenlos loslegen

Extracting for plotting

Extracting components from a datetime is particularly useful when exploring data. Earlier in the chapter you imported daily data for weather in Auckland, and created a time series plot of ten years of daily maximum temperature. While that plot gives you a good overview of the whole ten years, it's hard to see the annual pattern.

In this exercise you'll use components of the dates to help explore the pattern of maximum temperature over the year. The first step is to create some new columns to hold the extracted pieces, then you'll use them in a couple of plots.

Diese Übung ist Teil des Kurses

Working with Dates and Times in R

Kurs anzeigen

Anleitung zur Übung

  • Use mutate() to create three new columns: year, yday and month that respectively hold the same components of the date column. Don't forget to label the months with their names.
  • Create a plot of yday on the x-axis, max_temp of the y-axis where lines are grouped by year. Each year is a line on this plot, with the x-axis running from Jan 1 to Dec 31.
  • To take an alternate look, create a ridgeline plot(formerly known as a joyplot) with max_temp on the x-axis, month on the y-axis, using geom_density_ridges() from the ggridges package.

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

library(ggplot2)
library(dplyr)
library(ggridges)

# Add columns for year, yday and month
akl_daily <- akl_daily %>%
  mutate(
    ___ = ___(date),
    ___ = ___(date),
    ___ = ___(date, ___))

# Plot max_temp by yday for all years
ggplot(akl_daily, aes(x = ___, y = ___)) +
  geom_line(aes(group = ___), alpha = 0.5)

# Examine distribution of max_temp by month
ggplot(akl_daily, aes(x = ___, y = ___, height = ..density..)) +
  geom_density_ridges(stat = "density")
Code bearbeiten und ausführen