Page last updated: 04 May, 2019
Examples
One variable
##### scatter plot
ggplot(data = movies,
aes(x = votes, y = rating)) +
geom_point(aes(x = votes, y = rating),
color = discrete_wes_pal[1]) +
my_theme()
One variable shown by colour
##### scatter plot - with multiple groups
ggplot(data = movies,
aes(x = votes, y = rating)) +
geom_point(aes(colour = Genre)) +
scale_color_manual(values = discrete_wes_pal) +
guides(colour = guide_legend(override.aes = list(size = 5),
title = "",
label.hjust = 0,
label.vjust = 0.5)) +
my_theme()
One variable shown by size
##### scatter plot - with groups defined by size
ggplot(data = movies,
aes(x = votes, y = rating)) +
geom_point(aes(size = Genre),
color = discrete_wes_pal[1]) +
guides(size = guide_legend(title = "",
label.hjust = 0,
label.vjust = 0.5)) +
my_theme()
Scatter plot with line of fit and ci
##### scatter plot - with stat_smooth function with lines of fit and CI
ggplot(data = movies,
aes(x = votes, y = rating)) +
geom_point(aes(colour = Genre)) +
scale_color_manual(values = discrete_wes_pal) +
stat_smooth(aes(colour = Genre),
alpha = 0.2,
show.legend = FALSE) +
guides(colour = guide_legend(override.aes = list(size = 5),
title = "",
label.hjust = 0,
label.vjust = 0.5)) +
my_theme()
Grouped plots - facet_grid()
##### scatter plot - individual plots for each group horizontal
ggplot(data = movies,
aes(x = votes, y = rating)) +
geom_point(aes(colour = Genre)) +
scale_color_manual(values = discrete_wes_pal) +
facet_grid(Genre ~ .) + # facet_grid makes horizontal grids
guides(colour = guide_legend(override.aes = list(size = 5),
title = "",
label.hjust = 0,
label.vjust = 0.5)) +
my_theme() +
theme(
strip.text.y = element_blank()
)
Grouped plots - facet_wrap()
##### scatter plot - individual plots for each group in defined number of columns
ggplot(data = movies,
aes(x = votes, y = rating)) +
geom_point(aes(colour = Genre)) +
scale_color_manual(values = discrete_wes_pal) +
facet_wrap(~Genre, ncol=4) + # facet_wrap makes columns of n length
guides(colour = guide_legend(override.aes = list(size = 5),
title = "",
label.hjust = 0,
label.vjust = 0.5)) +
coord_flip() + # flips the x and y axis
my_theme() +
theme(
strip.text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