4.6 Explore ggplot2 object: Exercise

  • Once stored we can explore our ggplot2 object (check class with class(p))
  • p$...: Explore different elements of plot object
    • e.g., p$data, p$layers, p$mapping, p$labels etc.
  • Q: What can you decipher from the summary below?
## data: mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb [32x11]
## mapping:  x = ~mpg, y = ~drat
## faceting: <ggproto object: Class FacetNull, Facet, gg>
##     compute_layout: function
##     draw_back: function
##     draw_front: function
##     draw_labels: function
##     draw_panels: function
##     finish_data: function
##     init_scales: function
##     map_data: function
##     params: list
##     setup_data: function
##     setup_params: function
##     shrink: TRUE
##     train_scales: function
##     vars: function
##     super:  <ggproto object: Class FacetNull, Facet, gg>
## -----------------------------------
## mapping: colour = ~factor(gear) 
## geom_point: na.rm = FALSE
## stat_identity: na.rm = FALSE
## position_identity 
## 
## geom_smooth: se = TRUE, na.rm = FALSE, orientation = NA
## stat_smooth: method = lm, formula = NULL, se = TRUE, n = 80, fullrange = FALSE, level = 0.95, na.rm = FALSE, orientation = NA, method.args = list(), span = 0.75
## position_identity

We can also access sub elements.

  • Important: When we layer on a ggplot2 plot object we simply change these elements
    • e.g., we could change the axes of an existing plot that is stored in p
## [[1]]
## mapping: colour = ~factor(gear) 
## geom_point: na.rm = FALSE
## stat_identity: na.rm = FALSE
## position_identity 
## 
## [[2]]
## geom_smooth: se = TRUE, na.rm = FALSE, orientation = NA
## stat_smooth: method = lm, formula = NULL, se = TRUE, n = 80, fullrange = FALSE, level = 0.95, na.rm = FALSE, orientation = NA, method.args = list(), span = 0.75
## position_identity
## Aesthetic mapping: 
## * `x` -> `mpg`
## * `y` -> `drat`
## $x
## [1] "mpg"
## 
## $y
## [1] "drat"
## 
## $colour
## [1] "factor(gear)"