Home > OS >  reorder_within reordering facets in nestedfacet ggplot
reorder_within reordering facets in nestedfacet ggplot

Time:06-19

Help with reordering facets.

I am using reorder_within and scale_x_reordered from Julia Silge's blog (enter image description here

Is there anyway to remove the suffix in the facet labels (e.g.___Lvl1)? I can change the separator to be a space and this looks a little better but I have failed at finding a way to modify the facet labels.

Any help would be greatly appreciated.

CodePudding user response:

You were very close with your attempt of gsub. What you needed was a labeller function as

labeller = function(x) {x$Company <- sub('_ Lvl \\d ', '', x$Company);x}

The x here is a dataframe with two columns, Level and Company. We need to change the value in only Company column and return the dataframe back.

x

#   Level           Company
#1  Lvl 1 Company 5___Lvl 1
#2  Lvl 1 Company 3___Lvl 1
#3  Lvl 1 Company 2___Lvl 1
#4  Lvl 1 Company 4___Lvl 1
#5  Lvl 1 Company 1___Lvl 1
#6  Lvl 2 Company 4___Lvl 2
#7  Lvl 2 Company 5___Lvl 2
#8  Lvl 2 Company 2___Lvl 2
#9  Lvl 2 Company 3___Lvl 2
#10 Lvl 2 Company 1___Lvl 2

Here's the complete code -

data %>%
  mutate(
    Level = as.factor(Level),
    YEAR = as.factor(YEAR),
    Company = reorder_within(Company, -Rank, Level)) %>%
  
  #plot
  ggplot(aes(x = YEAR, y = Result, fill = Colour_flag))  
  facet_nested(. ~ Level   Company, 
               scales = "free_x", 
               labeller = function(x) {
                 x$Company <- sub('_ Lvl \\d ', '', x$Company)
                 x
                 })   
  geom_bar(stat = "identity")  
  geom_text(aes(y = Result, label = round(Result, 0)), 
            position = position_dodge(0.9), 
            hjust = 1.5, vjust = 0.5, angle = 90, size = 3.5)  
  
  scale_fill_manual(values = Col)  
  theme_minimal()  
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.x = element_text(angle = 90, hjust = 0, vjust = 0.5, size = 10),
    strip.text.x = element_text(size = 11),
    axis.text.y = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    legend.position = 'none',
    panel.spacing = unit(c(0.5,0.5,0.5,0.5,30,
                           0.5,0.5,0.5,0.5), "pt")
  )

enter image description here

  • Related