rggplot2ggiraph

scale_interactive onclick event printed in console


I've build a shiny app with an interactive legend using the scale_fill_manual_interactive function from the beautiful ggiraph package. However, I would like to print the information(male or female, depending on selection) from the onclick event to console. Here is the code snippet.

library(ggplot2)
library(ggiraph)

dat <- data.frame(
  name = c( "Guy", "Ginette", "David", "Cedric", "Frederic" ),
  gender = c( "Male", "Female", "Male", "Male", "Male" ),
  height = c(169, 160, 171, 172, 171 ) )

p <- ggplot(dat, aes( x = name, y = height, fill = gender,
                      data_id = name ) ) +
  geom_bar_interactive(stat = "identity")

p3 <- p +
  scale_fill_manual_interactive(
    name = label_interactive("gender", tooltip="Gender levels", data_id="legend.title"),
    values = c(Male = "#0072B2", Female = "#009E73"),
    data_id = function(breaks) { as.character(breaks)},
    tooltip = function(breaks) { as.character(breaks)},
    onclick = function(breaks) { cat( as.character(breaks)) }
  )
x <- girafe(ggobj = p3)
x <- girafe_options(x,
                    opts_hover_key(girafe_css("stroke:red", text="stroke:none;fill:red")))
if (interactive()) print(x)

now it only prints the entire list

Female Male

instead of only the one selected.


Solution

  • This should answer your question. It will print in the R console the last clicked key. A reactive value is available to get clicked key, its ID is plot_key_selected: the ggiraph ID + _key_selected

    library(shiny)
    library(ggplot2)
    library(ggiraph)
    
    gg <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
        geom_point_interactive( size = 3 ) + theme_minimal() +
        scale_colour_manual_interactive(
            data_id = c("setosa" = "setosa", "versicolor" = "versicolor", "virginica" = "virginica"),
            tooltip = c("setosa" = "setosa", "versicolor" = "versicolor", "virginica" = "virginica"),
            values = c("setosa" = "purple", "versicolor" = "blue", "virginica" = "darkgreen")
            )
    
    ui <- fluidPage(
    
        sidebarLayout(
            sidebarPanel(
            ),
            mainPanel(
                ggiraph::ggiraphOutput("plot")
            )
        )
    )
    
    server <- function(input, output) {
        output$plot <- renderggiraph({
            x <- girafe(code = print(gg), width_svg = 6, height_svg = 8)
            x
        })
        observe({
            print(input$plot_key_selected)
        })
    }
    
    shinyApp(ui = ui, server = server)