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"))
0

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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
@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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.