Search code examples
rplotly

Can't customize the hoverinfo in plotly plot created with sf object


Here is the code I am using from the tutorial here https://blog.cpsievert.me/2018/03/30/visualizing-geo-spatial-data-with-sf-and-plotly/:

library(plotly)
data(franconia, package = "mapview")

plot_ly(
  franconia,
  split = ~NUTS_ID,
  color = ~district,
  stroke = I("black"),
  text = ~paste("This is text and",NAME_ASCI, "\n is in", district), 
  hoverinfo = "text",
  hoveron = "fill"
)

I want the text in the hover tooltip to be the text attribute. However, when I run this, the text in the hover tooltip is the split attribute.

enter image description here


Solution

  • I believe the hoveron value should be "fills":

    library(plotly)
    data(franconia, package = "mapview")
    
    plot_ly(
      franconia,
      split = ~NUTS_ID,
      color = ~district,
      stroke = I("black"),
      text = ~paste("This is text and",NAME_ASCI, "\n is in", district), 
      hoverinfo = "text",
      hoveron = "fills"
    )
    #> No trace type specified:
    #>   Based on info supplied, a 'scatter' trace seems appropriate.
    #>   Read more about this trace type -> https://plotly.com/r/reference/#scatter
    

    There are quite a few hoveron = "fill" references out there, I guess this is something that has changed at some point, though there are also up to date examples like https://plotly-r.com/maps#cb63-1 .

    In this particular case the No trace type specified notice and a link to reference is quite handy. Well, the single page ref can get confusing for searching, so this variant is bit better - https://plotly.com/r/reference/scatter/#scatter-hoveron . And it lists "points", "fills", "points+fills" as available options.

    I don't know such syntax details by heart, but not so long ago I had my own Plotlyl struggles and from that session recalled something about "/../ fill and fills behaving differently /../" . It was this issue - https://github.com/plotly/plotly.R/issues/1260.