Primary exercises

  1. Facets (grid): variable for rows and/or variable for columns.
    Try each of the following facet_grid lines and understand the effects:
p <- ggplot( pulse ) +
  aes( x = weight, y = height, color = exercise, shape = gender ) +
  geom_point( size = 3, alpha = 0.8 )
p + facet_grid( . ~ exercise )

p + facet_grid( exercise ~ . )

p + facet_grid( gender ~ exercise )

p + facet_grid( exercise ~ gender )

p + facet_grid( exercise ~ gender, scales = "free" )

# p + facet_grid( . ~ exercise )
#     Here . (dot) is used to state that no facetting should be done for rows.

# p + facet_grid( exercise ~ . )
#     Here . (dot) is used to state that no facetting should be done for columns.

# p + facet_grid( exercise ~ gender, scales = "free" )
#     The scales="free" argument allows ranges on the axes to be different
#     in each row/column.
  1. Facets (wrap): multi-level variable in multiple rows and columns.
    Now compare facet_wrap with facet_grid:
p <- ggplot( pulse ) +
  aes( x = weight, y = height, color = exercise, shape = gender ) +
  geom_point( size = 3, alpha = 0.8 )
p + facet_grid( . ~ year )

p + facet_grid( year ~ . )

p + facet_wrap( ~ year )

p + facet_wrap( ~ year, scales = "free" )

# facet_grid always enforces that a single variable goes in one direction
#     (either rows or columns)
#
# facet_wrap distributes levels of the variable to fill the whole plot
#     area "nicely"
  1. Visualize effect of running on pulse.
    Reconstruct the following image based on the pulse data.
    Add component coord_fixed() to enforce that unit sizes are identical for both axes.
    Use geom_abline( slope = 1 ) to get the line showing where pulse1 and pulse2 are equal.
    Disable the warning message.
ggplot( pulse ) +
  aes( x = pulse1, y = pulse2 ) +
  geom_point() +
  facet_wrap( ~ ran ) +
  coord_fixed() +
  geom_abline( slope = 1, color = "red", linetype = 2 ) +
  theme_bw() +
  xlab( "pulse1 (before exercise) [1/min]" ) +
  ylab( "pulse2 (after exercise) [1/min]" )

Extra exercises

  1. Rotate axis labels.
    When using facets the numbers on the bottom axis often overlap.
    Modify the chart from the previous exercise by adding (after theme_bw):
    theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)).
    vjust and hjust are numbers in range [0,1]. Understand their effect.
    Try angle=45.
ggplot( pulse ) +
  aes( x = pulse1, y = pulse2 ) +
  geom_point() +
  facet_wrap( ~ ran ) +
  coord_fixed() +
  geom_abline( slope = 1, color = "red", linetype = 2 ) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
  xlab( "pulse1 (before exercise) [1/min]" ) +
  ylab( "pulse2 (after exercise) [1/min]" )



Copyright © 2023 Biomedical Data Sciences (BDS) | LUMC