This lesson is being piloted (Beta version)

Scatter plot

Overview

Teaching: 20 min
Exercises: 0 min
Questions
Objectives
  • Learn how to plot a nice scatter plot in ggplot2

Basic component of ggplot

Layers of ggplot

gp <- ggplot(mpg, aes(hwy, cty))

gp+geom_point(aes(color=cyl))
gp+geom_point(aes(color=factor(cyl)))
gp+geom_point(aes(color=factor(cyl)))+geom_smooth(method="lm")
gp+geom_point(aes(color=factor(cyl)))+geom_smooth(method="lm")
  +facet_grid(.~cyl)
# Save plot to file
ggsave("plot.png",width=5,height=5)

image

Scatter plot with full annotation

Another type of data:

data("midwest")
gg <- ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state, size=popdensity)) + 
  geom_smooth(method="loess", se=F) + 
  xlim(c(0, 0.1)) + 
  ylim(c(0, 500000)) + 
  labs(subtitle="Area Vs Population", 
       y="Population", 
       x="Area", 
       title="Scatterplot", 
       caption = "Source: midwest")
plot(gg)

image

Key Points

  • ggplot2, scatter plot