rggplot2labelfacet-gridr-glue

pasting with glue::glue changes order of values in facet


Based on this response How to add greek letters to Facet_Grid strip labels? , I successfully create a ggplot with greek letters in the facet label.

However the glue library changes the order of my label FacetX, how can I deal with it?

This is an example of my problem, I want 500 - 1000 - 5000 and not 1000 - 500 - 5000.

library(ggplot2)
library(glue)

df <- expand.grid(1:3, 1:3)
df$FacetX <- c(500,1000,5000)[df$Var1]
df$FacetY <- c(0.1, 1, 10)[df$Var2]

ggplot(df, aes(Var1, Var2)) +
  geom_point() +
  facet_grid(glue('sigma[E]^2*" = {FacetY}"') ~ glue("'p = {FacetX}'"), 
             labeller = label_parsed)

Best,


Solution

  • This has nothing to do with the Greek letters, but that the use of glue::glue messes up your levels. (It assigns the level order based on the increasing value, here 1<5)

    You could use forcats::fct_inorder to prevent this

    library(ggplot2)
    library(glue)
    
    df <- expand.grid(1:3, 1:3)
    df$FacetX <- c(500,1000,5000)[df$Var1]
    df$FacetY <- c(0.1, 1, 10)[df$Var2]
    
    ggplot(df, aes(Var1, Var2)) +
      geom_point() +
      facet_grid(glue('sigma[E]^2*" = {FacetY}"') ~ forcats::fct_inorder(glue("'p = {FacetX}'")), 
                 labeller = label_parsed)
    

    Created on 2022-04-06 by the reprex package (v2.0.1)