我正在学习R和ggplot2。我可以绘制单变量函数(使用geom_path
)和密度映射(使用geom_raster
)。但是,我无法找到一种方法将它们组合起来以产生如下图所示的图形。这对ggplot2来说是否可能?
答案 0 :(得分:4)
当然。也许:
library(tidyverse)
expand.grid(x = seq(0, 1, .001), # make a grid of x and y values
y = seq(0, 1, .001)) %>%
filter(y < x, y > x ^ 2) %>% # filter to rows between curves
ggplot(aes(x, y, fill = x + y)) +
geom_raster() +
stat_function(fun = identity, color = 'red') + # add y = x
stat_function(fun = function(x){x^2}, color = 'red', linetype = 'dashed') +
scale_fill_gradient(low = 'black', high = 'white') +
coord_equal()