MattCowgill / ggannotate

Interactively annotate ggplots
Other
309 stars 20 forks source link

Add factor levels for facets #28

Closed jonathananolan closed 3 years ago

jonathananolan commented 3 years ago

When you specify facet order using factor levels, ggannotate returns back to alphabetical order.

library(tidyverse)

data <- tribble(~r_awesomeness,~name,~Nationality,~time,
                1,"Matt","Western Austalian",1,
                1,"Will","Australian",1,
                10,"Hadley","New Zealander",1,
                2,"Matt","Western Austalian",2,
                2,"Will","Australian",2,
                10,"Hadley","New Zealander",2,
                2,"Matt","Western Austalian",3,
                5,"Will","Australian",3,
                10,"Hadley","New Zealander",3) %>% 
  mutate(name = fct_relevel(name,"Will","Hadley","Matt"))

data %>% ggplot(aes(x = time, 
                    y = r_awesomeness, 
                    fill = Nationality))+
  geom_bar(stat = "identity") +
  grattan_fill_manual(n = 3)+
  guides(col = guide_legend(nrow = 5))+
  facet_grid(.~name) +
  geom_text(data = data.frame(x = 1.29669354378515,
                              y = 7.28929935866944,
                              label = "annotation",
                              name = "Matt"),
            mapping = aes(x = x,
                          y = y,
                          label = label),
            size = 3.86605783866058,
            angle = 0L,
            lineheight = 1L,
            hjust = 0.5,
            vjust = 0.5,
            colour = "black",
            family = "sans",
            fontface = "plain",
            inherit.aes = FALSE,
            show.legend = FALSE) 

This can be fixed by entering in the factor orders manually:

 geom_text(data = data.frame(x = 1.29669354378515,
                              y = 7.28929935866944,
                              label = "annotation",
                              name = factor("Matt", levels = c("Will","Hadley","Matt")

But it would be even better if the levels were pulled in by ggannotate.

MattCowgill commented 3 years ago

Thanks Jonathan. I don't think you need to manually add in the factor levels... if your geom_text() call there, I think you just need name = factor("Matt"), right?

jonathananolan commented 3 years ago

That's correct! Thanks for the pickup.

MattCowgill commented 3 years ago

This should be fixed in dev branch now, but I haven't fully tested it