Scatter plot
Overview
Teaching: 20 min
Exercises: 0 minQuestions
Objectives
Learn how to plot a nice scatter plot in ggplot2
Basic component of ggplot
- A data frame
- aes: aesthetic mappings showing how data are mapped to color, size
- geoms: geometric objects like points, lines, shapes.
- facets: for conditional plots.
- stats: statistical transformations like binning, quanti les, smoothing.
- scales: what scale an aesthetic map uses
- coordinate system

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)

Scatter plot with full annotation
- Labels: xlab(), ylab(), labs(), ggtitle()
- global annotation: use theme()
- Standard appearance: theme_bw()
gp+geom_point(aes(color=factor(cyl), size=factor(cyl)))+ geom_smooth(method="lm")+ xlab("Highway miles per gallon")+ ylab("city miles per gallon")+ ggtitle("Scatter plot for cty & hwy")+ xlim(10,40)+ylim(10,40)+ theme_bw(base_size = 15)
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)

Key Points
ggplot2, scatter plot