1

I need to fill $\lambda$ = x (6 values of x) on each of the 6 facet_grid panels

ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_grid(am ~ cyl) +
  theme(panel.spacing = unit(1, "lines")) +
  annotate("text", label = c("\u03BB = 1", "\u03BB = 2", "\u03BB = 0.1", "\u03BB = 2.2", "\u03BB = 1.5", "\u03BB = 5") , size = 4, x = 30, y = 5)

I've modified the solutions here Annotating text on individual facet in ggplot2 but got an error.

Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (36): label

Backtrace:
  1. base `<fn>`(x)
  2. ggplot2:::print.ggplot(x)
  4. ggplot2:::ggplot_build.ggplot(x)
  5. ggplot2 by_layer(function(l, d) l$compute_geom_2(d))
  6. ggplot2 f(l = layers[[i]], d = data[[i]])
  7. l$compute_geom_2(d)
  8. ggplot2 f(..., self = self)
  9. self$geom$use_defaults(data, self$aes_params, modifiers)
 10. ggplot2 f(..., self = self)
 11. ggplot2:::check_aesthetics(params[aes_params], nrow(data))

The expected graph should have the values of lambda follow the = sign as follow

enter image description here

hnguyen
  • 772
  • 6
  • 17
  • 1
    a much better way to achieve `c("\u03BB = 1", "\u03BB = 2", "\u03BB = 0.1", "\u03BB = 2.2", "\u03BB = 1.5", "\u03BB = 5")` is `paste("\u03BB =", c(.1, 2, .1, 2.2, 1.5))` - this can also help to make your code more programmatic – tjebo May 29 '22 at 20:12
  • Thank you very much. I do like this solution. Even though not relevant to this specific problem, stefan's solution is more flexible, especially if I have 2 groups of point (colored by another variable in the `cars` df). – hnguyen May 29 '22 at 20:29

1 Answers1

3

One option to achieve your desired result would be to add the labels via a geom_text and a data.frame of labels like so:

library(ggplot2)

df_label <- data.frame(
  label = c("\u03BB = 1", "\u03BB = 2", "\u03BB = 0.1", "\u03BB = 2.2", "\u03BB = 1.5", "\u03BB = 5"),
  am = rep(0:1, each = 3),
  cyl = rep(c(4, 6, 8), 2)
)

ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  geom_text(data = df_label, aes(label = label), size = 4, x = 30, y = 5) +
  facet_grid(am ~ cyl) +
  theme(panel.spacing = unit(1, "lines"))

stefan
  • 90,330
  • 6
  • 25
  • 51