teunbrand / ggh4x

ggplot extension: options for tailored facets, multiple colourscales and miscellaneous
https://teunbrand.github.io/ggh4x/
Other
534 stars 32 forks source link

scale_y_dendrogram() not displaying dendro with ggplotly() in shiny app #128

Closed marine-ecologist closed 9 months ago

marine-ecologist commented 9 months ago

I've very much appreciated the simplicity of scale_y_dendrogram() to pair bar graphs and dendrograms in ggplot(), and would like to use the code in a shiny app via ggplotly. I'm sure this is my lack of knowledge as to how scale_y_dendrogram() is functioning under the hood rather than an issue, but I can't get the dendrogram to appear within the plot.

Example code below:

library(shiny)
library(ggplot2)
library(plotly)
library(ggh4x)

clusters <- hclust(dist(USArrests), "ave")

# reshaping USArrests
df <- data.frame(
  State = rownames(USArrests)[row(USArrests)],
  variable = colnames(USArrests)[col(USArrests)],
  value = unname(do.call(c, USArrests))
)

ggplot(df, aes(variable, State, fill = value)) +
  geom_raster() + scale_y_dendrogram(hclust = clusters)

Works fine:

Screenshot 2023-09-17 at 8 49 13 pm
ui <- fluidPage(
  plotlyOutput("plot")
)

server <- function(input, output, session) {
  output$plot <- renderPlotly({

    g <- ggplot(df, aes(variable, State, fill = value)) +
      geom_raster() + 
      scale_y_dendrogram(hclust = clusters)

    ggplotly(g)   
    })
}

shinyApp(ui, server)

Missing y axis:

Screenshot 2023-09-17 at 8 49 41 pm

The same problem exists with scale_x_dendrogram() and scale_y_dendrogram(). Am I missing something in how ggh4x is pairing with the ggplot() output and is there a solution to this with ggplotly?

teunbrand commented 9 months ago

Hi there,

I'm not too familiar with the inner workings of {plotly} and how axes are handled. From a small experiment, it seems that any non-default axis isn't displayed. You can check for yourself by running this example:

library(ggplot2)
library(plotly)

p <- ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  guides(x = "none", y = "none")

# No x/y axes
p

# Has x/y axes
ggplotly(p)

In any case, since plotly doesn't appear to support custom axes, there isn't anything I can do from ggh4x's side to make it possible.

Best, Teun