Search code examples
rggplot2facet-wrap

How to make different data format in different facet


In below ggplot2 code , A).How to change sales facet to comma format ,change margin% to percent format ? B).How to make scales='free_y' can work in A affacted ?

plot_data <- data.frame(category=c('a','b','c','a','b','c'),
                        type=c('sales','sales','sales','margin%','margin%','margin%'),
                        value=c(1,2,3,0.1,0.15,0.17),
                        budget=c(1.5,1.8,2.6,0.15,0.2,0.25))


plot_data %>% ggplot(aes(x=category,y= value,fill=category))+
  geom_col()+
  geom_text(vjust=1,size=6,aes(label=value))+
  geom_text(aes(y=max(plot_data$budget)*1.3,label=budget))+
  facet_wrap(.~ type,scales='free_y')+
  theme(strip.text = element_text(size=20))

enter image description here


Solution

    1. Following this post you could set the fomrat for each panel individually by using ggh4x::facettted_pos_scales.

    2. The issue with scales="free_y" is that you use the same value to position the budget label. Hence, you get the same range for the y scale and "free_y" will have no effect. To free the scale compute the position for the budget label per panel.

    library(ggplot2)
    library(ggh4x)
    library(dplyr)
    
    plot_data <- plot_data %>% 
      group_by(type) %>% 
      mutate(max_budget = max(budget)) %>% 
      ungroup()
    
    ggplot(plot_data, aes(x=category,y= value,fill=category))+
      geom_col()+
      geom_text(vjust=1,size=6,
                aes(label = ifelse(type == "sales", scales::comma(value), scales::percent(value)))) +
      geom_text(aes(y=max_budget*1.3, label = budget))+
      facet_wrap(~ type, scales='free_y')+
      facetted_pos_scales(
        y = list(
          type == "sales" ~ scale_y_continuous(labels = scales::comma_format()),
          type == "margin%" ~ scale_y_continuous(labels = scales::percent_format())
        )
      ) +
      theme(strip.text = element_text(size=20))