chungkim271
chungkim271

Reputation: 967

making a main title in ggvis chart interactive with Shiny input

I have a ggvis chart in my shiny app whose title I would like to be interactive with the user input.

following this post: Add a plot title to ggvis, I was able to add a title to my chart, but apparently making it interactive is not as simple as I thought.

below is the minimal reproducible example.

library(shiny)
library(ggvis)

example <- data.frame(a=c("apple", "pineapple", "grape", "peach"), b=11:14)

ui <- fluidPage (
    selectInput(inputId="option",
                label=NULL,
                choices= levels(example$a),
                selected="apple"),
    ggvisOutput("chart")
)

server <- function(input, output) {
    dataTable <- reactive({
        df <- example[example$a==input$option, ]
        df
    })

    ggvis(data=dataTable, x=~a, y=~b) %>%
        layer_bars() %>%
        add_axis("x", title="fruits") %>%
        add_axis("x", orient = "top", ticks = 0, title = "???", #I want: paste("chosen option is", input$option),
                 properties = axis_props(
                     axis = list(stroke = "white"),
                     labels = list(fontSize = 0))) %>%
        bind_shiny("chart")
}

shinyApp(ui=ui, server=server)

Thank you for your help.

Upvotes: 1

Views: 316

Answers (1)

John Paul
John Paul

Reputation: 12664

For your server, do this:

server <- function(input, output) {
    dataTable <- reactive({
        df <- example[example$a==input$option, ]
        df
    })
    observe({
      ggvis(data=dataTable, x=~a, y=~b) %>%
        layer_bars() %>%
        add_axis("x", title="fruits") %>%
        add_axis("x", orient = "top", ticks = 0, 
                 title = paste("chosen option is", input$option),
                 properties = axis_props(
                     axis = list(stroke = "white"),
                     labels = list(fontSize = 0))) %>%
        bind_shiny("chart")
   })
}

The observe puts this all in a "reactive context" which allows you to use input$option in your plot. Without the observe shiny does not understand how to deal with the reactivity in your plot.

Upvotes: 1

Related Questions