Apply custom model labels in ggplot2

61 Views Asked by At

This is likely trivial, but how can I:

  1. Apply labels to each modelnum value on the y axis? Could just be named "Label1" for "a", "Label2" for "b" or something like that.
  2. Reverse the order alphabetically within each facet, so that the letter higher in the alphabet is at the top of a given facet?

Code:

library(ggplot2)
ggplot(d, aes(y = modelnum, x = odds_ratio, color = sample,
               xmin = ci_lower, xmax = ci_upper)) +
  geom_errorbar(width = .1) +
  geom_point(size = 3) +
  geom_vline(xintercept = 1, 
             linetype = "dashed", 
             color = "black",
             linewidth = .3) +
  facet_wrap(~sample,
             scales = "free_y",
             nrow = 3) +
  scale_color_manual(values = c("Never" = "gray30",
                                "Pooled" = "red",
                                "Post" = "blue")) +
  labs(title = "Models",
       x = "Odds Ratio",
       y = "") +
  theme_bw() +
  theme(legend.position = "none"
        )

Data:

d <- structure(list(modelnum = c("a", "b", "c", "a", "b", "d", "e", 
"f"), odds_ratio = c(0.11, 0.151, 0.0629, 0.193, 0.052, 0.1065, 
0.2, 0.089), ci_lower = c(0.048, 0.054, 0.0049, 0.052, 0.004, 
0.0566, 0.067, 0.017), ci_upper = c(0.271, 0.425, 0.799, 0.646, 
0.72, 0.19, 0.5948, 0.461), sample = c("Pooled", "Pooled", "Pooled", 
"Never", "Never", "Never", "Post", 
"Post")), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -8L))

2

There are 2 best solutions below

0
On

You can do this very similar to how you mappped the colors, just add this somewhere in your ggplot:

+ scale_y_discrete(labels = c("a"="Label1", "b"="Label2"), limits=rev)

The limits=rev option will reverse a discrete axis. You could also use numeric values and map the breaks/labels to those for more fine-grained control over order.

0
On

Just one way to achieve what you are after. Create a label variable and reorder y inside aes() accordingly, i.e., y = reorder(label, desc(modelnum)).

library(ggplot2); library(dplyr)
d |>
  mutate(label = paste0("Label", modelnum)) |>
  ggplot(aes(y = reorder(label, desc(modelnum)), x = odds_ratio, color = sample,
              xmin = ci_lower, xmax = ci_upper)) +
  geom_errorbar(width = .1) +
  geom_point(size = 3) +
  geom_vline(xintercept = 1, 
             linetype = "dashed", 
             color = "black",
             linewidth = .3) +
  facet_wrap(~ sample,
             scales = "free_y",
             nrow = 3) +
  scale_color_manual(values = c("Never" = "gray30",
                                "Pooled" = "red",
                                "Post" = "blue")) +
  labs(title = "Models",
       x = "Odds Ratio",
       y = "") +
  theme_bw() +
  theme(legend.position = "none")