rggplot2plotlyr-plotlygghighlight

Is there a way to have a highlighted chart as well as have interactivity of selecting elements in R?


I have come across a beautiful chart on this webpage: https://ourworldindata.org/coronavirus and interested to know if we can build the same chart in R with functionality of having highlighted series as well as selecting any line on hovering ?

I have build static highlighted charts using gghighlight but those are not interactive. Plotly can help in interaction but I think they don't work with gghighlight.

So how can we have the combination of both highlight and interactivity in charts as in the link shared on top ?

Is it possible to achieve same results in R ? It would be really helpful if someone could share an example or link that can help.

(UPDATE: May be I can manually highlight lines by creating a factor column instead of using gghighlight and then pass it to ggplotly but then can ggplotly or some other library provide similar results on hover ?)

(NOTE: Not looking for animation. Just need highlighted, hover over interactive chart)

Below is the snapshot of same chart hovered over US (This chart is also similar to the one shared in World Economic Forum many times.)

enter image description here


Solution

  • Using plotly you can use highlight() to achive this.

    This is a slightly modified example from here:

    library(plotly)
    
    # load the `txhousing` dataset
    data(txhousing, package = "ggplot2")
    
    # declare `city` as the SQL 'query by' column
    tx <- highlight_key(txhousing, ~city)
    
    # initiate a plotly object
    base <- plot_ly(tx, color = I("black")) %>% 
      group_by(city)
    
    # create a time series of median house price
    time_series <- base %>%
      group_by(city) %>%
      add_lines(x = ~date, y = ~median)
    
    highlight(
      time_series, 
      on = "plotly_hover",
      selectize = FALSE, 
      dynamic = FALSE,
      color = "red",
      persistent = FALSE
    )
    

    result