1

In ggplot/facet_wrap(), how to marke axis Y have different format ? Thanks!

 library(tidyverse)
    test_data <- diamonds
    plot_data <- test_data %>% mutate(x_to_price=x/price,
                                      price=price*1000) %>% head(12) %>% 
      mutate(mseq=1:NROW(.)) %>% 
      select(price,x_to_price,mseq) %>% gather(key='type',value='amount',- mseq)
    
    
    plot_data %>% ggplot(aes(x=mseq,y=amount))+geom_line()+geom_point()+
      facet_wrap(.~type,scales='free_y')

enter image description here

anderwyang
  • 1,801
  • 4
  • 18
  • percent: https://stackoverflow.com/questions/27433798/how-can-i-change-the-y-axis-figures-into-percentages-in-a-barplot – Adam Quek Jun 01 '22 at 05:57
  • comma: https://stackoverflow.com/questions/37713351/formatting-ggplot2-axis-labels-with-commas-and-k-mm-if-i-already-have-a-y-sc – Adam Quek Jun 01 '22 at 05:58

1 Answers1

3

One option would be the ggh4x package which via facetted_pos_scales allows to set the scales individually for each facet:

library(ggplot2)
library(ggh4x)
 
ggplot(plot_data, aes(x=mseq,y=amount))+geom_line()+geom_point()+
  facet_wrap(.~type,scales='free_y') +
  facetted_pos_scales(
    y = list(
      type == "price" ~ scale_y_continuous(labels = scales::comma_format()),
      type == "x_to_price" ~ scale_y_continuous(labels = scales::percent_format())
    )
  )

stefan
  • 90,330
  • 6
  • 25
  • 51