1

I want to show graphically how the summation of two different sin curves looks like. So, I am trying to make a single graph that shows two different sin function and their sum. So, three curves on one graph.

How can I do it with ggplot layers?

I am defing two sin functions (y and z)

x <- seq(0, 16*pi, 0.01)
y <- 2*sin(3*(x-1))
z <- sin(x)

summing up the two curves:

t <- y + z

I can see the three separately with:

plot(x,y,type="l")
plot(x,z,type="l")
plot(x,t,type="l")

But how can I plot the three functions?

I tried this but it does not work

ggplot(x,
       qplot(y,x,geom="path", xlab="time", ylab="Sine wave") +
       qplot(z,x,geom="path", xlab="time", ylab="Sine wave"))
Axeman
  • 32,068
  • 8
  • 81
  • 94
Ron
  • 65
  • 1
  • 6

1 Answers1

2

Store everything in a data.frame, reshape from wide to long, and plot:

library(tidyverse)
data.frame(x = x, y = y, z = z, t = y + z) %>%
    pivot_longer(-x) %>%
    ggplot(aes(x, value, colour = name)) +
    geom_line()

enter image description here


Sample data

x <- seq(0, 16*pi, 0.01)
y <- 2*sin(3*(x-1))
z <- sin(x)
Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • Thanks, but I get an error: could not find function "pivot_longer". I have already tried with tidyr, dplyr, tidyverse, data.table and it does work. How to make it work? THANKS – Ron Feb 12 '20 at 08:53
  • @RonSlavaGrodko You need to update `tidyr`; `pivot_longer` was introduced in version `1.0.0` (the current CRAN version is `1.0.2`) and replaced `gather`. The old version would be `gather(name, value, -x)`. – Maurits Evers Feb 12 '20 at 11:49