R
Beginner
1 min read
Scales, Themes, and Customisation
Example
library(ggplot2)
data(mpg)
# Manual colour scale
ggplot(mpg, aes(x = displ, y = hwy, colour = drv)) +
geom_point(size = 2) +
scale_colour_manual(
values = c("4" = "#E41A1C", "f" = "#377EB8", "r" = "#4DAF4A"),
labels = c("4" = "Four-wheel", "f" = "Front", "r" = "Rear")
)
# Log scale on x axis
ggplot(diamonds, aes(x = carat, y = price)) +
geom_point(alpha = 0.1) +
scale_x_log10() +
scale_y_log10(labels = scales::comma) +
labs(title = "Diamond price vs carat (log-log)")
# Continuous colour gradient
ggplot(mpg, aes(x = displ, y = hwy, colour = cty)) +
geom_point(size = 2) +
scale_colour_gradient(low = "yellow", high = "red") +
labs(colour = "City MPG")
# Axis breaks and limits
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
scale_x_continuous(limits = c(1, 7),
breaks = seq(1, 7, by = 1)) +
scale_y_continuous(limits = c(10, 50))
# theme_minimal and manual theme tweaks
p <- ggplot(mpg, aes(x = class)) +
geom_bar(fill = "steelblue") +
theme_minimal() +
theme(
plot.title = element_text(size = 16, face = "bold"),
axis.text.x = element_text(angle = 45, hjust = 1),
panel.grid.major.x = element_blank(),
legend.position = "bottom"
) +
labs(title = "Styled bar chart")
print(p)
# Saving a plot
# ggsave("my_plot.png", plot = p, width = 8, height = 5, dpi = 300)