Come creare un grafico grafico delle variabili selezionate da un utente in shiny o flexdahsboard?

Aug 23 2020

Sono abbastanza nuovo in R e sto cercando di mettere insieme un flexdashboard che prenda le variabili x e y dagli input dell'utente e restituisca un grafico di quei valori. Finora sono in grado di generare i grafici desiderati utilizzando ggplotly nel codice sottostante.

output$scatter <-renderPlotly({
  
  cat('input$x=',input$x,'\n')
  cat('input$y=',input$y,'\n')
  p <- ggplot(Merged_data_frame_hcat, aes_string(x=input$x, y=input$y)) +
       geom_point()+
       theme_minimal(base_size = 14) 
  g <- ggplotly(p, source = 'source') %>%
       layout(dragmode = 'lasso',
       margin = list(l = 100),
       font = list(family = 'Open Sans', size = 16))
})

Tuttavia, mi sono reso conto che con ggplotly il mio asse x non era così definito come quando ho usato plot_ly per rappresentare graficamente le stesse variabili al di fuori della dashboard.
C'è un modo per usare plot_ly all'interno di una flexdashboard. Finora ho scritto questo ma non ha funzionato. A proposito, sto usando noquote qui perché plot_ly non accettava bene i nomi di input che erano stringhe

output$scatter <-renderPlotly({
  
  cat('input$x=',input$x,'\n')
  cat('input$y=',input$y,'\n')
  if (length(input$y) == 2){
     x1 = noquote(input$x)
     y1 =noquote(input$y[1])
     y2 = noquote(input$y[2])
  
   plot_ly(Merged_data_frame_hcat)%>%
     add_lines(x= ~x1,y =~y1, name = "Red") 
     add_lines(x= ~x1, y =~y2, name = "Green")
   }
})

Prima che me ne dimentichi, ecco un esempio del mio frame di dati che ho ridotto per semplicità

df <-data.frame("Timestamp.Excel_1900."=c("2019-04-01 16:52:51","2019-04-01 16:57:46","2019-04-01 17:02:51","2019-04-01 17:07:46","2019-04-01 17:12:52","2019-04-01 17:17:46"), "Temperature.C."= c(5.2995,5.3155,5.3353,5.3536,5.3770,5.4044), "pH.pH."= c(7.60,7.80,7.96,8.04, 8.09, 8.14))

Risposte

3 stefan Aug 23 2020 at 16:50

Ci sono diversi approcci per fare questo lavoro. Sfortunatamente il tuo approccio usando noquotenon funziona.

  1. Probabilmente l'approccio più semplice sarebbe quello di estrarre le colonne dal tuo df e passarle plotlycome vettori, ad esx = df[[input$x]]
  2. Poiché l' plotlyAPI funziona con una formula unilaterale, un secondo approccio sarebbe quello di passare le variabili come formule, ad esx = as.formula(paste0("~", input$x))
  3. Seguendo questo post puoi anche utilizzare base::get, ad esx = ~get(input$x)
  4. Seguendo questo post puoi anche utilizzare la valutazione ordinata

Tutti e quattro gli approcci sono illustrati nel seguente esempio di flexdashboard:

---
title: "Plotly"
output: flexdashboard::flex_dashboard
runtime: shiny
---

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

```{r global, include=FALSE}
# load data in 'global' chunk so it can be shared by all users of the dashboard
df <- data.frame("Timestamp.Excel_1900." = c("2019-04-01 16:52:51","2019-04-01 16:57:46","2019-04-01 17:02:51","2019-04-01 17:07:46","2019-04-01 17:12:52","2019-04-01 17:17:46"), "Temperature.C."= c(5.2995,5.3155,5.3353,5.3536,5.3770,5.4044), "pH.pH."= c(7.60,7.80,7.96,8.04, 8.09, 8.14))

```

Column {.sidebar}
-----------------------------------------------------------------------

```{r}
selectInput("x",
  "x",
  choices = names(df),
  selected = "Timestamp.Excel_1900."
)
selectizeInput("y",
  "y",
  choices = names(df),
  selected = c("Temperature.C.", "pH.pH."),
  multiple = TRUE,
  options = list(maxItems = 2)
)
```

Column
-----------------------------------------------------------------------

```{r}
# Pass the data columns as vectors
renderPlotly({
  if (length(input$y) == 2) {
    x1 <- df[[input$x]]
    y1 <- df[[input$y[1]]]
    y2 <- df[[input$y[2]]]

    plot_ly() %>%
      add_lines(x = x1, y = y1, name = "Red") %>%
      add_lines(x = x1, y = y2, name = "Green")
  }
})
```

```{r}
# One-sided formulas
renderPlotly({
  if (length(input$y) == 2) {
    x1 <- input$x
    y1 <- input$y[1]
    y2 <- input$y[2]

    plot_ly(df) %>%
      add_lines(x = as.formula(paste("~", x1)), y = as.formula(paste("~", y1)), name = "Red") %>%
      add_lines(x = as.formula(paste("~", x1)), y = as.formula(paste("~", y2)), name = "Green")
  }
})
```

Column
-----------------------------------------------------------------------

```{r}
# Using base::get
renderPlotly({
  if (length(input$y) == 2) {
    x1 <- input$x
    y1 <- input$y[1]
    y2 <- input$y[2]

    plot_ly(df) %>%
      add_lines(x = ~ get(x1), y = ~ get(y1), name = "Red") %>%
      add_lines(x = ~ get(x1), y = ~ get(y2), name = "Green")
  }
})
```

```{r}
# Using tidy evaluation
renderPlotly({
  if (length(input$y) == 2) {
    x1 <- input$x
    y1 <- input$y[1]
    y2 <- input$y[2]

    eval_tidy(
      quo_squash(
        quo({
          plot_ly(df) %>%
            add_lines(x = ~ !!sym(x1), y = ~ !!sym(y1), name = "Red") %>%
            add_lines(x = ~ !!sym(x1), y = ~ !!sym(y2), name = "Green")
        })
      )
    )
  }
})
```