Created
October 18, 2022 14:01
-
-
Save h-a-graham/17fbc90f6afa042f878099668bce58e1 to your computer and use it in GitHub Desktop.
plotly labels with raster and sf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much, this works perfectly.