如何在ggplot2 geom_raster中更改插值/平滑

Jas*_*lns 6 r ggplot2

是否可以更改中的插值级别(例如,平滑,模糊)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")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我想控制下图中发生的模糊程度:

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")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我知道该怎么做stat_density_2d- 请参阅这篇文章 -但我想通过填充计算出的值,而不是计算密度。

teu*_*and 2

AFAIK,除了打开或关闭网格功能之外,您无法操纵它的插值。相反,ggfx 包允许您使用您选择的“sigma”参数模糊特定图层。下面的例子:

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.
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v2.0.0)创建于 2021-08-29