ggplot2

ggplot2 #

Snippets of code and tidbits related to ggplot2.

Most of the headings are basically what I would Google for + ggplot2.

Data Prep #

Ordering numerical variables #

Ordering categorical variables #

Sometimes, you just want to order categorical variables in a particular sequence.

some_dataframe %>%
    mutate(
        some_categorical = fct_relevel(
            some_categorical = c(<first>, <second>, <third>, ...)
        )
    ) %>%
    ggplot(...) + ...

Where <first>, <second>, <third>, ... is a manual specification of the order.

Color #

Manually define colors of groups #

First, the dataframe should have some specification of groups, such as a binary column of some sort (e.g., “Big” / “Small”, “Left” / “Right”, etc.)

The ggplot2 part of it should look like the following:

some_data_frame %>%
    ggplot(
        aes(
            ...,
            color = factor(some_column),
            ...
        )
    ) +
    scale_color_manual(values = c("some_value" = red, "some_other_value" = blue)) +
    ...

Labels #

Make axis label percents #

scale_y_continuous(labels = scales::percent)

Remove legend title #

ggplot2(...) +
    theme(legend.title=element_blank())

log transform an axis #

Sometimes, the relative values of categories are so divergent that trying to present them on a linear scale is ineffective. Enter log transforms.

some_dataframe %>%
    ggplot(...) +
    scale_x_log10() +
    # scale_x_log10() +
    ...

Remember the rules of logarithms. It might require some tampering with the source data for log transforms to make sense.

Themes #

Left adjust title(s) to plot #

For when you want the title and other bodies of text to be aligned fully to the left.

ggplot(...) +
    theme(
        plot.title.position = "plot",
        plot.subtitle.position = "plot",
        plot.caption.position =  "plot"
    )   

And so on.