2017-04-21 144 views
0

我在學習R和ggplot2。我可以繪製單個可變函數(使用geom_path)和密度圖(使用geom_raster)。但是我找不到一種方法將它們結合起來,形成如下圖所示的圖形。這甚至可能與ggplot2?如何用ggplot2在兩條線之間繪製密度圖?

A density map restricted to the region between two lines.

+1

你能分享你有什麼碼? – atclaus

回答

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()