Home > Software engineering >  strip.position = "bottom" does not work when using ggplotly
strip.position = "bottom" does not work when using ggplotly

Time:09-08

When using ggplotly() the parameter strip.position = "bottom" does not work

library(tidyverse)
library(plotly)
library(ggplot2)

p = iris %>%
  ggplot(aes(x = Species , y = Sepal.Width))  
  geom_boxplot()  
  facet_wrap(~ Species , strip.position = "bottom")

ggplotly(p)

Here

CodePudding user response:

While Plotly doesn't interpret the strip position from ggplot, you can move the strips to the bottom after you create the ggplotly object.

When I looked through the settings it's like half the settings were already set for the strips to be on the bottom, but a few things didn't get set that way. In the end, you need to make one change for the annotations (the text in the strips) and one change for the shapes (the background of the strips).

Right now the extra space between the x-axis labels and the bottom of the box plots is not there, so that space needs to be readded. Additionally, there would be a gob of white space at the top of the plot after moving the strips. That means the margin needs to be adjusted, as well.

I assigned the ggplotly object to pp, then used lapply to change the yanchor position to the bottom for the shapes associated with the strips and the y to 0 for the annotations.

pp <- ggplotly(p)

invisible(
  lapply(1:length(pp$x$layout$shapes),
         function(i) {       # if a strip shape (using the strip color)
           if(isTRUE(pp$x$layout$shapes[[i]]$fillcolor == "rgba(217,217,217,1)")) {
             pp$x$layout$shapes[[i]]$yanchor <<- 0    # anchor at the bottom
           }                 # if at least i annotations (less annots than shapes)
           if(i <= length(pp$x$layout$annotations)) { # if the text is a strip label
             if(any(pp$x$layout$annotations[[i]]$text %in% unique(iris$Species))) {
               pp$x$layout$annotations[[i]]$y <<- 0.01   # move text to the bottom
             }
           }
         })
)
pp %>% layout(yaxis = list(range = c(1.5, 4.5)), # add space for strip position
              yaxis2 = list(range = c(1.5, 4.5)),
              yaxis3 = list(range = c(1.5, 4.5)),
              margin = list(t = 10, r = 10, b = 43, l = 43)) # remove excess on top

By the way, the way I used the original margins (rounded) for the right, left, and bottom. I really only changed the top margin.

enter image description here

  • Related