Search code examples
rggplot2plotlyggplotly

ggplotly with horizontal geom_crossbar() not matching original ggplot


When I use ggplot with geom_crossbar() going horizontally, everything looks how I want it. When I wrap the plot using ggplotly, the reference lines become meaningless and in the wrong orientation. Please see code and snapshots below:

Data Setup:

df <- data.frame(
    trt = factor(c(1, 1, 2, 2)),
    resp = c(1, 5, 3, 4),
    group = factor(c(1, 2, 1, 2)),
    upper = c(1.1, 5.3, 3.3, 4.2),
    lower = c(0.8, 4.6, 2.4, 3.6)
)

p <- ggplot(df, aes(resp, trt, colour = group)) + 
     geom_crossbar(aes(y=trt,xmin = lower, xmax = upper), width = 0.2)

ggplot with horizontal crossbar

ggplotly(p)

enter image description here

Is this a bug with ggplotly or is there a workaround I am not aware of? I would love to keep the crossbars going horizontal because it looks better with my actual data.


Solution

  • A workaround would be to use coord_flip() which requires to switch x and y:

    library(ggplot2)
    library(plotly)
    
    p <- ggplot(df, aes(trt, resp, colour = group)) +
      geom_crossbar(aes(x = trt, ymin = lower, ymax = upper),
        width = 0.2
      ) +
      coord_flip()
    
    ggplotly(p)