Skip to content

Instantly share code, notes, and snippets.

@h-a-graham
Created October 18, 2022 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h-a-graham/17fbc90f6afa042f878099668bce58e1 to your computer and use it in GitHub Desktop.
Save h-a-graham/17fbc90f6afa042f878099668bce58e1 to your computer and use it in GitHub Desktop.
plotly labels with raster and sf
#https://twitter.com/AnalyticalEdge/status/1582206425585324034
library(ggplot2)
library(stars)
library(sf)
library(dplyr)
library(plotly)
.d <- dim(volcano)
d1 <- expand.grid(x = 1:.d[1], y = 1:.d[2])
volcano_df <- transform(d1, z = volcano[as.matrix(d1)])
volcano_sf <- st_as_stars(volcano) |>
mutate(a = case_when(A1>190 ~ 1,
A1<180 & A1 > 160 ~ 2,
TRUE ~NA_real_)) |>
select(a) |>
st_as_sf(merge=TRUE) |>
mutate(.label = case_when(a==1~ "label-1",
a==2~ "label-2"))
p <- ggplot()+
geom_raster(data=volcano_df, aes(x=x, y=y, fill=z)) +
geom_sf(data=volcano_sf, aes(text=.label), fill=1:2, inherit.aes = FALSE, alpha=0.7) +
theme_light()
p2 <- ggplotly(p, tooltip='text')|>
style(hoverlabel = list(bgcolor="white"),
hoveron='fill')
p2
@TheAnalyticalEdge
Copy link

Thank you very much, this works perfectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment