使用反应值调整给定屏幕尺寸的绘图

adjust plot given screen size with reactive value

我正在尝试通过采用用户会话提供的像素比率来调整 flexdashboard 中的绘图,当我使用 renderPlot 渲染绘图时这工作正常但我正在努力为使用 renderPlotly 渲染的绘图分配动态高度/宽度

我提取用户像素比例如下

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

尝试 1

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

第一次尝试给出以下错误消息:

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

尝试 2

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

第二次尝试提交以下错误消息:

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

有没有办法获取像素比率以便自动缩放 plotlyOutput?

可以在plotl_ly函数中设置高度,在plotlyOutput中设置height = "auto"

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)