Skip to content

Instantly share code, notes, and snippets.

@eddjberry
Last active November 8, 2019 14:21
Show Gist options
  • Save eddjberry/d884fdcf6e91c90b578531f0e4b2ee8e to your computer and use it in GitHub Desktop.
Save eddjberry/d884fdcf6e91c90b578531f0e4b2ee8e to your computer and use it in GitHub Desktop.
Create a plot of percentages for some groups with lines for different sub-groups. E.g. regions along the x-axis with lines for the percentage of the population in different age-bands
#=================================================
# geom_line() + geom_ribbon()
#=================================================
# plots by group
plot_by_group <- function(df, x, colour) {
# create the summary data using # group_prop()
df_summary <- df %>%
dplyr::filter(!is.na({{ colour }})) %>%
group_prop({{ x }}, {{ colour }})
# create a df for the labels
df_labels <- df_summary %>%
dplyr::filter({{ x }} == levels({{ x }})[1])
# create the label for the x-axis
x_label <-
rlang::enquo(x) %>%
rlang::quo_name() %>%
stringr::str_replace_all('_', ' ') %>%
stringr::str_to_title()
# create the plot
ggplot2::ggplot(df_summary) +
ggplot2::aes({{ x }}, prop, color = {{ colour }}, fill = {{ colour }}, group = {{ colour }}) +
ggplot2::coord_cartesian(ylim = c(0, 1)) +
ggplot2::geom_ribbon(aes(ymin = prop - prop_se, ymax = prop + prop_se),
alpha = .25, color = 'transparent') +
ggplot2::geom_line() +
ggrepel::geom_text_repel(data = df_labels, ggplot2::aes(label = rag),
family = 'mono', nudge_x = -0.1) +
ggplot2::scale_y_continuous(labels = scales::percent_format()) +
ggplot2::labs(x = x_label,
y = 'Percentage')
}
#=================================================
# geom_pointrange()
#=================================================
# plots by group
plot_by_group <- function(df, x, colour) {
# create the summary data using # group_prop()
df_summary <- df %>%
dplyr::filter(!is.na({{ colour }})) %>%
group_prop({{ x }}, {{ colour }})
# create a df for the labels
df_labels <- df_summary %>%
dplyr::filter({{ x }} == levels({{ x }})[1])
# create the label for the x-axis
x_label <-
rlang::enquo(x) %>%
rlang::quo_name() %>%
stringr::str_replace_all('_', ' ') %>%
stringr::str_to_title()
# create the plot
ggplot2::ggplot(df_summary) +
ggplot2::aes({{ x }}, prop, color = {{ colour }}, fill = {{ colour }}, group = {{ colour }}) +
ggplot2::coord_cartesian(ylim = c(0, 1)) +
ggplot2::geom_line(
alpha = 0.5,
position = position_dodge(0.3)) +
ggplot2::geom_pointrange(
aes(ymin = prop - prop_se, ymax = prop + prop_se),
size = 0.5,
position = position_dodge(0.3)) +
ggrepel::geom_text_repel(
data = df_labels, ggplot2::aes(label = rag),
family = 'mono',
nudge_x = -0.3,
min.segment.length = 2) +
ggplot2::scale_y_continuous(labels = scales::percent_format()) +
ggplot2::labs(x = x_label,
y = 'Percentage')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment