r - Plot Data by 1 second intervals efficently -
so i've done (inefficiently), future reference i'd know if there's better way.
what i'm doing plotting number of packets, , data sent every second in trace. code is:
trace$sec = cut(trace$v1, breaks = seq(0, 1800, = 1), labels = 1:1800) packet_count_vec = numeric() data_trans_vec = numeric() (i in 0:1800 ) { print(i) bin = which(trace$sec == i) packet_count = 0 data_trans = 0 (j in bin) { packet_count = packet_count + 1 data_trans = data_trans + trace[j,]$v6 } packet_count_vec = c(packet_count_vec, packet_count) data_trans_vec = c(data_trans_vec, data_trans) } par(mfrow=c(2, 1)) plot(packet_count_vec, type = "l", xlab = "time (s)", ylab = "packets") title("time series of total packets") plot(data_trans_vec, type = "l", xlab = "time (s)", ylab = "bits") title("time series of data transferred")
what use cut
add bins second intervals data, each bin count number in bin (number of packets), , each packet add data (total data sent second).
the trace can found here, important columns are:
- v1 - time after start packet sent.
- v6 - amount of data sent.
my current solution reasonably slow (i have 1800 seconds), , i'm wondering how i'd more efficiently next time.
assuming grok'd file correctly, think you're trying achieve. use read_delim
readr
fast file reading, use dplyr
idioms transform , summarize data. use ggplot
vs base plotting , tidyr
transform data again before plotting. plotting simplified due use of facets in ggplot
.
library(dplyr) library(readr) library(stringr) library(tidyr) library(ggplot2) library(scales) trace <- read_delim("trace.txt", delim=" ", col_names=false) trace %>% mutate(second=as.numeric(str_replace(x1, "\\..*$", ""))) %>% # care second group_by(second) %>% # group second summarise(`total packets`=n(), # packet count `data transferred (bits)`=sum(x6)) -> trace # data count head(trace) ## source: local data frame [6 x 3] ## ## second total packets data transferred (bits) ## 1 0 151 5497 ## 2 1 203 11146 ## 3 2 170 13986 ## 4 3 163 10541 ## 5 4 152 6781 ## 6 5 147 9087 gg <- ggplot(gather(trace, measure, value, -second)) gg <- gg + geom_line(aes(x=second, y=value, color=measure)) gg <- gg + scale_y_continuous(label=comma) gg <- gg + facet_wrap(~measure, ncol=1, scales="free_y") gg <- gg + labs(x="time (s)", y=null) gg <- gg + theme_bw() gg <- gg + theme(legend.position="none") gg
Comments
Post a Comment