【问题标题】:What conditions do I need to make my plot reactive?我需要什么条件才能使我的情节反应?
【发布时间】:2019-09-29 11:17:24
【问题描述】:

我正在尝试使用列名为“release_year”的数据框作为滑块输入,因此无论我选择什么时间线,比如 1960 年到 1970 年,我只能在散点图上看到来自该特定时间线的数据。现在我的滑块表现得很奇怪,除了移动几个点之外什么也没做。我怎样才能解决这个问题?像这样的东西 https://shiny.rstudio.com/gallery/movie-explorer.html 你看到年份发布滑块了吗?我想要那个确切的东西。

  • 附加我的数据集的图像。
  • [df] (https://imgur.com/NZWuWtF)

     structure(list(id = c(135397L, 135397L, 76341L, 76341L, 262500L, 
    140607L, 140607L, 140607L, 168259L, 168259L), budget = c(150000000L, 
    150000000L, 150000000L, 150000000L, 110000000L, 200000000L, 200000000L, 
    200000000L, 190000000L, 190000000L), revenue = c(1513528810, 
    1513528810, 378436354, 378436354, 295238201, 2068178225, 2068178225, 
    2068178225, 1506249360, 1506249360), title = structure(c(3L, 
    3L, 4L, 4L, 2L, 5L, 5L, 5L, 1L, 1L), .Label = c("Furious 7", 
    "Insurgent", "Jurassic World", "Mad Max: Fury Road", "Star Wars: The Force Awakens"
    ), class = "factor"), homepage = structure(c(2L, 2L, 3L, 3L, 
    5L, 4L, 4L, 4L, 1L, 1L), .Label = c("http://www.furious7.com/", 
    "http://www.jurassicworld.com/", "http://www.madmaxmovie.com/", 
    "http://www.starwars.com/films/star-wars-episode-vii", "http://www.thedivergentseries.movie/#insurgent"
    ), class = "factor"), director = structure(c(1L, 1L, 2L, 2L, 
    5L, 3L, 3L, 3L, 4L, 4L), .Label = c("Colin Trevorrow", "George Miller", 
    "J.J. Abrams", "James Wan", "Robert Schwentke"), class = "factor"), 
        runtime = c(124L, 124L, 120L, 120L, 119L, 136L, 136L, 136L, 
        137L, 137L), vote_average = c(6.5, 6.5, 7.1, 7.1, 6.3, 7.5, 
        7.5, 7.5, 7.3, 7.3), release_year = c(2015L, 2015L, 2015L, 
        2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L), genre = structure(c(1L, 
        2L, 1L, 2L, 2L, 1L, 2L, 4L, 1L, 3L), .Label = c("Action", 
        "Adventure", "Crime", "Fantasy"), class = "factor"), breakeven = c(1363528810, 
        1363528810, 228436354, 228436354, 185238201, 1868178225, 
        1868178225, 1868178225, 1316249360, 1316249360), AerageVotesCat = structure(c(2L, 
        2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("Excellent", 
        "Good"), class = "factor")), row.names = c(NA, 10L), class = "data.frame" 
    
  • [需要控制数据显示的滑块] (https://imgur.com/vdvEJWN)

我几乎花了一周的时间尝试一切。我似乎无法解决这个问题。我知道问题出在我的反应支架周围的某个地方?但是作为新手,我不知道该传递什么。

UI:
library(gifski)
library(gganimate)
library(dplyr)
library(DT)
library(shinythemes)
library(scales)
library(shiny)
library(ggplot2)
library(plotly)



df <- read.csv("C:/Users/XXX/Downloads/movie1.csv")
n_total <- nrow(df)

ui <- fluidPage(theme = shinytheme("united"),
                titlePanel("Movie browser, 1960 - 2014", windowTitle = "Movies"),   

                # Sidebar layout with a input and output definitions
                sidebarLayout(
                  # Inputs
                  sidebarPanel(
                    wellPanel(

                      # Select variable for y-axis
                      selectInput(inputId = "y", 
                                  label = h4("Y-axis:"),
                                  choices =c("Budget" ="budget", "Revenue" = "revenue", "Runtime" = "runtime", "Vote average" = "vote_average", "Year released" = "release_year", "Profit" = "breakeven"), 
                                  selected = "revenue"),

                  sliderInput("SectorTime", h4("Select a time period:"), min = 1960, max = 2015,
                                value = c(1960,2015), step = 5),


                    textInput("Director", h4("Director name contains (e.g., Miyazaki)")),
                    numericInput(inputId = "n",
                                 label = h4("Sample size:"),
                                 value = 30,
                                 min = 1, max = n_total,
                                 step = 1),


                    radioButtons(inputId = "filetype",
                                 label = "Select filetype:",
                                 choices = c("csv", "tsv"),
                                 selected = "csv"),

                    # Select variables to download
                    checkboxGroupInput(inputId = "selected_var",
                                       label = "Select variables:",
                                       choices = names(df),
                                       selected = c("title"))
                  ),

                  # Outputs
                  mainPanel(
                    tabsetPanel(
                      tabPanel(h4("PLOT"), plotlyOutput("plot"),
                                            tabPanel(h4("DATA"), DT::dataTableOutput(outputId = "moviestable", width = 500)






                  )
                )
)
SERVER:

# Define server function required to create the scatterplot
server <- function(input, output) {

  dataset <- reactive({
    df[sample(nrow(df), input$SectorTime),]
  })


  # Create scatterplot object the plotOutput function is expecting
  output$plot <- renderPlotly({
    point <- format_format(big.mark = " ", decimal.mark = ",", scientific = FALSE)


    p <- ggplot(data = dataset(), aes_string(x = input$x, y = input$y, col = input$z)) +
      geom_point(alpha = input$alpha, size = 2, shape = 1)  +  theme_minimal() +
      ggtitle("Scatter plot between various variables") +scale_x_continuous(labels = point) + scale_y_continuous(labels = point)
    p +  theme(axis.text.x = element_text(angle = 30)) 

  })
   output$moviestable <- DT::renderDataTable({
    movies_sample <- df %>%
      sample_n(input$n) %>%
      select(title: AerageVotesCat)
    DT::datatable(data = movies_sample, 
                  options = list(pageLength = 30), 
                  rownames = FALSE)
  })

 }

# Create the Shiny app object
shinyApp(ui = ui, server = server)

这显然不是我的完整代码。我知道问题出在此处。非常感谢您的帮助。

【问题讨论】:

  • Hasan,请对如何以有用的方式提出问题进行一些研究。 StackOverflow 的 R page 的索引页特别指出 “使用 dput() 表示数据并使用 library() 调用指定所有非基础包。不要为数据或代码嵌入图片,而是使用缩进代码块。”。所以使用dput(head(x)),因为很多人(包括我)不会将数据图像转录成要测试的东西。其他参考:stackoverflow.com/questions/5963269stackoverflow.com/help/mcvestackoverflow.com/tags/r/info
  • ... 但我的第一个猜测是让您阅读sample 的第二个参数的作用。它确实猜测您想要对特定列的数据行进行采样以在其中包含一个或多个值。也许用df[ df$yr &gt;= input$SectorTime[1] &amp; df$yr &lt;= input$SectorTime[2],,drop=FALSE]替换sample(nrow(df),input$SectorTime),]
  • 嗨。道歉。我正在努力整理我的数据。您提到的这段代码给了我一个空白输出。所以只是一个白屏
  • 它可能会出现白屏,因为我不知道您的年份列的名称(现在您提供了数据,我知道它是 $release_year)。我曾使用$yr 作为占位符。你改了还是失败了?
  • 太棒了!作品!过去一周一直坚持这一点。谢谢!

标签: r ggplot2 shiny plotly reactive


【解决方案1】:

您的问题是您误用了sample:第二个参数通常是样本大小,而不是要从中过滤的字段。鉴于您的数据,它应该适用于:

  dataset <- reactive({
    df[input$SectorTime[1] <= df$release_year &
        df$release_year <= input$SectorTime[2]  ,,drop=FALSE]
  })

如果您已经在工作流程中使用dplyrdata.table 包,则两者都有一个between 函数,可以简化上述代码(尽管它们并不快)。


更新

我已经修复了你的大部分代码,现在你的“导演过滤器”可以正常工作了。在缩减中,我删除了与问题无关的东西(额外的包,不需要影响任何过滤的图)并提出了这个缩减集。 (我将由您来回填已移除的组件。)

# library(gifski)
# library(gganimate)
library(dplyr)
library(DT)
#library(shinythemes)
# library(scales)
library(shiny)
# library(ggplot2)
# library(plotly)

n_total <- nrow(df)

ui <- fluidPage(
  titlePanel("Movie browser, 1960 - 2014", windowTitle = "Movies"),   
  # Sidebar layout with a input and output definitions
  sidebarLayout(
    # Inputs
    sidebarPanel(
      wellPanel(
        sliderInput("SectorTime", h4("Select a time period:"), min = 1960, max = 2015,
                    value = c(1960,2015), step = 5),
        textInput("Director", h4("Director name contains (e.g., Miyazaki)")),
        numericInput(inputId = "n",
                     label = h4("Sample size:"),
                     value = 30,
                     min = 1, max = n_total,
                     step = 1)
      )
    ),
    # Outputs
    mainPanel(
      tabsetPanel(
        tabPanel(h4("PLOT"), #plotlyOutput("plot"),
                 tabPanel(h4("DATA"), DT::dataTableOutput(outputId = "moviestable", width = 500))
                 )
      )
    )
  )
)

server <- function(input, output) {
  dataset <- reactive({
    req(input$SectorTime, !is.null(input$Director))
    df[input$SectorTime[1] <= df$release_year &
         df$release_year <= input$SectorTime[2] &
         grepl(input$Director, df$director, ignore.case = TRUE),, drop=FALSE]
  })
  output$moviestable <- DT::renderDataTable({
    req(input$n, dataset())
    movies_sample <- dataset() %>%
      sample_n(min(input$n, n())) %>%
      select(title: AerageVotesCat)
    DT::datatable(data = movies_sample, 
                  options = list(pageLength = 30), 
                  rownames = FALSE)
  })
}

有些事情你还没有做:

  • 所有表格和绘图都必须使用过滤后的数据,您的表格使用的是原始 df 数据
  • 采样不能超过帧的大小,你会很乐意允许用户将input$n设置在数据的有效大小之上
  • 我鼓励您使用 req(...) 函数,以便在先决条件稳定之前不会触发块
  • (错字:AverageVotesCatAerageVotesCat

此外,我假设您的“导演过滤器”类似于模式而不是完全匹配(因此使用 grepl)。


&lt;rant&gt;

关于在 SO 上提问的评论,不需要回答这个特定问题:

  1. 对于以后的问题,提供一个完整的工作示例很重要:在上面,您的代码在中间和末尾都缺少括号。 (对于您的代码和您的 dput 输出。)在 新的 R 会话 中提出您的问题并尝试它会有所帮助,看看会发生什么。这样做,您会看到回答者在尝试帮助您时必须处理的无关问题。当我尝试其他人的代码时,如果我在问题代码中发现拼写错误,我通常会立即将问题视为“他们不知道问题到底是什么”或“OP不关心我们的时间,要求我们做的比需要的更多”。后者似乎很快就能判断,但我的时间对我来说很宝贵,所以我必须适当地分配它。

  2. 此外,它确实有助于提供一个最小工作示例。在这种情况下,问题与基本过滤有关,因此不需要绘图(ggplot2plotly)和主题(shinythemes)。同样,gifskigganimatescales 完全未使用。当我看到我的机器上没有安装“必需的包”时,我经常会跳过问题,如果没有其他原因,我不想安装我不需要的 cruft。 减少您的代码。如果代码因为滚动出代码窗格而没有立即可见,您应该向自己证明为什么您的问题需要额外的代码。

  3. “不起作用” 向我暗示,它当然需要更多的时间和注意力。但如果没有方向(例如,错误消息、警告、“丢失数据”、某事),您就要求进行端到端调试。通常这并不难,因为弹出的第一个警告/错误通常很明显,但警告/错误通常足够明显(对某些人来说)它可以在评论中解决,但必须加载所有代码/更改,修复代码(粘贴不正确),然后尝试找出我认为是提问者模糊“不起作用”的原因。

请记住,要获得答案,您有责任提供一个好的/简短/完整的问题,而不是我们解决不完整或不必要的冗长问题。

&lt;/rant&gt;

【讨论】:

  • 最后一个问题如何使用我的文本输入“director”过滤掉我的数据框?例如,在导演姓名中计时,DF 会在 SHINY 上自动更新!
  • ... &amp; (df$director == "" | df$director == input$Director) ?
  • 服务器中有这样的东西吗? output$moviestable &lt;- DT::renderDataTable({ movies_sample &lt;- df %&gt;% sample_n(input$n) &amp; (df$director == "" | df$director == input$Director) %&gt;% select(title: AerageVotesCat) DT::datatable(data = movies_sample, options = list(pageLength = 30), rownames = FALSE)
  • 或者你的意思是这样的?尽管dataset &lt;- reactive({ df[df$release_year &gt;= input$SectorTime[1] &amp; df$release_year &lt;= input$SectorTime[2] &amp; (df$director == "" | df$director == input$Director),,drop=FALSE] }) 两者都不起作用
  • “两者都不工作”对我来说不好如何? 您收到什么错误消息?理解我的沮丧,你没有付出任何努力(更不用说你上面的代码不完整/不正确,缺少括号,并非所有这些看起来都是“最后”)。
猜你喜欢
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
  • 2010-12-31
  • 2012-07-13
相关资源
最近更新 更多