2024

Load the ggplot2 package

# Don't forget to load the ggplot2 package
library(ggplot2)

Common Geoms: geom_point()

ggplot(data = mpg, aes(x = displ, y = hwy, color = class)) + 
  geom_point()

Common Geoms: geom_point()

Common Geoms: geom_line

# Line Plot
ggplot(data = mpg, aes(x = displ, y = hwy, color = class)) + 
  geom_line()

Common Geoms: geom_line

Common Geoms: geom_smooth

# Scatter Plot with a Smooth Line
ggplot(data = mpg, aes(x = displ, y = hwy, color = class)) + 
  geom_point() + 
  geom_smooth()

Common Geoms: geom_smooth

Common Geoms: geom_bar

# Bar Chart
ggplot(data = mpg, aes(x = class, fill = class)) + 
  geom_bar()

Common Geoms: geom_bar

Common Geoms: geom_boxplot

# Boxplot
ggplot(data = mpg, aes(x = class, y = hwy, fill = class)) + 
  geom_boxplot()

Common Geoms: geom_boxplot

Common Geoms: geom_violin

# Violin Plot
ggplot(data = mpg, aes(x = class, y = hwy, fill = class)) + 
  geom_violin()

Common Geoms: geom_violin

Common Geoms: geom_histogram

# Histogram
ggplot(data = mpg, aes(x = hwy)) + 
  geom_histogram()

Common Geoms: geom_histogram

Common Geoms: geom_density

# Density Plot
ggplot(data = mpg, aes(x = hwy, fill = class)) + 
  geom

Common Geoms: geom_density

Question

Add a smooth line to the following plot that summarizes the relationship between these two variables.

ggplot(data = mpg, aes(x = displ, y = hwy, color = class)) +
  geom_point()
Click here for the answer
ggplot(data = mpg, aes(x = displ, y = hwy, color = class)) +
  geom_point() +
  geom_smooth()

Question

Modify the following code to create a histogram exploring the distribution of highway miles per gallon (hwy) in the mpg dataset. Adjust the number of bins to refine the histogram’s granularity.

ggplot(data = mpg, aes(x = hwy))
Click here for the answer
ggplot(data = mpg, aes(x = hwy)) +
  geom_histogram(bins=100)