Shiny R:如何根据输入来更改绘图的不透明度?

问题描述 投票:0回答:1

在我的项目中,滑块控制模拟数据集的大小,大小范围为[5,10000]。

由于数据点可能会重叠,所以我希望在尺寸较小时具有较高的不透明度,而在尺寸较大时具有较低的不透明度。

我尝试使用reactValue和observeEvent,但不透明度在0.2不变:

o<- reactiveValues(data = NULL)
observeEvent(input$size<100,{
  o$data<-1
})
observeEvent(input$size>=100,{
  o$data<-0.2
})

p<-plot_ly()%>%
    add_trace(x=x,y=y1,type = 'scatter',mode = 'lines', name = "y1=a1+b1*x",line = list(color = 'rgb(255, 129, 10)'))%>%
    add_trace(x=round(random_x,4),y= round(y1_data,4),  opacity=o$data,name = 'y1_data',type = 'scatter',mode = 'markers',marker = list(size = 5, color ='rgb(255, 129, 10)')         

这里是相关代码:

sliderInput("size", "Select the sample size",min = 5,max = 10000,value = NULL,step = 1)
        random_x<- rnorm(input$size,mean = 0, 3)
        random_num1<- rnorm(input$size, mean=0, sd=input$sd1)
        random_num2<- rnorm(input$size, mean=0, sd=input$sd2)

        y1_data<- random_num1 + random_x*input$b1+input$a1
        y2_data<- 1/(1+exp(random_num2-input$a2-input$b2 * random_x))


        x<- seq(-10,10,0.1)
        y1<- x*input$b1+input$a1
        y2<- 1/(1+exp(-input$a2-input$b2*x))

        #plot
        p<-plot_ly()%>%
            layout(xaxis = list(range=c(-10,10)), yaxis = list(range=c(-32,32)))

        if (input$simple){
            p<-p%>%
                add_trace(x=x,y=y1,type = 'scatter', mode = 'lines', name = "y1=a1+b1*x",line = list(color = 'rgb(255, 129, 10)'))%>%
                add_trace(x=round(random_x,4),y= round(y1_data,4), name = 'y1_data',
                          type = 'scatter',mode = 'markers',marker = list(size = 5, color ='rgb(255, 129, 10)'))
            }

        if (input$logistic) {
            p<-p%>%
                add_trace(x=x,y=y2,type = 'scatter', mode = 'lines', name = "y2=1/(exp(-a2-b2*x))", line = list(color = 'rgb(22, 96, 167)'))%>%
                add_trace(x=round(random_x,4),y= round(y2_data,4), name = 'y2_data',
                          type = 'scatter',mode = 'markers',marker = list(size = 5, color ='rgb(22, 96, 167)'))
        }
r shiny plotly visualization opacity
1个回答
0
投票

我怀疑是当滑块更改值时,将同时调用两个observeEvent方法。然后,即使您的reactiveValues o$data被一个observeEvent更改为1,也将立即被另一个observeEvent用.2覆盖。相反,您可以简化为单个observeEvent语句吗?请在下面尝试类似的操作,看看是否按照您希望的方式运行。

library(shiny)

ui <- fluidPage(
  sliderInput("size", "Select the sample size", min = 5, max = 1000, value = NULL, step = 1)
)

server <- function(input, output, session) {

  o <- reactiveValues(data = NULL)

  observeEvent(input$size,{
    if (input$size < 100) {
      o$data <- 1
    } else {
      o$data <- .2
    }
    print(o$data)
  })

}

shinyApp(ui, server)
© www.soinside.com 2019 - 2024. All rights reserved.