Skip to content

Instantly share code, notes, and snippets.

@aravindhebbali
Last active September 25, 2017 09:33
Show Gist options
  • Save aravindhebbali/1b27833e8ace1c27e1cae1f6cdf21d2b to your computer and use it in GitHub Desktop.
Save aravindhebbali/1b27833e8ace1c27e1cae1f6cdf21d2b to your computer and use it in GitHub Desktop.
ggplot2: Scatter Plots
# install
install.packages('ggplot2')
install.packages('readr')
# library
library(ggplot2)
library(readr)
# Basic Plot
ggplot(mtcars) +
geom_point(aes(disp, mpg))
# Jitter
ggplot(mtcars) +
geom_point(aes(disp, mpg), position = 'jitter')
# Jitter
ggplot(mtcars) +
geom_jitter(aes(disp, mpg))
# Map Color to Variable (Categorical)
ggplot(mtcars) +
geom_point(aes(disp, mpg, color = factor(cyl)),
position = 'jitter')
# Map Color to Variable (Continuous)
ggplot(mtcars) +
geom_point(aes(disp, mpg, color = hp),
position = 'jitter')
# Specify Value for Color
ggplot(mtcars) +
geom_point(aes(disp, mpg), color = 'blue',
position = 'jitter')
# Specify Value for Alpha
ggplot(mtcars) +
geom_point(aes(disp, mpg), color = 'blue', alpha = 0.4,
position = 'jitter')
# Map Shape to Variable
ggplot(mtcars) +
geom_point(aes(disp, mpg, shape = factor(cyl)),
position = 'jitter')
# Specify Value for Shape
ggplot(mtcars) +
geom_point(aes(disp, mpg), shape = 3,
position = 'jitter')
# Map Size to Variable
ggplot(mtcars) +
geom_point(aes(disp, mpg, size = hp), color = 'blue',
position = 'jitter')
# Specify Value for Size
ggplot(mtcars) +
geom_point(aes(disp, mpg), size = 3,
position = 'jitter')
# Regression Line
ggplot(mtcars, aes(disp, mpg)) +
geom_point(position = 'jitter') +
geom_smooth(method = 'lm', se = FALSE)
# Regression Line - Conf. Interval
ggplot(mtcars, aes(disp, mpg)) +
geom_point(position = 'jitter') +
geom_smooth(method = 'lm', se = TRUE)
# Regression Line - Loess Method
ggplot(mtcars, aes(disp, mpg)) +
geom_point(position = 'jitter') +
geom_smooth(method = 'loess', se = FALSE)
# Fit Line - Intercept & Slope
ggplot(mtcars, aes(disp, mpg)) +
geom_point(position = 'jitter') +
geom_abline(slope = 29.59985, intercept = -0.04122)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment