Search code examples
rdictionaryggplot2pointrgdal

points distribution in map with ggplot


I have this files and data:

https://gofile.io/?c=JvglSo

https://pastebin.com/ePymwswn

and this script:

#open shp file
library(rgdal)
map <- readOGR(dsn= "/rj_municipios", layer = "33MUE250GC_SIR")

#open data file
ind_mapa <- read.csv("ind_mapa.csv", sep=";")

#map
library(ggplot2)
library(ggrepel)
mapdf <-fortify(map)

ggplot(data= mapdf, aes(x=long, y=lat, group=group)) +
  geom_path() +
  coord_map("mercator") +
  xlim(-42.040,-41.973)+
  ylim(-23.015, -22.949)+
  theme_bw() +
  geom_jitter(data=ind_mapa, width= .0015, height = .0015, size=3,alpha=.7,
              aes(x=lon, y=lat, group= code, color = code)) +
  geom_text_repel(data= ind_mapa, aes(x=lon, y=lat), group= code, label=ano)

with this I have two problems, the label "ano" does not appear:

Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomTextRepel, : object 'code' not found

and I used geom_jitter so that the dots don't overlap, but they get messy instead of being equally distributed over the original and central point.


Solution

  • Your label and group values need to be in an aesthetic. Your last line of code should read:

    geom_text_repel(data= ind_mapa, aes(x=lon, y=lat, group= code, label=ano))
    

    The error message received gives you a hint: geom = GeomTextRepel, : object 'code' not found. Using that, you know that it's a problem with the geom_text_repel() call and specifically the argument for code.

    Fun fact: change that last line to read geom_text_repel(data= ind_mapa, aes(x=lon, y=lat, group= code), label=ano), where only group=code is in the aes() call. You should expect to see the same error message, but with object 'ano' not found.