jerome
jerome

Reputation: 153

How to plot a density map between two lines with ggplot2?

I'm learning R and ggplot2. I can plot single variable functions (using geom_path) and density maps (using geom_raster). However I can't find a way to combine them to produce a figure like the one below. Is that even possible with ggplot2?

A density map restricted to the region between two lines.

Upvotes: 0

Views: 246

Answers (1)

alistaire
alistaire

Reputation: 43334

Of course. Maybe:

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

Upvotes: 4

Related Questions