r - 为什么同样的 ggplot 可以直接运行,但在 Shiny 中却失败?

标签 r ggplot2 shiny

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

Warning in xy.coords(x, y, xlabel, ylabel, log) :
  NAs introduced by coercion

我做错了什么?

我将此代码尝试基于在网络上阅读和 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

最佳答案

在 Shiny 的,input$xcol只是一个从UI返回的字符串。因此,如果您使用这些值,就像调用

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

返回的错误与您在 Shiny 中遇到的错误相同。

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

plot(dfx[[input$xcol]], dfx[[input$ycol]], xlim=c(0,6), ylim=c(0,10))

当然,plot() 是基本的 R 绘图命令。如果您确实想使用ggplot,您可以使用类似

ggplot(dfx) +
  aes(.data[[input$xcol]], .data[[input$ycol]]) + 
  geom_point()

关于r - 为什么同样的 ggplot 可以直接运行,但在 Shiny 中却失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68024984/

相关文章:

r - r中的NROW和nrow有什么区别?

从 GitHub 运行 Shiny 的应用程序

r - Shiny :在操作按钮单击时显示 mainPanel

R Shiny ,无法使用ggplot的 Shiny react 变量设置列名称

r - 从 R 中矩阵的每一列创建列表

R引用类和doparallel

r - 如何在ggplot2的右侧放置转换的比例?

r - ggplot2 - 如何使用另一个数据框作为查找表更改构面标签文本

r - 如何在每个方面添加注释

r - 按组查找每行日期后满足条件的第一行