How to plot linestring geometry with R plotly?

Viewed 29

I can do this if I go through ggplotly() first:

rivers <- RCzechia::reky("Brno")
p <- ggplot() + geom_sf(data = rivers)
ggplotly(p)

But when I try the same thing with plot_ly(), it only displays a straight line:

plot_ly() %>% add_sf(data = rivers, type = "scatter")

What do I need to do for the second approach to work?

1 Answers

I converted the data to sf coordinates and used the ggplotly you built to capture the aspect ratio.

plt <- ggplotly(p)

newRiver <- sf::st_coordinates(rivers) %>% as.data.frame(). # help plotly understand
plot_ly(type = "scatter", mode = "lines",
        x = ~X, y = ~Y, split = ~L1, data = newRiver) %>% 
  layout(xaxis = list(scaleratio = plt$x$layout$xaxis$scaleratio,  # set aspect ratio
                      scaleanchor = "y"))

enter image description here

Related