Reputation: 33
I have question regarding my R script: How do I overlay a point_density using google map or osm tile as background in R? 1) This works fine, but is not what I want:
library(ggmap)
map <- get_map("Vilnius", zoom = 14, source = "osm", color = "bw")
mapPoints <- ggmap(map)
p<-ggplot(geotag@data, aes(Y, X))
p + stat_density2d(aes(fill= ..level..), alpha =0.5, geom="polygon") + geom_point(aes(Y, X), colour="red", data = geotag@data, alpha = .5)
2) if I instead use a osm tile as background the point density is distorted (unfortunately I cannot show illustrate an image). It seems that the point density function does not recognize the point distribution and creates a symmetric overlay:
library(ggmap)
map <- get_map("Vilnius", zoom = 14, source = "osm", color = "bw")
mapPoints <- ggmap(map)
mapPoints + stat_density2d(aes(fill= ..level..), alpha =0.5, geom="polygon") + geom_point(aes(Y, X), colour="red", data = geotag@data, alpha = .5)
Here is some sample data:
OID_ Y X
0 25.29315500000 54.68288700000
0 25.29375600000 54.68260200000
0 25.28416600000 54.68472200000
0 25.29776900000 54.68051900000
0 25.29549400000 54.68064800000
0 25.25535200000 54.67742600000
0 25.29541800000 54.68429700000
0 25.29751100000 54.68445600000
0 25.29541800000 54.68429700000
0 25.29541800000 54.68429700000
0 25.29751100000 54.68445600000
0 25.29751100000 54.68445600000
0 25.29751100000 54.68445600000
0 25.29751100000 54.68445600000
0 25.28865900000 54.68074300000
0 25.28943200000 54.67457100000
0 25.29133200000 54.68690000000
0 25.29176000000 54.68873800000
0 25.28049400000 54.67952800000
what I am doing wrong?
Thanks for any help
Upvotes: 2
Views: 3258
Reputation: 59345
Is this what you're looking for? Calling your sample df
:
library(ggmap)
map <- get_map("Vilnius", zoom = 14, source = "osm", color = "bw")
mapPoints <- ggmap(map)
mapPoints +
stat_density2d(data=df,aes(Y,X, fill= ..level..), alpha =0.5, geom="polygon") +
geom_point(data=df, aes(Y, X), colour="red", alpha = .5)
The problem was that, in the first snippet, the default dataset is set to geotag@data
in the call to ggplot(...)
, whereas in the second snippet the default dataset is defined internally in the call to ggmap(...)
. In that case you have to explicitly define the (local) dataset, and the X and Y mappings, in the call to stat_density(...)
.
Upvotes: 3