Zooming when using facet_wrap and geom_tile together

When using the geom_tile and facet_wrap together in ggplot2, how to set different aesthetic fill limits, like the scales option, which can be set free free/free_y/free_x in facet_wrap ?

Below is an example to show the problem. For different types in data.frame df the z range can be so different. If we use the same limits of fill aesthetics, some panoramas, which part of z is of very little importance, it would be difficult to see the details.

 pp <- function (n,r=4) { x <- seq(-r*pi, r*pi, len=n) df <- expand.grid(x=x, y=x) df$r <- sqrt(df$x^2 + df$y^2) df$z <- cos(df$r^2)*exp(-df$r/6) df } tmp <- pp(20) tmp$type <- rep(1:4,each=nrow(tmp)/4) tmp$z <- tmp$z*(10^(tmp$type)) ggplot(tmp,aes(x,y))+geom_tile(aes(fill=z))+facet_wrap(~type,scales="free") 
+6
source share
2 answers

One way to solve this problem is to standardize the variable being populated so that the scale is the same for all facets.

 library(dplyr) tmp1 <- group_by(tmp,type) # grouping the data by type tmp2 <- mutate(tmp1, z1 = (z-mean(z))/sd(z)) #groupwise standardization ggplot(tmp2,aes(x,y))+geom_tile(aes(fill=z1))+facet_wrap(~type,scales="free") 

I want something like fill=std(z) , so I don't need to standardize manually.

+2
source

I know this is an old problem, but I recently had the same problem, and I came up with this solution that I wanted to share. The trick is to collect the datasets needed for individual geom_tile() plots in a nested frame using nest() from tidyr , and then use the map2() function from the purrr package and the wrapper function to create separate plots:

 library(tidyverse) pp <- function (n,r=4) { x <- seq(-r*pi, r*pi, len=n) df <- expand.grid(x=x, y=x) df$r <- sqrt(df$x^2 + df$y^2) df$z <- cos(df$r^2)*exp(-df$r/6) df } tmp <- pp(20) tmp$type <- rep(1:4,each=nrow(tmp)/4) tmp$z <- tmp$z*(10^(tmp$type)) plot_func <- function(df, name) { ggplot(data = df, aes(x = x, y = y, fill = z)) + geom_tile() + scale_fill_continuous(name = name) } nested_tmp <- tmp %>% group_by(type) %>% nest() %>% mutate(plots = map2(data, type, plot_func)) gridExtra::grid.arrange(grobs = nested_tmp$plots) 

Graphic chart of cards with different color scale

The nested framework contains two columns of the list that contain data sets and graphs:

 > nested_tmp # A tibble: 4 × 3 type data plots <int> <list> <list> 1 1 <tibble [100 × 4]> <S3: gg> 2 2 <tibble [100 × 4]> <S3: gg> 3 3 <tibble [100 × 4]> <S3: gg> 4 4 <tibble [100 × 4]> <S3: gg> 

It is very easy to change plot_func() to fine tune the graphs.

+2
source

Source: https://habr.com/ru/post/946880/


All Articles