How do you combine a map with complex display of points in ggplot2?

后端 未结 1 1200
时光说笑
时光说笑 2021-01-02 18:59

I\'m trying to plot points from study sites with a background map of Africa. I can create the two independently, but I am having a hard time overlaying them on top of eacho

相关标签:
1条回答
  • 2021-01-02 19:28

    Try something like this. Seems to work for me. I think some of your lat-long coordinates are wrong though. The fill colour for geom_point is currently set to Tot437 so you might want to change that.

    map

    library(ggplot2)
    library(rgdal)
    
    africa <- readOGR("c:/test", layer = "Africa")
    africa.map = fortify(africa, region="COUNTRY")
    
    africa.points = read.table("c:/test/SPM-437-22Nov12.txt", header = TRUE, sep = ",")
    names(africa.points)[which(names(africa.points) == 'Longitude')] <- 'long' # rename lat and long for consistency with shp file
    names(africa.points)[which(names(africa.points) == 'Latitude')] <- 'lat'
    
    ggplot(africa.map, aes(x = long, y = lat, group = group)) +
        geom_polygon(colour = "black", size = 1, fill = "white", aes(group = group)) +
        geom_point(data = africa.points, aes(x = long, y = lat, fill = Tot437, group = NULL), size = 4, shape = 21, colour = "black", size = 3)
    

    Incidentally, looking at your map you may have difficulty getting a good detailed view of individual areas, so one way to tackle that would be by subsetting, in this case with the data frames. You could do this:

    africa.map <- africa.map[africa.map$id == 'Madagascar', ]
    africa.points <- africa.points[africa.points$Country == 'Madagascar', ]
    ggplot(africa.map, aes(x = long, y = lat, group = group)) +
        geom_polygon(colour = "black", size = 1, fill = "white", aes(group = group)) +
        geom_point(data = africa.points, aes(x = long, y = lat, fill = Tot437, group = NULL), size = 2, shape = 21, colour = "black", size = 2)
    

    ...which should get you something similar to this:

    madagascar

    0 讨论(0)
提交回复
热议问题