Modify X and Y axis
In this module, we will learn how to modify the X and Y axis using the following functions:
scale_x_continuous()
scale_y_continuous()
scale_x_discrete()
scale_y_discrete()
library(ggplot2)
library(dplyr)
library(tidyr)
scale_x_continuous()
and scale_y_continuous()
take the following arguments:
ggplot(mtcars) +
geom_point(aes(disp, mpg))
ggplot(mtcars) +
geom_point(aes(disp, mpg)) +
scale_x_continuous(name = "Displacement")
ggplot(mtcars) +
geom_point(aes(disp, mpg)) +
scale_x_continuous(limits = c(0, 600))
ggplot(mtcars) +
geom_point(aes(disp, mpg)) +
scale_x_continuous(breaks = c(0, 150, 300, 450, 600))
ggplot(mtcars) +
geom_point(aes(disp, mpg)) +
scale_x_continuous(breaks = c(0, 150, 300, 450, 600),
labels = c('0', '150', '300', '450', '600'))
ggplot(mtcars) +
geom_point(aes(disp, mpg)) +
scale_x_continuous(position = 'top')
ggplot(mtcars) + geom_point(aes(disp, mpg)) +
scale_x_continuous(name = "Displacement", limits = c(0, 600),
breaks = c(0, 150, 300, 450, 600), position = 'top',
labels = c('0', '150', '300', '450', '600'))
ggplot(mtcars) + geom_point(aes(disp, mpg)) +
scale_y_continuous(name = "Miles Per Gallon", limits = c(0, 45),
breaks = c(0, 15, 30, 45), position = 'right',
labels = c('0', '15', '30', '45'))
scale_x_discrete()
and scale_y_discrete()
take the following arguments:
ggplot(mtcars) +
geom_bar(aes(factor(cyl))) +
scale_x_discrete(name = "Number of Cylinders")
ggplot(mtcars) +
geom_bar(aes(factor(cyl))) +
scale_x_discrete(labels = c("4" = "Four", "6" = "Six", "8" = "Eight"))
ggplot(mtcars) +
geom_bar(aes(factor(cyl))) +
scale_x_discrete(breaks = c("4", "6", "8"))
ggplot(mtcars) +
geom_bar(aes(factor(cyl))) +
scale_x_discrete(position = 'bottom')
ggplot(mtcars) + geom_bar(aes(factor(cyl))) +
scale_x_discrete(name = "Number of Cylinders",
labels = c("4" = "Four", "6" = "Six", "8" = "Eight"),
breaks = c("4", "6", "8"), position = "bottom")