r - showing different units in each free_y of facet_grid -
i have plotted 2 facets 1 on top of other 2 different ys (a percentage , cost) , same x (years). took of ideas this post , variations of same. i'd show labels of y axis percentages rate , £ costs, have been unable change each y label format independently.
below reproducible example using facet_grid (i managed create similar thing facet_wrap stuck same problem).
i considered using grid.arrange() gridextra package, seemed bring other issues legend.
library(plyr) library(tidyr) library(dplyr) library(ggplot2) library(scales) set.seed(12345) my_labels <- function(variable, value){ names_li <- list("percentage", "cost in pounds") return(names_li[value]) } df <- data.frame( rate = runif(10, 0, 1), cost = rnorm(10, 100, 40), years = seq(from = 2001, = 2010) ) df %>% gather(type_of_var, value, rate:cost) -> df2 df2 %>% ggplot(aes(x = years, y = value, ymin = 0, ymax = .1)) + facet_grid(type_of_var ~ ., scales = 'free_y', labeller = my_labels) + labs(x = "year", y = "") + geom_point(subset = . (type_of_var == "rate")) + geom_line(subset = . (type_of_var == "rate"), colour = "grey") + ## following 2 lines don't work # scale_y_continuous(subset = . (type_of_var == "rate"), # labels = percent) + geom_bar(subset = . (type_of_var == "cost"), stat = "identity") + theme_bw() + theme(strip.text.y = element_text(size = 15, colour = "black"), plot.title = element_text(lineheight = 0.8, face = "bold")) + scale_x_continuous(breaks = seq(2001, 2010, 1)) + labs(title = "free_y y axis labels")
thanks
as fragile workaround, use
label_fun <- function (x) { if(max(x, na.rm=true) > 1) dollar(x) else percent(x) }
(assuming deal big money , small percentages)
Comments
Post a Comment