Search code examples
rchartsplotlyline

How could I plot a continuous line in bar- line Plotly object in R?


Here is my code that I am using:

library(dplyr)
library(plotly)

DF <- data.frame(
  Month = lubridate::as_date(c("2019-Dec-01", "2019-Dec-01","2020-Jan-01","2020-Jan-01","2020-Jan-01", "2020-Feb-01", "2020-Feb-01")),
  #Week = c(4L, 5L, 5L, 1L, 1L, 1L, 2L, 1L),
  Cat = c("A", "C", "A", "B", "C", "A", "C"),
  n = c(38L, 10L, 19L, 20L, 12L, 14L, 20L)
)

DF1 <- data.frame(
  Month = lubridate::as_date(c("2019-Dec-01", "2020-Jan-01", "2020-Feb-01")),
  n = c(20L, 41L, 9L)
)

plot_ly() %>%
  add_bars(data = DF, x = ~Month, y = ~n, type = 'bar', split = ~Cat) %>%
  add_lines(data = DF1, x = ~Month, y = ~n, color = I("black")) %>%
  layout(barmode = "stack", xaxis = list(type = 'date', tickformat = '%Y-%b', tickangle = 90, nticks = 4))

Output is:

enter image description here

In the above visualization, the line starts from mid December and ends in mid February. Is it possible to start the line from extreme left and ends in extreme right so that it looks more continuous type?


Solution

  • I tried to play with the dates in DF and DF1 and it seems possible to achive what you are looking for by just moving DF1 to mid of the month 15th and moving DF to beginning of december, mid of january and end of february. Just used +-2 days at the beginning and the end for the lines to look nicer:

    DF <- data.frame(
      Month = lubridate::as_date(c("2019-Dec-15", "2019-Dec-15","2020-Jan-15","2020-Jan-15","2020-Jan-15", "2020-Feb-15", "2020-Feb-15")),
      #Week = c(4L, 5L, 5L, 1L, 1L, 1L, 2L, 1L),
      Cat = c("A", "C", "A", "B", "C", "A", "C"),
      n = c(38L, 10L, 19L, 20L, 12L, 14L, 20L)
    )
    
    DF1 <- data.frame(
      Month = lubridate::as_date(c("2019-Dec-03", "2020-Jan-15", "2020-Feb-27")),
      n = c(20L, 41L, 9L)
    )
    

    enter image description here

    If you want the labels to appear correctly (just took me a while to figure it out)

    plot_ly() %>%
      add_bars(data = DF, x = ~Month, y = ~n, type = 'bar', split = ~Cat) %>%
      add_lines(data = DF1, x = ~Month, y = ~n, color = I("black")) %>%
      layout(barmode = "stack", xaxis = list(
        type = 'date',
        ticktext = list("2019-Dec", "2020-Jan", "2020-Feb"), 
        tickvals = list(as.Date("2019-12-15"),as.Date("2020-01-15"),as.Date("2020-02-15"))
      )) 
    

    enter image description here