rggplot2economics

How to fill out an area of a graph with ggplot2


I'm working on a graph using R for one of my economics classes, and I want to fill out an area of the graph to represent the deadweight loss.

Below is the code I've used to make the graph:

rm(list = ls())
library(tidyverse)

housing_market <- ggplot(data.frame(x = c(0,3000)), aes(x = x)) +
  stat_function(fun = function(x){2.5-0.001*x}, color = "green", lwd = 1) +
  stat_function(fun = function(x){1}, color = "purple", lwd = 1) +
  stat_function(fun = function(x){0.70}, color = "blue", lwd = 1) +
  ylim(0,2.5) +
  annotate(geom = "text", label = "Inverse Demand = 2.5 - 0.001Q", x = 1250, y = 2, size = 4) +
  annotate(geom = "text", label = "MSC = 1", x = 500, y = 1.2, size = 4) +
  annotate(geom = "text", label = "MPC = 0.70", x = 500, y = 0.5, size = 4) +
  ggtitle("Housing Market") +
  labs(x = bquote(Q(ft.^2)), y = bquote(P("$"/ft.^2))) +
  geom_point(aes(1500,1), color = "black", size = 4) +
  geom_point(aes(1800,1), color = "black", size = 4) +
  geom_point(aes(1800,0.7), color = "black", size = 4)
housing_market

enter image description here

The deadweight loss is the triangle created by the points (1500,1), (1800,1), and (1800,0.7). I have tried using geom_rect, but I can't figure out a way to get it to fill the triangle only. Any help would be appreciated.


Solution

  • Obviously, a triangle is a specific polygon (rather than a rectangle) ;)

    You can define a dataframe with the coordinates. I do this inside the geom call. However, from a coding perspective you may want to do this outside. As a side note: you could use this external dataframe to define the points in one geom_point() call as well.

    housing_market + 
       geom_polygon(data = data.frame(  x = c(1500, 1800, 1800)
                                      , y = c(1,1,0.7))
                   , aes(x = x, y = y)   # set aesthetic mapping for polygon
                   , fill = "orange"     # put any other parameter
       )
    

    Adding the geom_polygon layer at the end will "overplot" your points. Thus, you may want to move the geom_polygon() layer upwards in constructing your plot or put the geom_point() call(s) after the polygon call.

    enter image description here