0

I have a data set which contains three columns: Date with no time stamp, TimeTS of the day converted to number of hours since midnight for a specific event associated with the Date. The third column is the Phase which is either or morning, afternoon, evening or night. Phase is derived from TimeTS.

Below is a sample

Date       TimeTS   Phase  
2020-01-29 2.75     Night 
2020-01-29 4.83     Morning
2020-01-29 7        Morning
2020-01-30 10.6     Afternoon

I need to use an interactive charting like plotly to show the following:

  • A scatter chart with Date on the x-axis and Timeon the y with each instance of time marked across each date
  • Translucent bands of the Phase running horizontally on the chart for easy interpretation of time bands and the distribution of markers by Phase

The below code gives me close to my desired result but not exactly.

p <- ggplot(clean.data, aes(x=Date,y=TimeTS)) +
  geom_rect(data=clean.data, mapping = aes(
    xmin=min(Date),
    xmax=max(Date),
    ymin=0,
    ymax=24,
    fill=Phase), alpha=0.1) +
  # scale_fill_manual(values=c("Morning" = "red", "Afternoon" = "blue", "Evening" = "green", "Night" = "black")) +
  geom_point()
p <- ggplotly(p)
p

This gets me only one of the Phase bands on the chart and not others. Plus i think its running vertically and not horizontally.

Any ideas are appreciated.

Drj
  • 1,176
  • 1
  • 11
  • 26
  • You need to create a separate data.frame for the rectangles and define their start and end points. See [https://stackoverflow.com/questions/32543176/highlight-areas-within-certain-x-range-in-ggplot2](https://stackoverflow.com/questions/32543176/highlight-areas-within-certain-x-range-in-ggplot2) for a (partial) solution for your problem. – user12728748 Jan 30 '20 at 05:42
  • @user12728748, thx mate. I will try this tomorrow and let you know, how it goes. – Drj Jan 30 '20 at 09:45

1 Answers1

0

Thanks to @user12728748, I was able to get this done. Code changes below:

df.phase <- data.frame(start = c(0,4,10,16,22), end = c(4,10,16,22,24), phase = c("Night", "Morning", "Afternoon", "Evening", "Night"))

p <- ggplot(clean.data, aes(x=Date,y=TimeTS)) +
  geom_rect(data=df.phase, inherit.aes = FALSE, aes(
    xmin= min(clean.data$Date),
    xmax= max(clean.data$Date),
    ymin=start,
    ymax=end,
    fill=phase), alpha=0.5) +
  scale_fill_manual(values=c("Morning" = "orange", "Afternoon" = "blue", "Evening" = "pink", "Night" = "black")) +
  geom_point()
p <- ggplotly(p)
p

The code will generate the following output Horizontal Rectangular swimlanes on a scatter plot

Drj
  • 1,176
  • 1
  • 11
  • 26