【问题标题】:ShinyApp scatterplot displays only one pointShinyApp 散点图只显示一个点
【发布时间】:2019-03-09 04:22:29
【问题描述】:

我正在尝试创建一个闪亮的应用程序来创建基于 Iris 数据集的散点图。代码生成应用程序,但无论我在应用程序中选择什么设置,都只在图表上显示一个点。代码如下:

options(warn = -1)
library(shiny)
library(shinythemes)
library(dplyr)
library(readr)
library(ggplot2)
options(warn=0)



# Define UI
ui <- fluidPage(theme = shinytheme("superhero"),
                titlePanel("Iris"),
  sidebarLayout(
    sidebarPanel(

      # Select Inputs
      selectInput(inputId = "y",
                  label = "Y-axis:",
                  choices = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"),
                  selected = "Sepal.Length"),

      selectInput(inputId = "x",
                  label = "X-axis:",
                  choices = c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"),
                  selected = "Petal.Length")
      ),

    # Output
    mainPanel(
      plotOutput(outputId = "scatterplot")
    )
  )
)

# Define server function
server <- function(input, output) {

  # Create the scatterplot object the plotOutput function is expecting
  output$scatterplot <- renderPlot({
    ggplot(data = iris, aes(x = input$x, y = input$y))+
      geom_point(aes(color=Species, shape=Species))+
      geom_smooth(method="lm")
  })
}

shinyApp(ui=ui, server=server)

【问题讨论】:

标签: r shiny


【解决方案1】:

这是因为您的 input$x 实际上是一个字符串。因此,在您的 ggplot 调用中将 aes() 替换为 aes_string()

library(ggplot2)

# This doesn't work: aes
ggplot(data = iris, aes(x = "Sepal.Length", y = "Sepal.Width"))+
  geom_point(aes(color=Species, shape=Species))+
  geom_smooth(method="lm")

# This works : aes_string
ggplot(data = iris, aes_string(x = "Sepal.Length", y = "Sepal.Width"))+
  geom_point(aes(color=Species, shape=Species))+
  geom_smooth(method="lm")

见:passing string to ggplot function

【讨论】:

  • 请注意 aes_string 已被 deprecated 支持 tidyeval
  • 谢谢卡米尔。在这种情况下,您将如何使用 tidyeval ?我发现的唯一解决方法是在aes() 中的!!as.name("Sepal.Length"),但可能有更方便的解决方案。
猜你喜欢
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多