Last active
May 16, 2023 18:49
-
-
Save holgerbrandl/2b216b2e3ec51d48b2be4d9f46f0ff5e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
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
Forgive me my ignorance, but what is this dataset that you used here? I would like to replicate this example.