mustafa00
mustafa00

Reputation: 891

How to dynamically change chart type?

I want to change chart type from e_line to e_bar based on a condition.
What I tried to do was using some reactive expression or if else inside plot, but neither of them works. Any ideas how to tackle this?

So, I need to change dynamically e_line, I tried this:

      newChartType <- reactive({
        df = switch(
           someCondition,
          '1' = echarts4r::e_line(ColumnName2),
          '2' = echarts4r::e_bar(ColumnName2)
         )        
      }) 

      output$plot <- echarts4r::renderEcharts4r({
        dataChartStats() %>% 
          echarts4r::e_charts(ColumnName1) %>% 
          newChartType() %>% 
          echarts4r::e_legend(show = FALSE)  
      })

but it doesn't work. I'm interested in general rule on how to change dynamically building elements of plot code (can be ggplot as well etc, here I used echarts4r).

Upvotes: 0

Views: 261

Answers (1)

Limey
Limey

Reputation: 12496

I couldn't find a way of obtaining the chart type directly from an input element, but here's one way of doing it:

library(shiny)
library(tidyverse)

ui <- fluidPage(
  selectInput(
    "type", 
    "Select a chart type:", 
    c("point", "line")),
  plotOutput("plot")
)

server <- function(input, output) {
  output$plot <- renderPlot({
     if (input$type == "line") {
       mtcars %>% ggplot() + geom_line(aes(x=mpg, y=disp))
     } else {
       mtcars %>% ggplot() + geom_point(aes(x=mpg, y=disp))
     }
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

Next time, please provide a minimum working example.

EDIT in response to OP's request for a solution based on a button click:

library(shiny)
library(tidyverse)

ui <- fluidPage(
  actionButton("go", "Click me!"),
  textOutput("type"),
  # selectInput(
  #   "type", 
  #   "Select a chart type:", 
  #   c("point", "line")),
  plotOutput("plot")
)

server <- function(input, output) {
  v <- reactiveValues(type="line")
  
  observeEvent(input$go, {
    if (v$type  == "line") v$type <- "point"
    else v$type <- "line"
  })
  
  output$type <- renderText({ v$type })

  output$plot <- renderPlot({
    if (v$type == "line") {
      mtcars %>% ggplot() + geom_line(aes(x=mpg, y=disp))
    } else {
      mtcars %>% ggplot() + geom_point(aes(x=mpg, y=disp))
    }
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions