Search code examples
rplotlydcast

How to do a plotly graph after a dcast table?


I have a database including day and places, with other relevant information. I am currently using the dcast function in order to count each occurence in a day and place (that in the real database are represented by numbers). Later, I want to do a plotly grafic where day represents my x coordinate, place represents my y coordinate, and z will represent the number of ocurence.

I provide some dummy data here, to simplify:

day<-c(1,2,3)
place<-c("here", "there", "far away")
frequency<-c(1,2,4)

d<-data.frame(day,place,frequency)

z<-dcast(d, day~place, fill=0)

How can I plot this using plotly ?


Solution

  • This really broad, but you could try this:

     place<-c("here", "there", "faraway")
     frequency<-c(1,2,4)
    
     d<-data.frame(day,place,frequency)
    
     z<-dcast(d, day~place, fill=0)
     z$day <- as.factor(z$day)
    plot_ly(data = z, x = ~day, y = ~here, type = "bar", name = 'here') %>%
      add_trace(y = ~there, name = 'there') %>%
      add_trace(y = ~faraway, name = 'faraway') %>%
      layout(yaxis = list(title = 'Count'), barmode = 'group')
    

    enter image description here

    Edit: Following OP comments. You can put it back to long format and then plot.

    d_long <- melt(z, id.vars=c("day"))
    plot_ly(data = d_long, x = ~day, y = ~variable, z = ~value, mode = "markers")