3

I am trying to adjust plots in flexdashboard by taking the pixelratio provided by the user session, this works fine when I am rendering plot with renderPlot but I am struggling to assign dynamic heights / widths to plots that are rendered with renderPlotly

I extract the user pixel ratio as followed

pixelratio <- reactive({
  session$clientData$pixelratio
})

attempt 1

output$myplot <- renderPlotly(myplot())
plotlyOutput("myplot", height = function() {900 / pixelratio()}, width = 825)

the first attempt is giving the following error msg :

Error : CSS units must be single element numeric or character vector

attempt 2

output$myplot <- renderPlotly(myplot())
plotlyOutput("myplot", height = 900 / pixelratio(), width = 825)

the second attempt is submitting the following error msg:

Error : Operation not allowed without an active reactive context.
* You tried to do something that can only be done from inside a reactive consumer

Is there a way to get pixelratio in order to autoscale plotlyOutput?

Yough Ghoug
  • 127
  • 2
  • 9
  • 1
    Try `plotlyOutput("myplot", height = 900 / pixelratio(), width = 825)` in a `renderUI`, and then use `uiOutput` on the `ui` side. – YBS Aug 12 '21 at 14:06
  • 1
    You wrote that you wanted to go based on screen size, but you chose pixels. You could try percent. Additionally, depending on how you implement it and what you implement (since you didn't provide all of the details), you could try to use `vh` and `vw` (viewport height and viewport width, respectively). Viewport scaling is another method to implement percentage as a measure. – Kat Aug 12 '21 at 14:10
  • @Kat - using the percentage doesn't scale up as expected, this is why i prefer multiply a fixed width/height by the pixelratio or another coefficient – Yough Ghoug Aug 12 '21 at 14:50
  • @YBS I have tried your solution and it works but it takes more time to render my plot – Yough Ghoug Aug 12 '21 at 15:35

1 Answers1

1

You can set the height in the plotl_ly function and set height = "auto" in plotlyOutput.

library(shiny)
library(plotly)
library(dplyr)
library(tibble)

state <- data.frame(state.x77, state.region, state.abb) %>% 
  rename(Region = state.region) %>% 
  rownames_to_column("State")


ui <- fluidPage(
  br(),
  plotlyOutput("myplotly", width = 825, height = "auto")
)

server <- function(input, output, session){
  
  pixelratio <- reactive({
    session$clientData$pixelratio
  })
  
  output[["myplotly"]] <- renderPlotly({
    plot_ly(
      data = state,
      x = ~ Income,
      y = ~ Murder,
      type = "scatter",
      mode = "markers",
      text = ~ paste(State, "<br>Income: ", Income, '<br>Murder Rate:', Murder),
      height = 900 / pixelratio()
    )
    
  })
  
  observe({
    print(pixelratio())
  })
}

shinyApp(ui, server)
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225