Black Lives Matter. Please consider donating to Black Girls Code today.
Learn how to use COVID-19 data in open source Dash apps. Register for the Sept 23rd webinar with IQT!

How to plot data with missing date/data in the second y-axis - R

I’m trying to plot a vertical bar plot with two y axis.

This works fine if data in both y-axis are of the same count( i.e both are plotting data for last 7 days), but the viz breaks if both the y axis do not have same number of data(i.e one has data for 14 days and other just 12 days with missing date and data for two days).

Is there a way I can make this work in plotly ?

library(plotly)

childUsersDf <- structure(list(time = structure(c(17392, 17395, 17396, 17397, 17398), class = "Date"), 
                     numActiveUsers = c(1, 199, 267, 277,292)), 
                             .Names = c("time", "numActiveUsers"), row.names = c(NA,-5L), class = "data.frame")
  

allUsersDf <- structure(list(time = structure(c(17392, 17393, 17394, 17395,17396, 17397), class = "Date"), 
                   numActiveUsers = c(9116, 9312, 976, 9460, 9181, 9305)), 
                           .Names = c("time", "numActiveUsers"), row.names = c(NA, 6L), class = "data.frame")

# Plots
p <- plot_ly(
  allUsersDf,
  x = ~ allUsersDf$time,
  y = ~ allUsersDf$numActiveUsers, 
  type = 'bar',
  name = "# All users(Except child users)"
) %>%
  add_trace(
    y = ~ childUsersDf$numActiveUsers,
    name = "# Child users "
  ) %>%
  layout(
    title = 'Active users & child users per day',
    titlefont = list(
      size=22,
      family = 'Arail'
    ), 
    margin = 50, 
    xaxis = list(
      type = "category"
    ),
    yaxis = list(
      title = 'Number of active users/child users'
    ),
    barmode = 'stack',
    legend = list(
      x = 0.8,
      y = 1.3
    )        
  )
p <- layout(p, xaxis = list(type = "category"))

I searched online and in couple of places the answer was to use:

layout(p, xaxis = list(type = "category"))

But, it doesn’t work. Any ideas or workaround ?

Thanks

Hey @anishjoni

Based on your code it looks like you are trying to do 2 traces on the same y axis (not multiple axes). If this is correct, try something like below, which will give you https://plot.ly/~bdun9/2132/

p <- plot_ly(
  type = 'bar'
) %>%
  add_trace(
    x = ~ allUsersDf$time,
    y = ~ allUsersDf$numActiveUsers,
    name = "# All users(Except child users)"
  ) %>%
  add_trace(
    x = ~ childUsersDf$time,
    y = ~ childUsersDf$numActiveUsers,
    name = "# Child users "
  ) %>%
  layout(
    title = 'Active users & child users per day',
    titlefont = list(
      size=22,
      family = 'Arail'
    ), 
    margin = 50, 
    xaxis = list(
      type = "category"
    ),
    yaxis = list(
      title = 'Number of active users/child users'
    ),
    barmode = 'stack'
  )