Refine Your Plots
February 19, 2025
scale_ functions for color or fill.RColorBrewerRColorBrewer package provides a wide range of named color palettes.
scale_color_brewer() or scale_fill_brewer() functions with palette parameter.
scale_color_brewer(palette = ...).scale_color_manual() or scale_fill_manual().
values argument that can be specified as vector of color names or hex colors.RColorBrewer provides the color-blind friendly pallets.color to highlight some aspect of our data.
color.theme()theme() function allows us to exert very fine-grained control over the appearance of all kinds of text and graphical elements in a plot.theme()element_blank() to remove a number of elements by naming them and making them disappear.theme()gss_lon data.theme()theme()p2 <- p1 +
geom_vline(
data = mean_age |>
filter(year %in% yrs),
aes(xintercept = xbar),
color = "white", size = 0.5) +
geom_text(
data = mean_age |>
filter(year %in% yrs),
aes(x = xbar, y = y, label = xbar),
nudge_x = 7.5, color = "white",
size = 3.5, hjust = 1) +
geom_text(data = yr_labs |>
filter(year %in% yrs),
aes(x = x, y = y, label = year))
p2nudge_x argument to push the label slightly to the right of its x-value.theme()facet_grid() we use the switch argument to move the labels to the left.theme()p2a <- p3 +
theme(
plot.title =
element_text(size = 16),
axis.text.x=
element_text(size = 12),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y = element_blank(),
strip.background = element_blank(),
strip.text.y = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
labs(x = "Age", y = NULL,
title =
"Age Distribution of\nGSS Respondents")
p2aggridgesggridges allows the distributions to overlap vertically.
ggridgesfactor() converts a variable to a factor variable.
levels parameter, we can set the categories of a categorical variable.ggridgesp2b <- p +
geom_density_ridges(
alpha = 0.6, fill = "lightblue",
scale = 1.5) +
scale_x_continuous(
breaks = c(25, 50, 75)) +
scale_y_discrete(
expand = c(0.01, 0)) +
labs(x = "Age", y = NULL,
title =
"Age Distribution of\nGSS Respondents") +
theme_ridges() + # make labels aligned properly
theme(
title =
element_text(
size = 16, face = "bold"))
p2bexpand argument in scale_y_discrete() adjusts the scaling of the y-axis slightly.gridExtra::grid.arrange()gridExtra package provides grid.arrange() function.
grid.arrange() arranges multiple ggplot objects on a page, and draw tables of figures.gridExtra::grid.arrange()studebt to describe how the distribution of Debt pct varies by type.Instead of having separate bars distinguished by heights, we can array the percentages for each distribution proportionally within a single bar.
Let’s make a stacked bar chart with just two main bars, and lie them on their side for comparison.