Search code examples
rhistogramplotly

Overlaying two histograms in R Plotly


I'm trying to overlay two histogram plots in R plotly. However only one of them shows up. Here's the code I'm using with some random data:

    myDF <- cbind.data.frame(Income = sample(1:9, size = 1000, replace= TRUE),
                           AgeInTwoYearIncrements = sample(seq(from = 2, to = 70, by = 2), size = 1000, replace = TRUE))


plot_ly(data = myDF, alpha = 0.6) %>% 
  add_histogram(x = ~Income, yaxis = "y1") %>% 
  add_histogram(x = ~AgeInTwoYearIncrements, yaxis = "y2") %>% 
  layout(
    title = "Salary vs Age",
    yaxis = list(
      tickfont = list(color = "blue"),
      overlaying = "y",
      side = "left",
      title = "Income"
    ),
    yaxis2 = list(
      tickfont = list(color = "red"),
      overlaying = "y",
      side = "right",
      title = "Age"
    ),
    xaxis = list(title = "count")
  )

Any help would be much appreciated!


Solution

  • It is the main cause to give the 1st yaxis overlaying. And because xaxis is count, Income and Age is y.

    plot_ly(data = myDF, alpha = 0.6) %>% 
      add_histogram(y = ~Income, yaxis = "y1") %>%    # not `x =`
      add_histogram(y = ~AgeInTwoYearIncrements, yaxis = "y2") %>% 
      layout(
        title = "Salary vs Age",
        yaxis = list(
          tickfont = list(color = "blue"),
          # overlaying = "y",     # the main cause is this line.
          side = "left",
          title = "Income"
        ),
        yaxis2 = list(
          tickfont = list(color = "red"),
          overlaying = "y",
          side = "right",
          title = "Age"
        ),
        xaxis = list(title = "count")
      )
    

    enter image description here

    [Edited: just flip]
    plot_ly(data = myDF, alpha = 0.6) %>% 
      add_histogram(x = ~ Income, xaxis = "x1") %>% 
      add_histogram(x = ~ AgeInTwoYearIncrements, xaxis = "x2") %>% 
      layout(
        margin = list(t = 60),
        title = "Salary vs Age",
        xaxis = list(
          tickfont = list(color = "blue"),
          side = "left",
          title = "Income"
        ),
        xaxis2 = list(
          tickfont = list(color = "red"),
          overlaying = "x",
          side = "top",
          position = 0.95,
          title = "<br>Age"
        ),
        yaxis = list(title = "count")
      )
    

    enter image description here