Alec
Alec

Reputation: 21

R - visualising data over time

I'm trying to plot a dataset over time (timeframe of ms/s). I need to show the order of events, the type of event and the duration of each event + the time between events. The dataset consists of a start time, end time and category.

I got close with this code someone used to answer a similar question back in '11 but found that I couldn't get it to colour the events according to the category, and I don't understand what the code is doing well enough to fix the issue.

zucchini <- function(st, en, mingap=1)
{
  i <- order(st, en-st);
  st <- st[i];
  en <- en[i];
  last <- r <- 1
  while( sum( ok <- (st > (en[last] + mingap)) ) > 0 )
 {
   last <- which(ok)[1];
   r <- append(r, last);
  }
  if( length(r) == length(st) )
    return( list(c = list(st[r], en[r]), n = 1 ));

  ne <- zucchini( st[-r], en[-r]);
  return(list( c = c(list(st[r], en[r]), ne$c), n = ne$n+1));
}

{
 zu <- zucchini(st, en, mingap = 1);
 plot.new();
 plot.window( xlim=c(min(st), max(en)), ylim = c(0, zu$n+1));
 box(); axis(1);
 for(i in seq(1, 2*zu$n, 2))
 {
   x1 <- zu$c[[i]];
x2 <- zu$c[[i+1]];
for(j in 1:length(x1))
  rect( x1[j], (i+1)/2,  x2[j], (i+1)/2+0.5,col=data$Type, border="black",
 );
  legend('bottomright', legend = levels(data$Type), col = 1:10, cex = 0.8, pch = 1)}
}

 st <- data$Time
 en <- data$End
 coliflore(st,en)

current code outputs this As best as I can tell it is assigning all boxes the same colour, that of the category of the first data point.

Does anyone know either: how to get this code to assign colours to the boxes based on a category, or how to accomplish this kind of plotting another way?

Upvotes: 2

Views: 99

Answers (1)

Daniel Bachen
Daniel Bachen

Reputation: 119

Its a little hard to for me to see whats going on without a toy dataset for your example. For maximum control over coloring in plots I like to add a color column to the dataframe or create a vector to store color values for use in plotting instead of using the factor levels to generate colors (eg data$Type). For instance if I want factors 1:3 to be red, green, and blue:

# create data frame with X,Y coordinates and 3 factor levels
toy_data<- data.frame (X= 1:9, Y=9:1, Factor = rep(1:3, times=3))
# create a vector of colors to use for plotting
# color function
colFxn<-function(val){
    cw_df<-data.frame(value=1:3, color = c("red", "green", "blue"))
    return(cw_df[cw_df$value %in% val,]$color)
}
col_vec<-sapply (toy_data$Factor, colFxn)
#plot
plot(toy_data$X, toy_data$Y, col=col_vec)

I prefer this option because of the control I have over my colors. This can also be expanded to transparent colors by changing the alpha value using the RGB function, or through using a color pallet available through many packages.

Upvotes: 2

Related Questions