Search code examples
rfacet-grid

Combining two types of labellers in facet_grid


I have the follow facet_grid + ggplot2 code:

    ggplot(output,aes(x=as.factor(X_and_Color),y=Y_values,fill=as.factor(X_and_Color)))+
  geom_bar(stat="identity",position='dodge')+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+
  theme(text = element_text(size=18),legend.position = "bottom")+
  facet_grid(rows=vars(facet_rows),cols=vars(facet_columns),scales="free",labeller = label_bquote(cols=N[t0]==.(facet_columns)))

When the resulting plots look fine but the labels for the rows need to be text wrapped.

I looked at using label_wrap_gen() but have been unable to make it fit into the label_bquote() correctly for just the rows.

Edit 1:

output<-structure(list(X_and_Color = c(100, 1000, 5000, 100, 1000, 5000, 
100, 1000, 5000, 100, 1000), Y_values = c(0.867583920521508, 
0.124953765675481, 344.093547640026, 0.0134418163074479, 0.0890165925565165, 
155.778207495509, 86.4571212256961, 13.2165726083926, 0.395814237374253, 
33.928067237654, 175.145881111351), facet_rows = structure(c(2L, 
2L, 1L, 7L, 7L, 4L, 5L, 5L, 3L, 6L, 6L), .Label = c("Effective Number of Haplotypes", 
"Gene Diversity", "Nucleotide Diversity", "Number of Haplotypes", 
"Number of Heterozygotes", "Number of Polymorphic Sites", "Site by Site Heterozygosity"
), class = "factor"), Not_Needed = c(1e-04, 1e-04, 1e-04, 1e-04, 
1e-04, 1e-04, 1e-04, 1e-04, 1e-04, 1e-04, 1e-04), facet_columns = c(2, 
100, 2, 2, 100, 2, 2, 100, 2, 2, 100)), .Names = c("X_and_Color", 
"Y_values", "facet_rows", "Not_Needed", "facet_columns"), row.names = c(1L, 
7L, 13L, 19L, 25L, 31L, 37L, 43L, 49L, 55L, 61L), class = "data.frame")

Using this data and the above code I get this for the row labels:enter image description here


Solution

  • We can use str_wrap function from stringr for rows of facet_grid separately. Also adjust your size parameter based on your preference/screen size so the labels are visible.

    library(ggplot2)
    library(stringr)
    
    ggplot(output,aes(x=as.factor(X_and_Color),y=Y_values,fill=as.factor(X_and_Color)))+
       geom_bar(stat="identity",position='dodge')+
       theme(axis.title.x=element_blank(),
             axis.text.x=element_blank(),
             axis.ticks.x=element_blank())+
       theme(text = element_text(size=10),legend.position = "bottom")+
       facet_grid(rows= vars(str_wrap(facet_rows, 2)),
                  cols=vars(facet_columns),scales="free", 
                  labeller = label_bquote(cols=N[t0]==.(facet_columns)))
    

    enter image description here