display data on a map - r

I need to plot my variable Omega as a heat map on the Pacific Ocean.
I have the coordinates and the Omega values but ggplot would only plot a world map while my omega appears as a separate figure (See image attached)
This is my data where y and x are Lat and Longs for my sites
Country Omega y x
1 Guam 3.28 144.7822 13.66660
2 Guam 3.28 144.7605 13.62500
This is the code I am using
map.world <- map_data(map = "world")
gg <- ggplot()
gg <- gg + theme(legend.position = "none")
gg <- gg +
geom_map(data = map.world, map = map.world,
aes(map_id = region, x = long, y = lat),
fill = "white", colour = "black", size = 0.25) +
theme_bw()
omega <- read.csv("map.csv", header = T)
head(omega)
g <- gg +
geom_polygon() +
geom_point(data = omega, aes(y = y, x = x, color = Omega)) +
theme_minimal()
I need to plot my Omega in my study sites and generate a heat map. Please any help would be very appreciated. Thank you very much

You might want to have a look at the leaflet package, it’s easier to use and better
library(leaflet)
df <- data.frame(Country=c("Guam","Guam"),
Omega=c(3.28,3.28),
y=c(144.7822, 144.7605),
x=c(13.6660, 13.6250))
m <- leaflet(data=df)
content <- paste("Omega Value:",df$Omega)
m %>% addCircles(lng=~y, lat=~x, radius=df$Omega, popup=content) %>%
setView(lng=144.793732, lat=13.444304, zoom=10)

Related

R contour plots

I have a set of data in a gridded map and air pollutant concentrations for each grid.
x <- seq(1:12)
y <- seq(0.1,3,0.24)
set.seed(5)
z <- runif(length(x)*length(y),0,10)
data <- expand.grid(x,y)
data$z <- z
colnames(data)<-c("x","y","z")
p1<-ggplot(data)+
aes(x = x, y = y, z = z, fill = z) +
geom_tile() +
coord_equal() +
geom_contour(color = "white", alpha = 0.5) +
scale_fill_distiller(palette="Reds")+
theme_bw()
print(p1)
We can see the contour lines, but filling color not like smooth contour plot.
I've tried some example from website, they are working fine. I am just wondering, is this due to I have same lat for each raw and lon for each col? Any suggestion how can I fix it?

Using ggplot to plot a map from a matrix

I wanted to create some maps by using ggplot2, but I am struggling to find the best way. Since I have a list ("models") with matrix, I wanted to use ggplot because then, it should be easier to create a multiplot (with facet_wrap..but just a thought).
I will create an reproducible example for doing this:
#European corrdinates
lon <- rep(loni,38) #longitude values -13W-34E
lat <- rep(lati, each = 48) #latitude values 34N-70N
#Matrix of values
mod <- matrix( rnorm(48*38,mean=0,sd=1), 48, 38)
#Create a list of matrix (as my real data)
dat.mod <- rep(list(mod), 4)
names(dat.mod) <- c("DJF","MAM","JJA","SON")
#Order data
md <- melt(dat.mod)
md$lon <- lon
md$lat <- lat
md$group <- "Model1"
names(md) <- c("X1","X2","SI","Season","lon","lat","model")
#
#First try:
#Problem here: I don't know how to add the map
brks <- seq(0, 2.2, by=0.2)
cols <- colorRampPalette(c("skyblue1", "lightcyan2", "lightyellow", "yellow", "orange", "red3"))(length(brks)-1)
m <- ggplot(data = md, aes(x = lon, y = lat, fill = SI)) +
geom_raster() +
scale_fill_gradientn(colours = cols, na.value = NA)+
facet_wrap(~ model~ Season, nrow =11,ncol=4)+
theme(strip.background = element_blank(),
strip.text.x = element_blank())
#I would get this image:
#Now, as a second try to add a map of Europe, I used:
map <- ggplot()
map <- map + coord_fixed()
map <- map + geom_polygon(data=map_data(map="world"), aes(x=long, y=lat, group=group), fill=NA, color="black", size=0.01)
map <- map + coord_cartesian(xlim=range(md$lon), ylim=range(md$lat))
map <- map + geom_tile(data=md, aes(x=lon, y=lat, fill=SI), alpha=I(0.7))
map <- map + scale_fill_gradientn(colours=cols)
map <- map + facet_grid(model~Season)
map <- map + theme(legend.position="none")
Now, I would have:
The problem with the second one is that I don't know how to change to background with white, and make the map more visible..is that possible?? The thing is, I wanted to plot 11 rows by 4 col. so when plotting all together it doesn't look very well...any suggestion?
Really appreciate any help.
Many thanks

Close polygon on ggmap (stat_contour)

I have recently started coding with R, so far it has been quite a journey with several obstacles on the road. Most of them I have been able to solve by searching the internet. However, now I am encountering a problem I am unable to fix. I found a sort of similair thread on stackoverflow, (How to fill in the contour fully using stat_contour), nevertheless it does not work in my situation, ggmap + ggplot seem unable to work together.
So, the problem is the following. I am studying whether the red light district in Amsterdam has an effect on local businesses. I do this by creating plot that shows business density in the city centre of Amsterdam. I have used this code to make it:
# Background map
geo <- geocode("Amsterdam", source="google")
lon <- geo$lon - .000
lat <- geo$lat + .000
map <- get_map(c(lon = lon, lat = lat), zoom=14,maptype = "satellite", color="color")
p <- ggmap(map) + theme(legend.position = c(1, 1), legend.justification = c(1,1)) +
xlab("Longitude") + ylab("Latitude")
# Map boundaries
#xmin = 4.86774509503174
#xmax = 4.92267673565674
#ymin = 52.3534171572766
#ymax = 52.386956071714
# RLD Map (so it can be read by ggplot2)
rldmap <- fortify(rld)
rld2map <- fortify(rld2)
natmap <- fortify(nat)
# Ticks
mid <- 250
mi <- 0
ma <- 500
r <- (ma-mi)/5
breaks = seq(mi,ma,r)
# Density
ncells <- 150
dens2000 <- kde2d(bedrijven2000$LONG, bedrijven2000$LAT, n = ncells)
densdf2000 <- data.frame(expand.grid(x = dens2000$x, y = dens2000$y), z = as.vector(dens2000$z))
densmap2000 <- p + geom_point(aes(x = x, y = y), data = coords2000, alpha = .5, size = 1) +
stat_contour(aes(x,y,z=z,fill = ..level..), data=densdf2000,geom="polygon", alpha=.3, inherit.aes = F) +
scale_fill_gradientn(name="density", breaks = breaks, colours=rev(brewer.pal(7,"Spectral"))) +
geom_polygon(aes(x=long, y=lat, group=group), fill='grey', size=.2,color='green', data=rldmap, alpha=0) +
geom_polygon(aes(x=long, y=lat, group=group), fill='grey', size=.2,color='green', data=rld2map, alpha=0) +
geom_polygon(aes(x=long, y=lat, group=group), fill='grey', size=.2,color='green', data=natmap, alpha=0) +
geom_point(aes(x = x, y = y), data = coords,color = 'yellow',alpha = 1, size = 1, shape=10) +
annotate('text', x=4.892, y=52.374, label = "Amsterdam", col="white") +
ggtitle("Business Density in Amsterdam year=2000")
plot(densmap2000)
Using this code provides the following output:
output density plot Amsterdam
The problem here is that the lines of the polygons that show the density stop when they are close to the border of the plot, this gives a disturbing image.
Therefore my question is, how can I make the polygons forget about the borders of the graph and make them continuous?
Managed to answer the question myself in the end, thanks to this thread: Truncated Density Polygons with ggmap
the answer lies in two parts:
1, edit extend and maprange in background map
ggmap(map, extent="normal", maprange=FALSE)
2, edit in code for plot, add:
coord_cartesian(xlim=c(min(4.86774509503174),max(4.92267673565674)),
ylim=c(min(52.3534171572766),max(52.386956071714))) +

Raster image on world map in ggplot

I want to fill certain values (pressure) continuously as gradient fill on a world map and I am writing the following code:
df = data.frame(phi)
names(df) = lat
df$lon= lon
mdata = melt(df, id=c("lon"))
names(mdata) = c("lon", "lat", "x")
mdata$x = as.numeric(mdata$x)
mdata$lon = as.numeric(mdata$lon)
mdata$lat = as.numeric(as.character(mdata$lat))
wr <- map_data("world")
# Prepare a map of World
wrmap <- ggplot(wr, aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "white", colour = "black") +
geom_point(data=mdata, inherit.aes=FALSE, aes(x=lon, y=lat, colour=x), size=3, shape=4) +
scale_fill_gradient("Phi", limits=c(4500,6000)) +
theme_bw() +
coord_equal()
wrmap
Unfortunately the points are coming out discreet.
Any ideas how to fix this?
I am not exactly sure what you want because you didn't give us any data, but I made some guesses and did this:
library(ggplot2)
library(maps)
library(reshape2)
# Generate some fake data
lat <- seq(-90, 90, by = 5)
lon <- seq(-180, 180, by = 10)
phi <- 1500*tcrossprod( sin( pi*lat/180 ), cos( pi*lon/180 ))^ 2 + 4500
# above thanks to #NBAtrends for turning my two ugly for loops into this elegant statement
df = data.frame(phi)
names(df) = lat
df$lon = lon
mdata = melt(df, id = c("lon"))
names(mdata) = c("lon", "lat", "x")
mdata$x = as.numeric(mdata$x)
mdata$lon = as.numeric(mdata$lon)
mdata$lat = as.numeric(as.character(mdata$lat))
wr <- map_data("world")
# Prepare a map of World
wrmap <- ggplot(wr, aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "white", colour = "black") +
geom_point(data=mdata, inherit.aes=FALSE,aes(x=lon, y=lat, color=x),size=3) +
scale_color_gradient("Phi", limits = c(4500, 6000)) +
theme_bw() +
coord_equal()
wrmap
Yielding this, which seems close to what you probably want:
This leads me to conclude that the problem is with your data. By comparing it to my fake data, I think you can probably figure out your problem.
Also I changed the "x" to a circle since you couldn't see it's color very well.

Points changing sizes on ggplot geom_point and no legend?

Okay so here is my code for a base map:
gg <- ggmap(Peru) +
geom_map(data = peru.coast, map = peru.coast, aes(x = long, y = lat, map_id = region),
fill="gray", color="black") +
xlim(-86, -70) +
ylim(-20, -4) +
labs(x = "Longitude", y = "Latitude") +
coord_map()
I then add in towns I wish to name manually (wasn't sure how to do it using google maps as I only wanted these 4)
gg <- gg + geom_point(aes(x=-78.981885, y=-8.229354, size=3)) +
annotate("text", label='Salaverry', size=4, x=-77.2, y=-8.229354) +
geom_point(aes(x=-71.345838, y=-17.644347, size=3)) +
annotate("text", x=-70.545838, y=-17.644347, label = 'Ilo', size=4) +
geom_point(aes(x=-77.142375, y=-12.047544, size=3)) +
annotate("text", x=-75.9, y=-12.047544, label = 'Callao', size=4) +
geom_point(aes(x=-78.610677, y=-9.074166, size=3)) +
annotate("text", x=-76.9, y=-9.074166, label = 'Chimbote', size=4)
gg <- gg + guides(size=FALSE) #this removes the legend with the black dot and '3' on it
gg
I get this lovely map:
I then use this dataset to add datapoints, and I wish to make the points bigger or smaller according to 'n' abundance
Trip_Set sex Set.Lon Set.Lat n
119_1 hembra -81.09390 -9.32338 2
119_7 hembra -81.03117 -9.09622 1
161_3 macho -83.76533 -9.74533 5
193_8 hembra -81.00888 -9.00950 7
255_5 macho -80.14992 -8.64592 1
271_6 hembra -72.20233 -18.05117 6
271_6 macho -72.20233 -18.05117 7
328_7 hembra -78.66667 -12.91700 2
403_3 hembra -80.03037 -10.03900 1
428_2 hembra -83.01305 -8.74883 2
655_4 hembra -71.58363 -18.24882 1
using this code:
ggAB <- gg + geom_point(data=dframe4, aes(Set.Lon, Set.Lat, colour='red', size=n))
ggAB <- ggAB + theme(legend.title = element_text(colour="black", size=12, face="bold"))
ggAB <- ggAB + guides(colour=FALSE) #This removes the legend for the red colour
ggAB <- ggAB + scale_size(name='Sharks per line', range = c(5,9))
ggAB <- ggAB + theme(legend.key=element_rect(fill = NA)) #This removes the boxes around the points
ggAB
However, when I do this... I get this:
The datapoints are plotted great (phew!), but why does it make the points bigger for my town names? I can't seem to get it to just keep the abundance for my 'n' number datapoints... It also doesn't put an automatic legend on (as ggplot usually does), even when I try and put one in manually using the scale_discrete function.
I thought it might be something to do with the fact that I use gg + guides(size=FALSE) in the first part, but even when taking that out it doesn't work, but adds in an annoying legend for my town datapoints.
Any ideas?
The problem is that in the code where you add the towns, you have put the size inside the aes. Therefore it also gets transformed when you call scale_size(name='Sharks per line', range = c(5,9)). Just use size outside the aes:
gg <- gg + geom_point(aes(x=-78.981885, y=-8.229354), size=3) +
annotate("text", label='Salaverry', size=4, x=-77.2, y=-8.229354) +
geom_point(aes(x=-71.345838, y=-17.644347), size=3) +
annotate("text", x=-70.545838, y=-17.644347, label = 'Ilo', size=4) +
geom_point(aes(x=-77.142375, y=-12.047544), size=3) +
annotate("text", x=-75.9, y=-12.047544, label = 'Callao', size=4) +
geom_point(aes(x=-78.610677, y=-9.074166), size=3) +
annotate("text", x=-76.9, y=-9.074166, label = 'Chimbote', size=4)
In addition to #shadow's answer, I'd like to leave the following for the OP as supplementary information. This comes from the chat with the OP. If you want to avoid using annotate, you can use geocode in the ggmap package. Here, I added some from my answer to the previous question of the OP, and I combined/modified the OP's code. One change is that I used alpha so that you can see red/pink points in the ocean. One note is that the positions of the city names are not perfect; the further you go down south in the map, the more you see gaps between points and city names. This could be due to something to do with map projection. According to Wiki, googlemap is using something close to marcator, but not exact the same. This could be the reason. Some GIS experts here would be able to provide more information.
library(ggmap)
library(mapdata)
library(ggplot2)
# Get Peru map
Peru <- get_map(location = "Peru", zoom = 5, maptype="satellite")
# This is the layer I wish to put over the top
coast_map <- fortify(map("worldHires", fill = TRUE, plot = FALSE))
# Subset data for Peru
peru.coast <- subset(coast_map, region == "Peru")
### Get lon and lat using geocode() in the ggmap package and crate a data frame
cities <- c("Salaverry", "Chimbote", "Callao", "Ilo")
locations <- geocode(cities)
locations$city <- cities
locations2 <- transform(locations, lon2 = lon + 1.1) # This is for text position
ggmap(Peru) +
geom_map(data = peru.coast, map = peru.coast, aes(x = long, y = lat, map_id = region),
fill="gray", color="black") +
geom_point(data = locations2, aes(x = lon, y = lat, color = city), size = 4) +
geom_text(data = locations2, aes(x = lon2, y = lat, label = city), size = 3) +
scale_color_manual(values = rep(c("black"), times = 4)) +
geom_point(data = newdata, aes(Set.Lon, Set.Lat, size = n), colour = "red", alpha = 0.5) +
scale_size(name = "Sharks per line", range = c(5,9)) +
xlim(-86, -70) +
ylim(-20, -4) +
labs(x = "Longitude", y = "Latitude") +
coord_map("mercator") +
guides(colour=FALSE) +
theme(legend.key=element_rect(fill = NA))

Resources