library(tidyverse)
# Make some data
data_to_plot <- mpg %>%
group_by(drv) %>%
summarize(avg_mpg = mean(hwy))
data_to_plot
#> # A tibble: 3 x 2
#> drv avg_mpg
#> <chr> <dbl>
#> 1 4 19.2
#> 2 f 28.2
#> 3 r 21
# Normal way to plot this, where x is the categorical variable and y is numeric
ggplot(data_to_plot, aes(x = drv, y = avg_mpg)) +
geom_col()
# Old way to rotate this so the bars go horizontal
# But this gets confusing because if you want to change the label on the bottom,
# for instance, that's still the y-axis, it's just rotated, so you have to say
# labs(y = "whatever")
ggplot(data_to_plot, aes(x = drv, y = avg_mpg)) +
geom_col() +
labs(y = "Average MPG") +
coord_flip()
# Since ggplot2 version 3.3.0, you don't have to put a categorical variable as
# x; you can now put it on y, which means you don't need to use coord_flip
# anymore *and* you don't need to remember that the bottom is the flipped
# y-axis. The bottom is the x-axis, as it should be
ggplot(data_to_plot, aes(x = avg_mpg, y = drv)) +
geom_col() +
labs(x = "Average MPG")
# My cheating way to get geom_pointrange to show lollipops is to set the min to
# 0 and the max to the actual value:
ggplot(data_to_plot, aes(x = drv, y = avg_mpg)) +
geom_pointrange(aes(ymin = 0, ymax = avg_mpg))
# In the olden days, you'd flip this with coord_flip(), but then you get the
# weird x-axis-is-really-the-y-axis issue:
ggplot(data_to_plot, aes(x = drv, y = avg_mpg)) +
geom_pointrange(aes(ymin = 0, ymax = avg_mpg)) +
labs(y = "Average MPG") +
coord_flip()
# But now you can reverse x and y just fine. You just also have to use xmin and
# xmax instead of ymin and ymax
ggplot(data_to_plot, aes(x = avg_mpg, y = drv)) +
geom_pointrange(aes(xmin = 0, xmax = avg_mpg)) +
labs(x = "Average MPG")
Created on 2021-05-11 by the reprex package (v1.0.0)