ggplot格式化闪亮

时间:2019-12-21 19:10:40

标签: r ggplot2 shiny

我想了解如何在ggplot中使用shiny

当我尝试在内置mtcars数据集上编写简单的kmean应用程序时,无法在ggplot中绘制结果。

可以绘制结果,但似乎有点不正确。

我想寻求任何建议:

ui <- fluidPage(

pageWithSidebar(
  headerPanel('Iris k-means clustering'),
  sidebarPanel(
    selectInput('xcol', 'X Variable', names(mtcars)),
    selectInput('ycol', 'Y Variable', names(mtcars),
                selected=names(mtcars)[[2]]),
    numericInput('clusters', 'Cluster count', 3,
                 min = 1, max = 9)
  ),
  mainPanel(
    plotOutput('plot1')
  )
)
)

server <- function(input, output, session) {

  # Combine the selected variables into a new data frame
  selectedData <- reactive({
    mtcars[, c(input$xcol, input$ycol)]
  })

  clusters <- reactive({
    kmeans(selectedData(), input$clusters)
  })

  output$plot1 <- renderPlot({

    x <- input$xcol
    y <- input$ycol

    ggplot(mtcars, aes(x, y)) +
      geom_point(size = 4, aes(color = factor(clusters()$cluster)))
  })

}


shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:2)

我们可以更改此工作,然后重试吗? 这对我有用!

output$plot1 <- renderPlot({
x <- input$xcol
y <- input$ycol
ggplot(mtcars, aes_string(x, y)) +
  geom_point(size = 4, aes_string(color = factor(clusters()$cluster)))  })