Home

Awesome

<!-- README.md is generated from README.Rmd. Please edit that file -->

reconPlots: Create economics-style plots with R

Author: Andrew Heiss<br/> License: MIT

Build Status Coverage Status

Intro paragraph here.

Installation

This package is not on CRAN yet.

You can install the development version from Github with devtools:

library(devtools)
install_github("andrewheiss/reconPlots")

Plotting intersections of curves

The curve_intersect() function calculates the intersection of two curves, defined as either as data frames with x and y columns, or as single-variable functions

Straight lines with empirical data

library(reconPlots)

line1 <- data.frame(x = c(1, 9), y = c(1, 9))
line1
#>   x y
#> 1 1 1
#> 2 9 9

line2 <- data.frame(x = c(9, 1), y = c(1, 9))
line2
#>   x y
#> 1 9 1
#> 2 1 9

line_intersection <- curve_intersect(line1, line2)
line_intersection
#> $x
#> [1] 5
#> 
#> $y
#> [1] 5
library(ggplot2)

ggplot(mapping = aes(x = x, y = y)) +
  geom_line(data = line1, color = "red", size = 1) +
  geom_line(data = line2, color = "blue", size = 1) +
  geom_vline(xintercept = line_intersection$x, linetype = "dotted") +
  geom_hline(yintercept = line_intersection$y, linetype = "dotted") +
  theme_classic()

Curved Bézier lines with empirical data

This also works with curved lines created with Hmisc:bezier():

curve1 <- data.frame(Hmisc::bezier(c(1, 8, 9), c(1, 5, 9)))
curve2 <- data.frame(Hmisc::bezier(c(1, 3, 9), c(9, 3, 1)))

curve_intersection <- curve_intersect(curve1, curve2)
curve_intersection
#> $x
#> [1] 4.654098
#> 
#> $y
#> [1] 3.395566

ggplot(mapping = aes(x = x, y = y)) +
  geom_line(data = curve1, color = "red", size = 1) +
  geom_line(data = curve2, color = "blue", size = 1) +
  geom_vline(xintercept = curve_intersection$x, linetype = "dotted") +
  geom_hline(yintercept = curve_intersection$y, linetype = "dotted") +
  theme_classic()

Curved lines defined with functions

Instead of defining curves with empirical data (i.e. data frames of x and y values), you can also work with actual functions. The only change is that you need to set empirical = FALSE and define a range of values of x to look within for the intersection.

curve1 <- function(q) (q - 10)^2
curve2 <- function(q) q^2 + 2*q + 8

x_range <- 0:5

curve_intersection <- curve_intersect(curve1, curve2, empirical = FALSE, 
                                      domain = c(min(x_range), max(x_range)))

ggplot() +
  stat_function(aes(x_range), color = "blue", size = 1, fun = curve1) +
  stat_function(aes(x_range), color = "red", size = 1, fun = curve2) +
  geom_vline(xintercept = curve_intersection$x, linetype = "dotted") +
  geom_hline(yintercept = curve_intersection$y, linetype = "dotted") +
  theme_classic()