Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change interpolation / smoothing in ggplot2 geom_raster

Tags:

r

ggplot2

Is it possible to change the level of interpolation (e.g. smoothing, blur) in geom_raster?

library(tidyverse)

mtcars %>%
  group_by(carb, hp = cut(mtcars$hp, 3, labels = c("low", "med", "hi"))) %>%
  summarise(mean_mpg = mean(mpg)) %>%
  ggplot(aes(carb, hp)) +
  geom_raster(aes(fill = mean_mpg), interpolate = FALSE) +
  scale_fill_viridis_c(option = "inferno")

enter image description here

I'd like to have control over how much blurring takes place in the following graph:

mtcars %>%
  group_by(carb, hp = cut(mtcars$hp, 3, labels = c("low", "med", "hi"))) %>%
  summarise(mean_mpg = mean(mpg)) %>%
  ggplot(aes(carb, hp)) +
  geom_raster(aes(fill = mean_mpg), interpolate = TRUE) +
  scale_fill_viridis_c(option = "inferno")

enter image description here

I know how to do this with stat_density_2d -- see this post -- but I would like to pass fill a calculated value and not to calculate a density.

like image 514
JasonAizkalns Avatar asked Jun 15 '18 18:06

JasonAizkalns


1 Answers

AFAIK, you can't manipulate the interpolation of the grid function other than just turning it on or off. Instead, the ggfx package allows you to blur a specific layer with a 'sigma' parameter of your choosing. Example below:

library(tidyverse)
library(ggfx)

mtcars %>%
  group_by(carb, hp = cut(mtcars$hp, 3, labels = c("low", "med", "hi"))) %>%
  summarise(mean_mpg = mean(mpg)) %>%
  ggplot(aes(carb, hp)) +
  with_blur(
    geom_raster(aes(fill = mean_mpg), interpolate = FALSE),
    sigma = 10
  ) +
  scale_fill_viridis_c(option = "inferno")
#> `summarise()` has grouped output by 'carb'. You can override using the `.groups` argument.
#> Warning: Raster pixels are placed at uneven horizontal intervals and will be
#> shifted. Consider using geom_tile() instead.

Created on 2021-08-29 by the reprex package (v2.0.0)

like image 87
teunbrand Avatar answered Nov 12 '22 08:11

teunbrand