1

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.

Community
  • 1
  • 1
chungkim271
  • 927
  • 1
  • 10
  • 20
  • You can put it the title just as you want with paste. However, you need to wrap the `ggvis` part from `ggivs(...` through the `bind_shiny` in an `observe({})` for this to work. – John Paul May 24 '16 at 16:59
  • I don't understand. Could you provide a skeleton of code? I haven't used observe() in Shiny yet... also, do you know why this is throwing error? – chungkim271 May 24 '16 at 17:27

1 Answers1

1

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.

John Paul
  • 12,196
  • 6
  • 55
  • 75
  • the code didn't work with add_axis("x", orient = "top", ticks = 0, title = dataTable()$a[1], either. It seems odd to me because dataTable()$a[1] is a fixed string once it runs through the reactive function. (I also tried with dataTable$a[1] to no avail) – chungkim271 May 24 '16 at 18:01