0

I have the following script from the DTW package and I'm looking for the equivalent code of this example in ggplot framework:

library(dtw)
idx<-seq(0,6.28,len=100);
query<-sin(idx)+runif(100)/10;
reference<-cos(idx)

plot(reference); 
lines(query,col="blue");
alignment<-dtw(query,reference);


#how can I add line on the ggplot plot ?  with geom_segment ?
plot(reference)
lines(query[alignment$index1]~alignment$index2,col="blue")

and how to interpret the symbol tilde in this use case in the lines function ?

1
  • 1
    Can you add the result to your question? Commented Oct 23, 2018 at 11:00

1 Answer 1

1

Take a look at it, hope this will help,

df <- tibble(
  row_num = 1:100,
  idx = seq(0, 6.28, len = 100),
  query = sin(idx) + runif(100)/10,
  reference = cos(idx)
)
alignment <- with(df, dtw(query, reference))
seg_df <- tibble(
  x = alignment$index2,
  y = df$query[alignment$index1]
)
ggplot(df, aes(row_num, reference)) +
  geom_point(shape = 21) +
  geom_path(data = seg_df, aes(x = x, y = y, col = "blue"))

EDIT: for different query and reference

You can always create different data frame for query and reference as,

library(tibble)
library(ggplot2)
library(dtw)

query <- tibble(
  row_num = 1:100,
  idx = seq(0, 6.28, len = 100),
  query = sin(idx) + runif(100)/10
)
ref <- tibble(
  row_num = 1:50,
  idx = seq(0, 6.28, len = 50),
  reference = cos(idx)
)
alignment <- dtw(query$query, ref$reference)
seg_df <- tibble(
  x = alignment$index2,
  y = query$query[alignment$index1]
)
plt <- ggplot(ref, aes(row_num, reference)) +
  geom_point(shape = 21) +
  geom_path(data = seg_df, aes(x = x, y = y), col = "blue")
plot(plt)

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, it works fine for the equal length sequence (query and reference have here length of 100) but but what about the seqences that are not the same length ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.