I am trying to present some of my math homework in R, the problem is I cannot plot the intersecting points with geom_point. Here is my code.
library(ggplot2)
library(tidyverse)
library(rlang)
#function boundaries
x <- -5:5
#left hand function
dat_fun1 <- data.frame(x, y = 2 * sin(x))
fun1 <- function(x) y = 2 * sin(x)
#right hand function
dat_fun2 <- data.frame(x, y = x cos(x))
fun2 <- function(x) y = x cos(x)
#both plotted together.
ggplot()
geom_function(data = dat_fun1, mapping = aes(x,y), fun = fun1, color = "blue")
geom_function(data = dat_fun2, mapping = aes(x,y), fun = fun2, color = "red")
geom_point(x = -1.767, y = -1.962)
Usually, this format works for me when plotting functions. But, it could be a problem with my R-Studio because I was getting errors and had to update rlang.
CodePudding user response:
The issue is that you have to specify a global or a local data
argument, e.g. add data=dat_fun1
to geom_point
or use annotate
to add your point(s) which doesn't require the data
argument:
library(ggplot2)
base <- ggplot()
geom_function(data = dat_fun1, mapping = aes(x,y), fun = fun1, color = "blue")
geom_function(data = dat_fun2, mapping = aes(x,y), fun = fun2, color = "red")
base
geom_point(data = dat_fun1, x = -1.767, y = -1.962, color = "green", size = 10)
base
annotate(geom = "point", x = -1.767, y = -1.962, color = "green", size = 10)