How can I recreate the following, such that I do not need to duplicate the geom_segment line, but rather, I produce the multiple geom_segment calls programatically (and hence, can use many different dataframes, which may vary in the number of rows)?
library(ggplot2)
library(tibble)
df <- tibble::tibble(freqs = c(261.6256, 293.6648, 329.6276, 293.6648, 329.6276, 349.2282, 391.9954, 349.2282, 329.6276,
293.6648, 329.6276, 293.6648, 329.6276, 349.2282, 391.9954),
durs = c(0.96, 1.92, 3.84, 4.80, 5.76, 7.68, 8.64, 9.60, 10.56, 11.52, 12.00, 12.48, 12.96, 13.44, 15.36))
df2 <- df
ggplot2::ggplot(df, ggplot2::aes(x = durs, y = freqs))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[1],xend=df2$durs[2],y=df2$freqs[1],yend=df2$freqs[1]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[2],xend=df2$durs[3],y=df2$freqs[2],yend=df2$freqs[2]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[3],xend=df2$durs[4],y=df2$freqs[3],yend=df2$freqs[3]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[4],xend=df2$durs[5],y=df2$freqs[4],yend=df2$freqs[4]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[5],xend=df2$durs[6],y=df2$freqs[5],yend=df2$freqs[5]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[6],xend=df2$durs[7],y=df2$freqs[6],yend=df2$freqs[6]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[7],xend=df2$durs[8],y=df2$freqs[7],yend=df2$freqs[7]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[8],xend=df2$durs[9],y=df2$freqs[8],yend=df2$freqs[8]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[9],xend=df2$durs[10],y=df2$freqs[9],yend=df2$freqs[9]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[10],xend=df2$durs[11],y=df2$freqs[10],yend=df2$freqs[10]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[11],xend=df2$durs[12],y=df2$freqs[11],yend=df2$freqs[11]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[12],xend=df2$durs[13],y=df2$freqs[12],yend=df2$freqs[12]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[13],xend=df2$durs[14],y=df2$freqs[13],yend=df2$freqs[13]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[14],xend=df2$durs[15],y=df2$freqs[14],yend=df2$freqs[14]))
ggplot2::geom_segment(ggplot2::aes(x=df2$durs[15],xend=df2$durs[16],y=df2$freqs[15],yend=df2$freqs[15]))
CodePudding user response:
ggplot(df, aes(x = durs, xend = dplyr::lead(durs), y = freqs, yend = freqs))
geom_segment()
or, if you want to avoid needing to use dplyr::lead
for some reason, here's a base ggplot2 solution. I create a new vector in df2
with the durs
values shifted to appear one row earlier.
df2 <- df
df2$durs_next = c(df2$durs[seq_len(length(df2$durs)-1) 1], NA)
ggplot(df2, aes(x = durs, xend = durs_next, y = freqs, yend = freqs))
geom_segment()