Extra Challenges

Last updated on 2022-09-13 | Edit this page

R

library(tidyverse)
surveys <- read_csv("data/cleaned/surveys_complete_77_89.csv")

Challenge: ggplot2 syntax

There are some issues with these ggplot2 examples. Can you figure out what is wrong with each one?

R

ggplot(data = surveys, 
       mapping = aes(x = weight, y = hindfoot_length, color = "blue")) +
  geom_point()

Our points don’t actually turn out blue, because we defined the color inside of aes(). aes() is used for translating variables from the data into plot elements, like color. There is no variable in the data called “blue”.

Challenge: ggplot2 syntax (continued)

R

ggplot(data = surveys, 
       mapping = aes(x = "weight", y = "hindfoot_length")) +
  geom_point()

Variable names inside aes() should not be wrapped in quotes.

Challenge: ggplot2 syntax (continued)

R

ggplot(data = surveys, 
       mapping = aes(x = weight, y = hindfoot_length)) 
  + geom_point()

When adding things like geom_ or scale_ functions to a ggplot(), you have to end a line with +, not begin a line with it.

Challenge: ggplot2 syntax (continued)

R

ggplot(data = surveys, x = weight, y = hindfoot_length) +
  geom_point()

When translating variables from the data, like weight and hindfoot_length, to elements of the plot, like x and y, you must put them inside aes().

Challenge: ggplot2 syntax (continued)

R

ggplot(data = surveys, 
       mapping = aes(x = weight, y = hindfoot_length, color = species_id)) +
  geom_point() +
  scale_color_continuous(type = "viridis")

species_id is a categorical variable, but scale_color_continuous() supplies a continuous color scale. scale_color_discrete() would give a discrete/categorical scale.