当我创建一个小数据框并在 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/