ggplot中具有段功能的行

时间:2018-10-23 10:07:57

标签: r ggplot2

我从DTW包中获得了以下脚本,并且正在ggplot框架中寻找该示例的等效代码:

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

以及如何在line函数中的这种用例中解释符号代字号?

1 个答案:

答案 0 :(得分:1)

看看它,希望对您有所帮助,

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

编辑:用于不同的查询和参考

您始终可以创建其他数据框以供查询和引用,

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