【问题标题】:Update plot from interactive table in html从 html 中的交互式表格更新绘图
【发布时间】:2018-10-28 15:16:37
【问题描述】:

我想做的是在 html 中过滤后根据 (DT-) 表的输出更新绘图

例如 - 这是在 html 中为maz 过滤的表格的屏幕截图:

我希望散点图更新为仅显示过滤表中显示的值。

这可能吗?我知道我可以使用shiny web app 来实现这样的目标,但是是否可以在 html 中嵌入一些闪亮的代码来实现这一目标? (我使用 Shiny/html 的经验非常有限,因此将不胜感激任何指针/想法)。

我正在使用 R-markdown(和 here is a link to the html produced):

---
title: "Filter interative plots from table results"
date: "`r format(Sys.time(), '%B %e, %Y')`"
output:
  html_notebook:
    theme: flatly
    toc: yes
    toc_float: yes
    number_sections: true
    df_print: paged
  html_document: 
    theme: flatly
    toc: yes
    toc_float: yes
    number_sections: true
    df_print: paged
---

```{r setup, include=FALSE, cache=TRUE}
library(DT)
library(plotly)
library(stringr)
data(mtcars)
```


# Clean data
## Car names and models are now a string: "brand_model" in column 'car'

```{r include=FALSE}
mtcars$car <- rownames(mtcars)
mtcars$car <- stringr::str_replace(mtcars$car, ' ', '_')
rownames(mtcars) <- NULL
```

# Interactive table using DT

```{r rows.print=10}
DT::datatable(mtcars,
              filter = list(position = "top"),
              selection="none",                 #turn off row selection
              options = list(columnDefs = list(list(visible=FALSE, targets=2)),
                             searchHighlight=TRUE,
                             pagingType= "simple",
                             pageLength = 10,                  #default length of the above options
                             server = TRUE,                     #enable server side processing for better performance
                             processing = FALSE)) %>% 
              formatStyle(columns = 'qsec',
                background = styleColorBar(range(mtcars$qsec), 'lightblue'),
                backgroundSize = '98% 88%',
                backgroundRepeat = 'no-repeat',
                backgroundPosition = 'center')
```

# Plot disp against mpg using plotly

```{r fig.width=8, fig.height=8}
p <- plot_ly(data = mtcars,
             x = ~disp,
             y = ~mpg,
             type = 'scatter',
             mode = 'markers',
             text = ~paste("Car: ", car, "\n",
                           "Mpg: ", mpg, "\n"),
             color = ~mpg,
             colors = "Spectral",
             size = ~-disp
)
p
```

【问题讨论】:

  • (p.s. 如果有人对我如何最好地共享 .Rmd 和 .html 文件以更好地理解问题有任何建议,我很想听听他们的意见!)
  • 遗憾的是不能直接完成。问题是 DT - 过滤器不会转化为闪亮。但是您可以使用闪亮的过滤器。将在一小时内上传我的版本。
  • @5th - 这将非常有帮助!
  • 好的,这里的防火墙阻止了我。那得等到我回家了。
  • 原来我错了,你可以直接做。我更改了您的代码并将其上传到下面作为答案。这样看起来更容易

标签: css r shiny plotly r-plotly


【解决方案1】:

与我的第一个评估相反,这实际上是可能的。您的代码有多项添加。我将按时间顺序浏览它们:

  1. 您需要在 yaml-header 中添加 runtime: shiny 以在任何 R-markdown 文件中开始闪亮
  2. 可选:我添加了一些 css 样式,以防您需要调整闪亮的应用程序以适应特定的屏幕尺寸
  3. Shiny-documents 包含一个 UI 部分,您可以在其中配置用户界面。通常您只需为此使用 fluidPage 函数
  4. 下一部分是server.r-部分,有趣的事情发生了:
    • 我们将您的DT::datatable 分配给output 对象(通常是一个列表)
    • 对于每个分配,我们需要设置一个shinyID,我们在ui.r 中配置,然后添加,即output$mytable
    • 我添加了一个element,它显示选择了哪些行进行调试
    • 所有更改的核心是input$mytable_rows_all。我们在ui.r 中设置的所有控件都可以在render 函数中调用。在这种特殊情况下,mytable 指的是我在 UI 部分中为DT::datatable 设置的shinyIDrows_all 告诉闪亮获取所示表中的所有行号。
    • 这样我们只需使用mtcars[input$mytable_rows_all,] 对数据进行子集化

要学习闪亮,我推荐Rstudio's tutorial。在再次学习并忘记一切后,我建议您使用wonderful cheatsheet provided by Rstudio

整个修改后的代码如下:

---
title: "Filter interative plots from table results"
date: "`r format(Sys.time(), '%B %e, %Y')`"
runtime: shiny
output:
  html_document: 
    theme: flatly
    toc: yes
    toc_float: yes
    number_sections: true
    df_print: paged
  html_notebook:
    theme: flatly
    toc: yes
    toc_float: yes
    number_sections: true
    df_print: paged
---

<style>
 body .main-container {
    max-width: 1600px !important;
    margin-left: auto;
    margin-right: auto;
  }
</style>

```{r setup, include=FALSE, cache=TRUE}
library(stringr)
data(mtcars)
```


# Clean data
## Car names and models are now a string: "brand_model" in column 'car'

```{r include=FALSE}
mtcars$car <- rownames(mtcars)
mtcars$car <- stringr::str_replace(mtcars$car, ' ', '_')
rownames(mtcars) <- NULL
```



# Plot disp against mpg using plotly

```{r}
library(plotly)
library(DT)

## ui.r
motor_attributes=c('Cylinder(  shape): V4','Cylinder(  shape): V6','Cylinder(  shape): V8','Cylinder(  shape): 4,Straight Line','Cylinder(  shape): 6,Straight Line','Cylinder(  shape): 8,Straight Line','Transmission: manual','Transmission: automatic')

fluidPage(# selectizeInput('cyl','Motor characteristics:',motor_attributes,multiple=TRUE,width='600px'),
          downloadLink('downloadData', 'Download'),
          DT::dataTableOutput('mytable'),
          plotlyOutput("myscatter"),
          htmlOutput('Selected_ids'))


### server.r
output$mytable<-DT::renderDataTable({
  DT::datatable(mtcars,
              filter = list(position = "top"),
              selection='none', #list(target='row',selected=1:nrow(mtcars)),                 #turn off row selection
              options = list(columnDefs = list(list(visible=FALSE, targets=2)),
                             searchHighlight=TRUE,
                             pagingType= "simple",
                             pageLength = 10,                  #default length of the above options
                             server = TRUE,                     #enable server side processing for better performance
                          processing = FALSE))   %>% 
              formatStyle(columns = 'qsec',
                background = styleColorBar(range(mtcars$qsec), 'lightblue'),
                backgroundSize = '98% 88%',
                backgroundRepeat = 'no-repeat',
                backgroundPosition = 'center')
})


output$Selected_ids<-renderText({
  if(length(input$mytable_rows_all)<1){
      return()
  }

  selected_rows<-as.numeric(input$mytable_rows_all)  
  paste('<b> #Cars Selected: </b>',length(selected_rows),'</br> <b> Cars Selected: </b>',
        paste(paste('<li>',rownames(mtcars)[selected_rows],'</li>'),collapse = ' '))

})

output$myscatter<-renderPlotly({
  selected_rows<-as.numeric(input$mytable_rows_all)  
  subdata<-mtcars[selected_rows,]
  p <- plot_ly(data = subdata,
             x = ~disp,
             y = ~mpg,
             type = 'scatter',
             mode = 'markers',
             text = ~paste("Car: ", car, "\n",
                           "Mpg: ", mpg, "\n"),
             color = ~mpg,
             colors = "Spectral",
             size = ~-disp
)
p
})
```

【讨论】:

  • 这非常有用 - 谢谢。当我运行此代码时,它以Error in output$myscatter &lt;- renderPlotly({ : object 'output' not found 失败。 ui.Rserver.R 是否应该保存到单独的文件中?
  • 对我来说它有效。您可以尝试将从 fluidPage-function 开始的块保存到 app.r 并加载它。但是,您需要将fluidPage 的输出分配给一个名为ui 的对象,对于服务器部分,您需要将代码包装到这个东西的括号中:server &lt;- function(input, output) { }。您还需要shinyApp(ui,server) 来调用所有内容。最好查看基本的闪亮教程 - 只需十分钟。
  • 部署app.r 尝试使用shinyAppDir-function。您还可以尝试为您的 R 版本添加服务器和 ui 功能是否有效
猜你喜欢
  • 1970-01-01
  • 2018-04-28
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 2012-01-05
  • 2018-07-27
相关资源
最近更新 更多