Home > Back-end >  R plotly second y axis title not alligned with horizontal legend
R plotly second y axis title not alligned with horizontal legend

Time:12-08

When I combine 2 plots in 1 in plotly with horizontal legend the 2nd y-axis title (right-side) is not well alligned...it covers the ticks see:

x1 <- rnorm(50)
x2 <- rnorm(10)

fit <- density(x1, na.rm = T)

fig <- plot_ly() 

fig <- fig %>% 
  
  add_histogram(x = ~x1, name = "X1", marker = list(color = "red")
  ) %>%
  
  add_histogram(x = ~x2, name = "X2", marker = list(color ="#blue")
  ) %>% 
  
  add_lines(x = fit$x, y = fit$y, yaxis = "y2", name = "Density", line = list(color = "#33228875", inherit = F)
   )%>%
  
  layout(yaxis2 = list(title = 'testesttesttesttesttesttesttesttest',
                       overlaying = "y", 
                       side = "right", 
                       rangemode = "tozero"),
                       legend = list(orientation = "h")
  )

enter image description here

With normal right alligned legend it goes well

enter image description here

Any fix for the y2 title with horizontal legend? I thought about adding a small white picture to the right outside the paper-area but obviously doenst make any sense

CodePudding user response:

Set automargin = TRUE in the definition of the second y-axis:

fig <- plot_ly()  %>% 
  add_histogram(x = ~x1, name = "X1", marker = list(color = "red")) %>%
  add_histogram(x = ~x2, name = "X2", marker = list(color ="#blue")) %>% 
  add_lines(x = fit$x, y = fit$y, yaxis = "y2", name = "Density",
            line = list(color = "#33228875", inherit = FALSE)) %>%
  layout(yaxis2 = list(title = 'testesttesttesttesttesttesttesttest',
                       overlaying = "y",
                       automargin = TRUE,
                       side = "right",
                       rangemode = "tozero"),
        legend = list(orientation = "h"))

ad

  • Related