Skip to content

Instantly share code, notes, and snippets.

@holgerbrandl
Last active May 16, 2023 18:49
Show Gist options
  • Save holgerbrandl/2b216b2e3ec51d48b2be4d9f46f0ff5e to your computer and use it in GitHub Desktop.
Save holgerbrandl/2b216b2e3ec51d48b2be4d9f46f0ff5e to your computer and use it in GitHub Desktop.
require(dplyr)
require(ggplot2)
# make sure that purrr package is installed to use purrr::set_names
# aggregate data
df = mpg %>%
group_by(year, manufacturer) %>%
summarize(mixmpg = mean(cty + hwy)) %>%
# create dummy var which reflects order when sorted alphabetically
mutate(ord =sprintf("%02i", as.integer(rank(mixmpg))) )
# `ord` is plotted on x-axis instead of `manufacturer`
ggplot(df, aes(x = ord, y = mixmpg)) +
# geom_col() is replacement for geom_bar(stat = "identity")
geom_col() +
# independent x-axis scale in each facet,
# drop absent factor levels (actually not required here)
facet_wrap(~ year, scales = "free_x", drop = TRUE) +
# use named character vector to replace x-axis labels
scale_x_discrete(labels = with(df, as.character(manufacturer)%>% set_names(ord))) +
# replace x-axis title
xlab(NULL) +
# rotate x-axis labels
theme(axis.text.x = element_text(angle = 90, hjust=1, vjust=.5))
@fgashakamba
Copy link

Forgive me my ignorance, but what is this dataset that you used here? I would like to replicate this example.

@holgerbrandl
Copy link
Author

Forgive my ignorance of not properly including required libraries in the first place. :-) I've updated the example to be more self-contained. mpg is loaded along with ggplot2 package, see https://ggplot2.tidyverse.org/reference/mpg.html#ref-usage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment