首页 > 解决方案 > 初学者 - 我想在 R 中的 Shiny 上制作 ggplot,但我不知道我在哪里犯了错误

问题描述

我在 R 中使用 Shiny 来制作两个不同的选项卡。我认为一个选项卡是一个好主意,可以制作一个摘要选项卡,另一个选项卡用于绘图。我想为用户提供 x、y 和颜色部分的选择...当我完成 ggplot 部分的部分时,该图未按预期显示。请帮我解决我在哪里犯了错误,请帮助我理解它。

谢谢你。

# ui.R
library(shiny)
library(ggplot2)
library(plyr)
library(dplyr)

data(mtcars)
new_mtcars <- mtcars %>%
  select(wt,mpg,cyl,vs,am,gear,carb)

# Define UI for an application that draws a histogram
shinyUI(fluidPage(
  
  # Application title
  titlePanel("prac"),
  
  # Sidebar with a slider input for number of bins 
 sidebarLayout(
   sidebarPanel(
     selectInput("xvalue","Please Choose X Value : ", c("wt","mpg")),
     selectInput("yvalue","Please Choose Y Value : ", c("wt","mpg")),
     selectInput("color","Please Choose color Value : ", choices =  c("cyl","vs","am","gear","carb"))
   ),
   mainPanel(
     tabsetPanel(#tabPanel("Information",tableOutput("info")),
                 tabPanel("Summary",tableOutput("summary")),
                 tabPanel("Comparison",plotOutput("plot")))
   )
  )
 
  # Show a plot of the generated distribution
  
))
library(shiny)

# Define server logic required to draw a histogram
shinyServer(function(input, output) {
  df_sub <- reactive({
    new_mtcars[,c(input$xvalue,input$yvalue,input$color)]
  })
  
  output$plot <- renderPlot({
    category <- input$color
    ggplot(df_sub(), aes(input$xvalue,input$yvalue)) + 
      geom_point(aes_(color = as.name(category)),size = 3) +
      geom_smooth(method = "lm")
  })
 })

标签: rggplot2shiny

解决方案


问题是,input$xvalue并且input$yvalue是字符。告诉 ggplot 它应该在数据集中查找具有这些名称的变量

  1. 使用.data[[input$xvalue]]and .data[[input$yvalue]]inside aes()or
  2. 使用aes_string而不是aes().

在此处输入图像描述


推荐阅读