我想在我的Shiny App中绘制一个绘制的3D图形,但只绘制具有在输入范围滑块范围内的值的数据。但是我想在滑块范围内没有值时阻止绘图 - 当前没有输入时会导致以下错误:
Warning: Error in UseMethod: no applicable method for 'plotly_build' applied
to an object of class "NULL"
或在示例代码中:
Error in : length(Lab) == 3L is not TRUE
这是一个示例代码,它与原始问题有类似的错误:
library(shiny)
library(plotly)
d = diamonds[1:100,]
ui = fluidPage(
headerPanel("Data"),
sliderInput(inputId="slider", label = "Choose a range", value =c(0,max(d$price)),
min = 0,max = max(d$price)),
# saves space for the plot in the user interface. Id allows communication
plotlyOutput(outputId="trendPlot", width="100%", height=800)
)
server = function(input, output)
{
NROF = reactiveValues(test = 1)
output$trendPlot= renderPlotly({
d_sub=d[d$price >= input$slider[1] & d$price <= input$slider[2],]
NROF = nrow(d)
if(NROF != 0)
{
plot_ly(d_sub, x=d_sub$cut, y=d_sub$color, z=factor(d_sub$color),
type='scatter3d', mode='markers',
sizemode='diameter', size=d_sub$price, color=d_sub$price,colors = 'Set1')
}
})
}
shinyApp(ui=ui, server=server)
解决方案:我使用反应值时犯了一个错误 - 应该是NROF $ TEST
答案 0 :(得分:2)
您正在寻找req()
或validate()
之类的声音:
http://shiny.rstudio.com/articles/req.html
http://shiny.rstudio.com/articles/validation.html
library(shiny)
library(plotly)
d <- diamonds[1:100,]
ui <- fluidPage(
headerPanel("Data"),
sliderInput(inputId="slider",
label = "Choose a range",
value =c(0,max(d$price)),
min = 0,max = max(d$price)),
# saves space for the plot in the user interface. Id allows communication
plotlyOutput(outputId="trendPlot",
width="100%", height=800)
)
server <- function(input, output) {
output$trendPlot <- renderPlotly({
d_sub <- d[d$price >= input$slider[1] & d$price <= input$slider[2],]
req(nrow(d_sub) > 0)
# validate(need(nrow(d_sub) > 0, "No data selected!"))
plot_ly(d_sub, x=d_sub$cut, y=d_sub$color,
z=factor(d_sub$color), type='scatter3d',
mode='markers', sizemode='diameter',
size=d_sub$price, color=d_sub$price,
colors = 'Set1')
})
}
shinyApp(ui=ui, server=server)
答案 1 :(得分:0)
我试图重现它。我的建议是有一个小错字(你的意思是NROF = nrow(d_sub)
而不是NROF = nrow(d)
)。另外,您没有包含else
案例的任何返回值。
这对你有帮助吗?
server = function(input, output)
{
NROF = reactiveValues(test = 1)
output$trendPlot= renderPlotly({
d_sub=d[d$price >= input$slider[1] & d$price <= input$slider[2],]
NROF = nrow(d_sub)
if(NROF != 0)
{
plot_ly(d_sub, x=d_sub$cut, y=d_sub$color, z=factor(d_sub$color),
type='scatter3d', mode='markers',
sizemode='diameter', size=d_sub$price, color=d_sub$price,colors = 'Set1')
} else {
plot_ly(type='scatter3d')
}
})
}