Search code examples
rggplot2flexdashboard

How would you generate multiple scatterplot in Flexdashboard R


I have a reactive input, which takes values from 1 to 12, what I want to achieve is a plot using one column as the x variable (always), and different columns as the y variable - The input below works fine, but obviously is hardcoded, so if I use less or more than 6 variables the plot doesn't work

ggplotly(
  ggplot(table_plot(),aes(x=Streamer_Offset)) +
    geom_point(aes(y= CMP_1, color = "Source 1"))+
    geom_point(aes(y= CMP_2, color = "Source 2"))+
    geom_point(aes(y= CMP_3, color = "Source 3"))+
    geom_point(aes(y= CMP_4, color = "Source 4"))+
    geom_point(aes(y= CMP_5, color = "Source 5"))+
    geom_point(aes(y= CMP_6, color = "Source 6"))
  
)

What I want to do is to put a vector of variables for example c(CMP_1,CMP_2....) etcetera, I have tried to use the following code to create a vector, and then pass on to a formula, but ggplot doesn't recognize the input

  l <- colnames(table_plot())
  m <- c(paste0("~",l))
  d <- m[1:length(m)-1]
  as.formula(d)

Additionaly I tried ggloop and renderPlot or renderPLotly won't work with that function, as such, I'm not sure what to do as in principle, this should not be a very complicated process.


Solution

  • It would be easier if you get the data in long format. Try this -

    library(tidyverse)
    
    ggplotly(
        ggplot(table_plot() %>% pivot_longer(cols = -Streamer_Offset),
               aes(x=Streamer_Offset, y = value, color = name))
    )