cssggiraph

set css property separately for each layer on hover (ggiraph)


Using ggiraph, I'd like to set css properties differently for each ggplot geom_ or layer using hover. In the example below, how might I set the stroke for the second geom_rect_interactive to blue on hover but keep the first layer stroke red on hover (keeping the data_id the same so both respond to hovering over either layer)?

library(ggplot2)
library(ggiraph)
p <- 
  ggplot(
  data = data.frame(id = seq(3), x = 1:3, y = 1:3)
) +

  # red stroke
  geom_rect_interactive(
    mapping = aes(
      xmin = x, xmax = x - 0.1,
      ymin = y, ymax = y - 0.1,
      data_id = id
    )
  ) +

  # blue stroke
  geom_rect_interactive(
    mapping = aes(
      xmin = x, xmax = x + 0.1,
      ymin = y, ymax = y + 0.1,
      data_id = id
    )
  )

x <- girafe(ggobj = p)
x <- girafe_options(
  x,
  opts_hover(
    css = "stroke:#ff0000;"
  )
)
x

I'm guessing I might be able to do something like assign some custom css class to a particular layer (e.g., .mystroke {stroke:#0000ff;}) but not sure how to approach this.


Solution

  • (I am one of the authors) This is not currently possible, we have not considered this case (we will if we can implement it).

    For the moment, it is only possible to specify a CSS per shape type. An example will be more meaningful, it is copied from:

    https://davidgohel.github.io/ggiraph/articles/offcran/customizing.html#detailled-control-1

    library(ggplot2)
    library(ggiraph)
    
    
    dataset <- mtcars
    dataset$carname <- row.names(dataset)
    
    gg_scatter <- ggplot(dataset, aes(x = disp, y = qsec, label = carname, 
      data_id = carname, color= wt) ) + 
      geom_point_interactive(size=3) + 
      geom_text_interactive(vjust = 2) +
      theme_minimal()
    
    girafe(ggobj = gg_scatter2, 
      options = list(
        opts_hover(
        css = girafe_css(
          css = "fill:purple;stroke:black;",
          text = "stroke:none;fill:red;"
        )
      )
      ) )