ipeaGIT / geobr

Easy access to official spatial data sets of Brazil in R and Python
https://ipeagit.github.io/geobr/
786 stars 118 forks source link

cities map not working with `plotly` #279

Closed GitHunter0 closed 1 year ago

GitHunter0 commented 2 years ago

Hi folks, for some reason the cities map is not working with plotly (while others like regions map are working flawlessly). Any idea what is happening?

library(plotly)
library(geobr)
map_regions <- geobr::read_region(year=2010) |> sf::st_cast("MULTIPOLYGON")
map_cities <- geobr::read_municipality(code_muni="all", year=2010) |> sf::st_cast("MULTIPOLYGON")

While this works:

plot_ly() %>% add_sf(data = map_regions) 

This returns Error in `[.data.frame`(x, i) : undefined columns selected:

plot_ly() %>% add_sf(data = map_cities) 
R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252 
[2] LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    
system code page: 65001

attached base packages:
[1] stats     graphics  grDevices utils    
[5] datasets  methods   base     

other attached packages:
[1] geobr_1.6.6   plotly_4.10.0 ggplot2_3.3.5

Thank you

rafapereirabr commented 2 years ago

Hi @GitHunter0 . Thanks for opening this issue. There could be some kind of conflict with data.table, but I'm not sure why.

library(plotly)
library(magrittr)
library(sf)
library(geobr)

# note the object has multiple classes
map_cities <- geobr::read_municipality(code_muni="all", year=2010)
class(map_cities)
> [1] "sf"         "data.table" "data.frame"

If if try plot_ly(), we get the error you pointed out.

plot_ly() %>% add_sf(data = map_cities) 

> Error in `[.data.frame`(x, i) : undefined columns selected

Now, when we remove the data.table class, then plot_ly() works.

map_cities <- as.data.frame(map_cities) %>% st_sf()
class(map_cities)
> [1] "sf"         "data.frame"

plot_ly() %>% add_sf(data = map_cities) 

This looks a bit strange, to be honest. It looks like a bug on plotly, but I cannot really grasp why it happens.

GitHunter0 commented 2 years ago

Hey @rafapereirabr , it makes some sense I believe, AFAIK data.table has compatibility issues with sf.

Probably map_cities should not have data.table class as default, since other maps from geobr like map_regions (from the example above) do not have it.

But I'm glad you found a workaround, thank you.

rafapereirabr commented 2 years ago

Yes, I should proabably remove the data.table class from the data. I'll keep this issue open and will add this to my task list. Thanks,

rafapereirabr commented 1 year ago

Fixed in dev version with 45b99a20 .