【发布时间】:2020-06-17 18:35:07
【问题描述】:
我正在关注 R Shiny Gallery 中的 kmeans 教程,并希望修改为使用三个变量并绘制一个 3D 散点图。没有错误,但图表未显示。这似乎应该工作......我做错了什么?
data <- iris %>% select(-Species)
# this works
# data %>%
# plot_ly(x = ~Petal.Length, y = ~Petal.Width, z = ~Sepal.Length) %>%
# add_markers()
server = function(input, output, session) {
# Combine the selected variables into a new data frame
selectedData <- reactive({
data[, c(input$xcol, input$ycol, input$zcol)]
})
clusters <- reactive({
kmeans(selectedData(), input$clusters)
})
output$plot1 <- renderPlotly({
selectedData() %>%
plot_ly(x = ~input$xcol, y = ~input$ycol, z = ~input$zcol) %>%
add_markers()
})
}
ui <-
pageWithSidebar(
headerPanel('Iris'),
sidebarPanel(
selectInput('xcol', 'X Variable', names(data)),
selectInput('ycol', 'Y Variable', names(data)),
selectInput('zcol', 'Z Variable', names(data)),
numericInput('clusters', 'Cluster count', value = 3, step = .5, min = 1, max = 10)
),
mainPanel(
plotOutput('plot1')
)
)
# Run the application
shinyApp(ui = ui, server = server)
【问题讨论】:
-
只需将
plotOutput更改为plotlyOutput。 -
哦,伙计...多么简单的修复。谢谢你。然而,正如编程中经常发生的那样,修复那个东西会使其他东西崩溃。有些东西没有与变量值正确映射。
-
也许您在 plotly 函数中对数据框列进行子集化有问题?这行得通吗?
df <- selectedData()plot_ly(x = df[, input$xcol], y = df[, input$ycol], z = df[, input$zcol]) %>%add_markers() -
是的!确实如此。谢谢你。如果你想作为我可以接受的答案。