我正在努力使下面的代码正常工作。
我记得您可以强制使用plotlyproxy
和plotlyProxyInvoke
relayout
来放大图,并且在某种程度上,我的测试应用程序确实会调整范围,但是由于某种原因,它会重置立即达到全范围,我无法弄清楚如何避免这种情况,或者到底是什么原因造成的。
library(shiny)
library(plotly)
ui <- fluidPage(
plotlyOutput('PlotPlot'),
br(),
checkboxInput(inputId = 'AddAnnot', label = 'trigger rerender', value = F)
)
server <- function(input, output, session) {
values <- reactiveValues()
output$PlotPlot <- renderPlotly({
ypar <- 'mpg'
xpar <- 'cyl'
p <- plot_ly(source = 'PlotMTCARS',
data = mtcars,
height = 450,
width = 750) %>%
add_trace(x = mtcars[[xpar]],
y = mtcars[[ypar]],
type = 'scatter',
mode = 'markers') %>%
layout(
title = "Plot with zoom",
margin = list(l = 20, r= 220, b = 20, t = 50),
showlegend = FALSE,
xaxis = list(title = xpar),
yaxis = list(title = ypar)
)
## add annotation to simulate changes that cause a rerender of any kind
if(input$AddAnnot){
p <- add_annotations(p,
x = 1.4,
y = 0.70,
xref = "paper", yref = "paper", align = 'right',
textangle = 0,
font = list(size = 14,
color = '#c0c0c0'),
text = 'Just text',
showarrow = F
)
}
#this code updates the zoom, but somehow it gets overruled again by something
isolate({
if(!is.null(values$PlotZoomXmin)) {
print('applying')
print(paste("setting zoom:", values$PlotZoomYmin))
plotlyProxy('PlotPlot', session) %>%
plotlyProxyInvoke("relayout", list(yaxis = list(title = 'mpg',
showgrid = F,
range = list(values$PlotZoomYmin,values$PlotZoomYmax)
),
xaxis = list(title = 'cyl',
showgrid = F,
range = list(values$PlotZoomXmin,values$PlotZoomXmax)
)
)
)
Sys.sleep(2)
}
})
p
})
relayout_zoom <- reactive({
zoom <- event_data("plotly_relayout", source = "PlotMTCARS")
zoom
})
observe({
zoom <- relayout_zoom()
if(!is.null(zoom$`xaxis.range[0]`)) {
values$PlotZoomXmin <- zoom$`xaxis.range[0]`
values$PlotZoomXmax <- zoom$`xaxis.range[1]`
values$PlotZoomYmin <- zoom$`yaxis.range[0]`
values$PlotZoomYmax <- zoom$`yaxis.range[1]`
}
})
}
shinyApp(ui, server)