为什么相同的 ggplot 直接工作但在 Shiny 中失败?

Wad*_*tte 2 r ggplot2 shiny

当我创建一个小数据框并在 RStudio 中将直接绘图运行到 PLOT 选项卡,然后尝试在 Shiny 中运行相同的概念时,直接绘图有效,并且 Shiny 绘图显示为空白并显示错误消息:

Warning in xy.coords(x, y, xlabel, ylabel, log) :
  NAs introduced by coercion
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

我将此代码尝试基于在网络上阅读和 Stack Overflow 中的先前答案,因此很接近,但我错过了一些隐式转换或其他内容。我只想使用 Shiny 来绘制数据框的两列。

 library(shiny)

dfx <- data.frame(xx=c(1,2,3,4,5),
                  yy=c(2,4,6,8,10))


plot(dfx$xx, dfx$yy, xlim=c(0,6), ylim=c(0,10))

# the result in PLOTS in RStudio is a 5 point rising line graph as expected.

ui <- fluidPage(
  headerPanel('my first shiny app'),
  sidebarPanel(
    selectInput('xcol', 'X Variable', names(dfx)),
    selectInput('ycol', 'Y Variable', names(dfx))
  ),
  mainPanel(
    plotOutput('plot1')
  )
)

server <- function(input, output) {
  output$plot1 <- renderPlot({
    plot(input$xcol, input$ycol, xlim=c(0,6), ylim=c(0,10))
  })
}

shinyApp(ui = ui, server = server)

# the result of this in shiny is a blank graph

Run Code Online (Sandbox Code Playgroud)

MrF*_*ick 5

在闪亮中,input$xcol只是一个从 UI 返回的字符串。所以如果你使用这些值,就像调用

plot("xx", "yy", xlim=c(0,6), ylim=c(0,10))
Run Code Online (Sandbox Code Playgroud)

它返回与 Shiny 相同的错误。

如果您想从 data.frame 中获取值,则需要执行dfx[[input$xcol]]. 所以试试

plot(dfx[[input$xcol]], dfx[[input$ycol]], xlim=c(0,6), ylim=c(0,10))
Run Code Online (Sandbox Code Playgroud)

当然plot()是基本的 R 绘图命令。如果你确实想使用ggplot,你会使用类似的东西

ggplot(dfx) +
  aes(.data[[input$xcol]], .data[[input$ycol]]) + 
  geom_point()
Run Code Online (Sandbox Code Playgroud)