library(tidyverse)
library(broom)
model1 <- lm(hwy ~ displ + cyl, data = mpg)
model2 <- lm(hwy ~ displ + cyl + drv, data = mpg)
plot_data <- bind_rows(
tidy(model1, conf.int = TRUE) |> mutate(model = "Model 1"),
tidy(model2, conf.int = TRUE) |> mutate(model = "Model 2")
) |>
filter(term %in% c("displ", "cyl"))
# This is wrong, but that's because the legend key is actually kind of tricky
# here. It's not drawing the vertical line in the legend; it's drawing the
# horizontal error bars
ggplot(plot_data, aes(x = term, y = estimate, color = model)) +
geom_point() +
geom_errorbar(aes(ymin = conf.low, ymax = conf.high)) +
theme(legend.position = "top")
# You can see that's happening if you use geom_crossbar - the legend keys match
# the shapes in the plot
ggplot(plot_data, aes(x = term, y = estimate, color = model)) +
geom_point() +
geom_crossbar(aes(ymin = conf.low, ymax = conf.high)) +
theme(legend.position = "top")
# So ggplot isn't really doing anything *wrong*—it's just not showing the
# vertical line in the legend like it does with geom_pointrange. It's really
# just showing the horiztonal error bar, for whatever reason
# You can confirm also if you use geom_pointrange, where the legend will be right
ggplot(plot_data, aes(x = term, y = estimate, color = model)) +
geom_pointrange(aes(ymin = conf.low, ymax = conf.high)) +
theme(legend.position = "top")
# There's a neat workaround though! You can override the glyph that shows up in
# the legend with the "key_glyph" argument. Start typing `draw_key_` in the
# console to see all the possible glyphs
#
# Like this for a time series:
ggplot(plot_data, aes(x = term, y = estimate, color = model)) +
geom_point() +
geom_errorbar(aes(ymin = conf.low, ymax = conf.high), key_glyph = "timeseries") +
theme(legend.position = "top")
# Obviously you don't want that, but it's possible, which is neat
#
# To make the errorbar legend glyph show a vertical line instead of the
# horizontal error bar line, you can use the "vline" key glyph
ggplot(plot_data, aes(x = term, y = estimate, color = model)) +
geom_point() +
geom_errorbar(aes(ymin = conf.low, ymax = conf.high), key_glyph = "vline") +
theme(legend.position = "top")
Created on 2024-03-19 with reprex v2.0.2