Reputation: 265
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 eachother.
The map of Africa I am using is an Esri shapefile from maplibrary.org. It is available from my dropbox at https://www.dropbox.com/s/etqdw3nky52czv4/Africa%20map.zip. I have the points in a text file, also available from my drop box. https://www.dropbox.com/s/scvymytjsr5pvaf/SPM-437-22Nov12.txt. They refer to studies on molecular drug resistance of malaria parasites. I would like to plot them so that the color is the proportion of parasites with the drug resistant genetic marker and the size is the number of parasites tested.
Plotting the points independently:
qplot(Longitude, Latitude, data = d.spm.437, colour = Frc437, size = Tot437)
Plotting the map of Africa:
library(maptools)
africa = readShapePoly("Africa.shp")
africa.map = fortify(africa, region="COUNTRY")
qplot(long, lat, data = africa.map, geom="path", group=group)
Any help on putting these two together while preserving the display of the points would be appreciated.
Upvotes: 7
Views: 4413
Reputation: 7997
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.
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:
Upvotes: 9