Skip to content

Instantly share code, notes, and snippets.

@RussellDash332
Last active September 10, 2021 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RussellDash332/6a37c8e3ae13001039a60bb2564fa5ee to your computer and use it in GitHub Desktop.
Save RussellDash332/6a37c8e3ae13001039a60bb2564fa5ee to your computer and use it in GitHub Desktop.
Code used on my Medium post
## Install the ggplot2 package
install.packages("ggplot2")
## Load the ggplot2 package
library(ggplot2)
## The dataset itself
mtcars
## Find out the dataset's structure
str(mtcars)
## A bunch of plots to compare
ggplot(mtcars, aes(mpg, disp)) + geom_point()
ggplot(mtcars, aes(mpg, disp, color = cyl)) + geom_point()
ggplot(mtcars, aes(mpg, disp, color = factor(cyl))) + geom_point()
ggplot(mtcars, aes(mpg, disp, color = factor(cyl), size = hp)) + geom_point()
ggplot(mtcars, aes(mpg, disp, color = factor(cyl), size = hp)) + geom_point(alpha = 0.3)
ggplot(mtcars, aes(mpg, disp, color = factor(cyl), size = hp)) + geom_point(alpha = 0.3) + scale_x_log10() + scale_y_log10()
ggplot(mtcars, aes(mpg, disp)) + geom_point() + facet_wrap(~ cyl)
ggplot(mtcars, aes(mpg, disp, color = factor(cyl))) + geom_point() + expand_limits(x = 0)
ggplot(mtcars, aes(mpg, disp, color = factor(cyl))) + geom_point() + expand_limits(y = 0)
ggplot(mtcars, aes(mpg, disp, color = factor(cyl))) + geom_point() + expand_limits(x = 50)
ggplot(mtcars, aes(mpg, disp, color = factor(cyl))) + geom_point() + expand_limits(x = 0:50)
ggplot(mtcars, aes(mpg, disp, color = factor(cyl))) + geom_point() + ggtitle("Plot of disp against mpg")
ggplot(mtcars, aes(mpg, disp, color = factor(cyl))) +
geom_point() +
labs(
title = "Plot of disp against mpg",
subtitle = "This plot uses ggplot2",
x = "Miles per US gallon",
y = "Displacement (cu.in.)",
color = "Cylinders"
)
## Save to my_plot
my_plot <- ggplot(mtcars, aes(mpg, disp, color = factor(cyl))) +
geom_point() +
labs(
title = "Plot of disp against mpg",
subtitle = "This plot uses ggplot2",
x = "Miles per US gallon",
y = "Displacement (cu.in.)",
color = "Cylinders"
)
my_plot + theme_gray()
my_plot + theme_bw()
my_plot + theme_linedraw()
my_plot + theme_light()
my_plot + theme_minimal()
my_plot + theme_classic()
my_plot + theme_void()
my_plot + theme_dark()
## Installing ggthemes for custom themes
install.packages("ggthemes")
library(gthemes)
my_plot + theme_tufte()
my_plot + theme_economist()
my_plot + theme_stata()
my_plot + theme_wsj()
my_plot + theme_calc()
my_plot + theme_hc()
## Different types of visualizations
ggplot(mtcars, aes(mpg, disp)) + geom_line()
ggplot(mtcars, aes(mpg, disp)) + geom_col()
ggplot(mtcars, aes(mpg)) + geom_histogram(bins = 5)
ggplot(mtcars, aes(factor(cyl), disp)) + geom_boxplot()
ggplot(mtcars, aes(mpg, disp)) + geom_point() + geom_line()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment