'Ggplotly corrupts facet_wrap() fixed scales

When I plot this using only ggplot2, with fixed scales, there's no problem at the faceted plot

  ggplot(aes(x = fecha, y = prom_imagen_pos)) +
  geom_line(size = 1.5) +
   annotate(geom='line', x=oposicion$fecha,y=oposicion$imagen , size = 1.5, color = "darkgoldenrod") +
  facet_wrap(dirigente~.,scales = "fixed",) +
  scale_y_continuous(labels = function(x) paste0(x, "%"),breaks = c(20,30,40,50,60)) +
  labs(x = "",
       y = "") +
  theme_light()

Note that y scales are fixed

This is plot using ggplotly

When I add ggplotly() function to that plot, the faceted y scale gets broken (the top ones have one, and the bottom ones have other). There's a way to solve this and have a fixed scale like in the first plot?

Code:

plot <-   ggplot(aes(x = fecha, y = prom_imagen_pos)) +
  geom_line(size = 1.5) +
   annotate(geom='line', x=oposicion$fecha,y=oposicion$imagen , size = 1.5, color = "darkgoldenrod") +
  facet_wrap(dirigente~.,scales = "fixed",) +
  scale_y_continuous(labels = function(x) paste0(x, "%"),breaks = c(20,30,40,50,60)) +
  labs(x = "",
       y = "") +
  theme_light()

ggplotly(plot, dynamicTicks = TRUE) 

Using ggplotly looks like this



Solution 1:[1]

You'll want to set dynamicTicks = FALSE in ggplotly(...). Per the documentation:

Dynamic ticks are useful for updating ticks in response to zoom/pan interactions; however, they can not always reproduce labels as they would appear in the static ggplot2 image

I tested this out quickly using the diamonds dataset that comes with ggplot2.

library(ggplot2)
library(plotly)
my.plt <- ggplot(diamonds, aes(x = price, y = carat)) + 
   geom_point() + 
   facet_wrap(~clarity, nrow = 2) # scales = "fixed" is used by default


ggplotly(my.plt, dynamicTicks = FALSE)

image of correct y-axis scale

Setting dynamicTicks = TRUE overrides the fixed scales/labels in the facets.

ggplotly(my.plt, dynamicTicks = TRUE)

image of incorrect y-axis scale

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 krfurlong