【问题标题】:Creating Custom Graphs with imported Data使用导入的数据创建自定义图表
【发布时间】:2016-01-05 13:42:42
【问题描述】:

我一直在尝试在我的 Shiny Project 中创建自定义图表,但出现错误:

> Warning in model.response(mf, "numeric") : NAs introduced by coercion
> Error in contrasts<-(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :   
>     contrasts can be applied only to factors with 2 or more levels

代码如下:

observeEvent(input$create_cutom_graph, {
  output$cutom_graph <- reactive(renderPlot(
    plot(input$graph_X,input$graph_Y),
    abline(lm(input$graph_X~input$graph_Y)),
    title(input$graph_X,"i",input$graph_Y)
  ))
 }
))

它应该工作的方式是你从下拉菜单中选择哪些数据应该在 X 轴上,然后你对 Y 轴做同样的事情, 然后您单击“创建”按钮,它可以解决问题,但不知何故它没有。 而且我还必须强调,我已经尝试在数据之前应用函数na.omit,例如:na.omit(input$graph_X),但它仍然不能解决问题。

谢谢你的帮助!

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    如果我理解正确,用户应该在导入的数据中选择一列的名称。这里的问题是来自用户的输入参数属于字符类。当您调用绘图函数时,数据中所需列的名称作为长度为 1 的字符向量放入函数调用中。它不知道如何处理此类参数。 lm 函数也是如此。为了解决这个问题,您可以使用data[,'someCharacter'] 对数据进行子集化处理。

    下次您发布问题时,包含一个可重现的示例会很有帮助,请参阅here。我创建了一个可重现的虚拟 Shiny App 来演示答案。要成功运行此应用程序,您需要将此文件保存为“app.R”,并确保工作目录包含该文件。

    如果您希望您的 plotOutput 依赖于用户的某些事件,那就是您希望代码在用户运行时运行,例如单击一个按钮,我建议使用 eventReactive 而不是 observeEvent。

    ui <- shinyUI(fluidPage(
    
    
    
     titlePanel("Plot columns in a dataset"),
        fluidRow(
            column(4,
                   selectInput("graph_X", "Select column 1", choices=c("One","Two","Three")),
                   selectInput("graph_Y", "Select column 2", choices=c("One","Two","Three"),selected="Two"),
                   actionButton("create_custom_graph","Plot")
            ),
            column(8,
                   plotOutput("plot")
            )
    
        )
        ))
    
        server <- function(input,output){
            makePlot<- eventReactive(input$create_custom_graph,{
    
            #make some dummy data
            data=data.frame(One=c(1,2,3,4,5),Two=c(1,2,3,4,5),Three=c(4,5,6,7,8))
            col1=data[,input$graph_X]
            col2=data[,input$graph_Y]
    
            #evaluate the characters
            plot(col1,col2)
            abline(lm(col1~col2))
            title(paste(input$graph_X,"i",input$graph_Y))
        })
        output$plot <- renderPlot({
            makePlot()
        })
    }
    
    shinyApp(ui,server)
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 2016-04-30
      • 2018-07-23
      • 2017-09-25
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多