7

I'm trying to use the labeller function within ggplot2 to label faceted plots. When I run my code I don't get any errors or warnings (which I know doesn't always mean everything is working like I think it is), but instead of my predefined labels being applied to the plots I just get "NA" as the plot label. A small subsample of my data is:

w <- structure(list(Var1 = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L), .Label = c("0", "1"), class = "factor"), Var2 = structure(c(1L, 
1L, 2L, 2L, 1L, 1L, 2L, 2L), .Label = c("0", "1"), class = "factor"), 
Freq = c(9L, 18L, 7L, 12L, 11L, 12L, 15L, 7L), Index = c(1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L), ComboCode = c("00", "10", "01", 
"11", "00", "10", "01", "11"), Var1Name = c("hibernate", 
"hibernate", "hibernate", "hibernate", "migrate", "migrate", 
"migrate", "migrate"), Var2Name = c("migrate", "migrate", 
"migrate", "migrate", "solitary_or_small_clusters", "solitary_or_small_clusters", 
"solitary_or_small_clusters", "solitary_or_small_clusters"
)), .Names = c("Var1", "Var2", "Freq", "Index", "ComboCode", 
"Var1Name", "Var2Name"), row.names = c("2.1", "2.2", "2.3", "2.4", 
"3.1", "3.2", "3.3", "3.4"), class = "data.frame")

panel_labels <- c("hibernate/migrate", "migrate/solitary_or_small_clusters")

and here is my code used to produce the plot:

library(ggplot2)
ggplot(w, aes(x = ComboCode, y = Freq, fill = ComboCode)) +
geom_bar(stat = "Identity") +
facet_wrap(~Index, labeller = labeller(Index = panel_labels)) +
guides(fill = FALSE)

If anyone could shed some light as to why the labels are not being applied to the plots I would greatly appreciate it.

pogibas
  • 27,303
  • 19
  • 84
  • 117
Curtis
  • 449
  • 1
  • 4
  • 17

1 Answers1

16

labeller needs named arguments.

Passing only a vector to labeller will return NA:

library(ggplot2)

panel_labels <- c("hibernate/migrate", "migrate/solitary_or_small_clusters")
ggplot(w, aes(ComboCode, Freq, fill = ComboCode)) +
    geom_bar(stat = "Identity") +
    facet_wrap(~Index, labeller = labeller(Index = panel_labels)) +
    guides(fill = FALSE) +
    labs(title = "Vector")

Passing named vector will return changed labels:

panel_labels <- c("1" = "hibernate/migrate", "2" = "migrate/solitary_or_small_clusters")
ggplot(w, aes(ComboCode, Freq, fill = ComboCode)) +
    geom_bar(stat = "Identity") +
    facet_wrap(~Index, labeller = labeller(Index = panel_labels)) +
    guides(fill = FALSE) +
    labs(title = "Named vector")

enter image description here

pogibas
  • 27,303
  • 19
  • 84
  • 117
  • Thanks so much @PoGibas! I attempted to upvote your answer but I don't have enough rep points yet. Much appreciated – Curtis Jun 06 '18 at 22:51