Обновление графика из интерактивной таблицы в html - PullRequest
0 голосов
/ 18 мая 2018

Я хотел бы иметь возможность обновить график на основе вывода из таблицы (DT-) после фильтрации в html .

Например - здесьэто скриншот таблицы, отфильтрованной для maz в html:

enter image description here

Я бы хотел, чтобы график рассеяния обновлялся только для отображениязначения показаны в отфильтрованной таблице.

Возможно ли это?Я знаю, что могу добиться чего-то подобного, используя блестящее веб-приложение , но возможно ли для этого встроить какой-нибудь блестящий код в html?(У меня очень ограниченный опыт использования глянцевого / html, поэтому буду благодарен за любые советы / идеи).

Я использую R-markdown (а здесь - ссылка на созданный html ):

---
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
```

1 Ответ

0 голосов
/ 19 мая 2018

Вопреки моей первой оценке, это действительно возможно.Есть несколько дополнений к вашему коду.Я расскажу их в хронологическом порядке:

  1. Вам нужно добавить runtime: shiny в заголовок yaml, чтобы начать блестеть в любом файле R-markdown
  2. Необязательно: я добавил немного стиля CSSна случай, если вам нужно настроить блестящее приложение, чтобы оно соответствовало определенным размерам экрана
  3. Shiny-документы содержат UI-часть, где вы настраиваете пользовательский интерфейс.Обычно вы просто используете fluidPage функцию для этого
  4. Следующая часть - это server.r -часть, где происходит интересное:
    • Мы присваиваем, т. Е. Ваш DT::datatableoutput -объект (обычно список)
    • Для каждого назначения нам нужно установить shinyID, который мы настраиваем в ui.r, а затем добавить, то есть output$mytable
    • Iдобавлен element, который показывает, какие строки выбраны для отладки
    • Сердцем всех изменений является input$mytable_rows_all.Все элементы управления, которые мы установили в ui.r, могут вызываться внутри render -функций.В данном конкретном случае mytable относится к shinyID, которое я установил для DT::datatable в UI-части, а rows_all говорит блестящему взять все числа в показанной таблице.
    • Таким образом, мы просто подставляем данные с помощью mtcars[input$mytable_rows_all,]

Чтобы научиться блестящему, я рекомендую Учебное пособие по Rstudio .После изучения и повторного забывания я советую вам воспользоваться замечательной таблицей , предоставленной 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
})
```
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...