I just got my location data from Falkland Island, and i tried to map the locations that I got from the tags, however, when i run this code r stop working.
I have a data frame for 30 penguins, with different amount of location each, thus, the table looks like this:
This is the code that i tried:
gentoo<-read.csv("Regularised Gentoos.csv", header=F)
plot(gentoo$V3~gentoo$V4,ylab="Latitude",xlab="Longitude",
col=gentoo$V1,aspect="iso")
I could finally plot my data, with the bathymetry of the area:
#Load in libraries
library(sp)
library(rgdal)
library(rgeos)
library(maptools)
library(raster)
library(ggplot2)
library(scales)
library(gridExtra)
library(adehabitatHR)
library(maptools)
library(marmap)
library(maptools)
#Load in shapefile from NaturalEarthData.com
#Load in shapefile from NaturalEarthData.com
world_shp = rgdal::readOGR("/Users/danielgonzalez/Desktop/Thesis/DATA EMAILS/natural_earth_vector/10m_physical",layer = "ne_10m_land")
world_shp
#Load in .csv file
gentoo = read.csv("/Users/danielgonzalez/Desktop/Thesis/DATA EMAILS/Regularised Gentoos.csv")
#Create a spatial points dataframe
locs = sp::SpatialPointsDataFrame(coords = cbind(gentoo$lon, gentoo$lat), data = gentoo, proj4string=CRS("+proj=longlat +datum=WGS84"))
locs
#Extra...
#To download bathymetry data FALKLAND ISLAND MAP
#ETOPO1 database hosted on the NOAA website
library(marmap)
getNOAA.bathy(lon1=-70, lon2=-52, lat1=-57, lat2=-46, resolution = 1) -> bathy
plot(bathy, image=TRUE, deep=-6000, shallow=0, step=1000)
bat = as.raster(bathy)
#Write
writeRaster(bat, filename = "~/bathy.asc")
#Read
bat = readGDAL("~/bathy.asc")
#Load in Raster data
#This is 1 min resolution bathymetry from ETOPO1 database hosted on the NOAA website
bathy = raster::raster("/Users/danielgonzalez/bathy.asc")
#Define projection of bathymetry data
raster::projection(bathy) = CRS("+proj=longlat +datum=WGS84")
#Create a spatialpoints object of the colony
Colonsay = sp::SpatialPoints(coords = cbind(-6.25, 56.07), proj4string = CRS("+proj=longlat +datum=WGS84"))
#Quick plot
#png("gentoo distribution.png",width=8,height=6,units="in",res=1800)
image(bathy,ylab="Latitude",xlab="Longitud")
lines(world_shp)
points(gentoo$lon,gentoo$lat, pch = 19, cex = 0.3,col=gentoo$id)
#dev.off()
Just use ggmap
library(ggmap)
library(ggplot2)
#lat/lon data
df <- as.data.frame(matrix(nrow = 3, ncol =3))
colnames(df) <- c("lat", "lon", "id")
df$lon <- c(-51.2798, -51.3558, -51.9)
df$lat <- c( -59.6387, -59.7533, -59.4)
df$id <- c("1", "2", "3")
df
lat lon id
1 -59.6387 -51.2798 1
2 -59.7533 -51.3558 2
3 -59.4000 -51.9000 3
#get the map
library(ggmap)
mapImageData <- get_map(location = "Falkland Islands",
source = "google", zoom = 9)
#plot the points
ggmap(mapImageData,
extent = "panel",
ylab = "Latitude",
xlab = "Longitude",
legend = "right") +
geom_point(aes(x = lat, # path outline
y = lon),
data = df,
colour = "black") +
labs(x = "Longitude",
y = "Latitude") + ggtitle("Penguin Sightings") +
theme(plot.title = element_text(lineheight=.8, face="bold"))
Related
I'm trying to create a map of Europe with grid cells coloured based on the number of records within a cell. Here I attach an image as illustrative of the desired output (see Fig 1 of https://doi.org/10.3897/phytokeys.74.9723).
In order to produce this image I have developed a minimal reproducible example with random points distributed across Europe. I have been able to produce a similar figure with levelplot but I'm particulary interested in doing this with ggplot as it will allow further customising. Is it possible to do produce a similar figure with ggplot? And if so, any advice of what path should I follow?
Note: The size of the grids/cells is irrelevant at the moment but I'll adjust it depending on point density. All of them have to be the same size as in the first example and they only will differ on the pattern of colour.
#Load libraries
library(rgdal) #v1.5-28
library(rgeos) #v.0.5-9
library(ggplot2) # 3.3.5
library(rworldmap) #plot worldmap v.1.3-6
library(dplyr) #v.1.0.7
#Create dataframe of coordinates that fall in Europe
coord <- data.frame(cbind(runif(1000,-15,45),runif(1000,30,75)))
colnames(coord) <- c("long","lat")
#Exlude ocean points following this post
URL <- "http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/110m/physical/ne_110m_ocean.zip"
fil <- basename(URL)
if (!file.exists(fil)) download.file(URL, fil)
fils <- unzip(fil)
oceans <- readOGR(grep("shp$", fils, value=TRUE), "ne_110m_ocean",
stringsAsFactors=FALSE, verbose=FALSE)
europe_coord <- data.frame(long = coord$long,
lat = coord$lat)
coordinates(europe_coord) <- ~long+lat
proj4string(europe_coord) <- CRS(proj4string(oceans))
ocean_points <- over(europe_coord, oceans)
#Add ocean points to dataset
coord$ocean <- ocean_points$featurecla
#Exlude ocean points
europe_land <- coord %>% filter(is.na(ocean))
#Load worldmap
world <- map_data("world")
#Plot europe spatial data
ggplot() + geom_map(data = world, map = world,
aes(long, lat, map_id = region), color = "white",
fill = "lightgray", size = 0.1) +
geom_point(data = europe_land,aes(long, lat),
alpha = 0.7, size = 0.05) + ylim(0,70) +
coord_sf(xlim = c(-15, 45), ylim = c(30, 75), expand = FALSE)
I need to create a map of country(Thailand) based on shapes files (preferably colored)and to add the codes of the provinces (from 10 to 96,77 codes) and the corresponding coefficient from h.сsv(also 77 values) file on the map.
I am trying to show my two codes(maybe,one of them will be better for map):
1st:
library(raster)
library(rasterVis)
library(rgdal)
library(rgeos)
library(dismo)
library(sp)
library(maptools)
library(maps)
library(mapdata)
library(XML)
library(foreign)
library(latticeExtra)
library(shapefiles)
library(RColorBrewer)
library(GISTools)
#library(SDMTools)
library(dplyr)
library(tidyr)
library(tidyverse)
library(lubridate)
## preparing shapefiles
thailand_district <- shapefile("C:/usa/archive/TH_Province2012.shp")
thailand_district
crs(thailand_district)
names(thailand_district)
thailand_district_lonlat<- spTransform(thailand_district, CRS("+proj=longlat +datum=WGS84"))
crs(thailand_district_lonlat)
thailand_district_lonlat_s<-gSimplify(thailand_district_lonlat, tol=0.02, topologyPreserve=TRUE)
district_id<-thailand_district_lonlat$A_CODE
province_id<-thailand_district_lonlat$P_CODE
thailand_prov <- shapefile("C:/usa/archive/TH_Province2012.shp")
thailand_prov
crs(thailand_prov)
thailand_prov_lonlat<- spTransform(thailand_prov, CRS("+proj=longlat +datum=WGS84"))
crs(thailand_prov_lonlat)
thailand_prov_lonlat_s<-gSimplify(thailand_prov_lonlat, tol=0.02, topologyPreserve=TRUE)
## preparing centroids
thailand_district_centroids <- getSpPPolygonsLabptSlots(thailand_district_lonlat)
head(thailand_district_centroids)
district_centroids<- data.frame(province_id,district_id, thailand_district_centroids[,1],thailand_district_centroids[,2])
district_centroids<-read.csv("data.scrub.district.csv")
names(district_centroids) <- c("province_id","district_id","longitude", "latitude")
ex<-district_centroids
coordinates(ex)<- cbind("longitude", "latitude")
plot(ex)
thailand_province_centroids <- getSpPPolygonsLabptSlots(thailand_prov_lonlat)
head(thailand_province_centroids)
## read cases
scrub1<-read_csv("C:/usa/archive/scrub_2003-07_180319.csv")
names(scrub1)
scrub1<-dplyr::select(scrub1,Address, The.day.began.to.get.sick..M.D.Y.)
scrub1 <- dplyr::rename(scrub1,date=The.day.began.to.get.sick..M.D.Y.)
scrub1 <-na.omit(scrub1)
scrub2<-read_csv("C:/usa/archive/scrub_2008-11_180319.csv")
scrub2<-dplyr::select(scrub2,Address, The.day.began.to.get.sick..M.D.Y.)
scrub2 <- dplyr::rename(scrub2,date=The.day.began.to.get.sick..M.D.Y.)
scrub3<-read_csv("C:/usa/archive/scrub_2012-18_180319.csv")
scrub3<-dplyr::select(scrub3,Address, The.day.began.to.get.sick..M.D.Y.)
scrub3 <- dplyr::rename(scrub3,date=The.day.began.to.get.sick..M.D.Y.)
scrub<-dplyr::union(scrub1, scrub2)
scrub<-dplyr::union(scrub, scrub3)
scrub$district_id<-(tamboon_id=substr(scrub$Address, 1,4))
scrub <- dplyr::rename(scrub,village_id=Address)
scrub<-tidyr::drop_na(scrub,village_id)
scrub_district <- dplyr::select(scrub,district_id)
# preparation
scrub$date1 <- as.Date(scrub$date,
format = "%d/%m/%Y")
scrub$year<-lubridate::year(scrub$date1)
scrub$YearMonth<-format(scrub$date1, "%Y-%m")
scrubYear<-scrub %>%
drop_na() %>%
group_by(year) %>%
summarise(scrubcases= n())
scrub$district_id<-as.factor(scrub$district_id)
is.factor(scrub$district_id)
scrubDistrict<-scrub %>%
drop_na() %>%
group_by(district_id) %>%
summarise(scrubcases= n())
district_centroids
district_centroids2<-district_centroids %>%
unite("district_id", province_id,district_id2)
district_centroids2$district_id<-gsub("_", "",district_centroids2$district_id )
scrubdistict_longlat<-dplyr::left_join(district_centroids2,scrubDistrict,
by="district_id")
write_csv(scrubdistict_longlat,"data.scrub.district.csv")
scrubClean<-read_csv("data.scrub.district.csv")
mydata<-dplyr::filter(scrubClean, scrubcases > 0)
ex2<-mydata
coordinates(ex2)<-c("longitude","latitude")
bubble(ex2,"scrubcases")
# map
library(tmap)
library(tmaptools)
proj4string(ex2) <- proj4string(thailand_district_lonlat)
tmaptools::palette_explorer()
# thailand
tm1<-tm_shape(thailand_prov_lonlat_s) +
tm_fill(NA) + tm_borders("black")+
tm_borders("black")+
tm_compass(type = "8star", position = c("right", "top"),size = 2)+
tm_scale_bar(breaks = c(0, 100, 100), size = 0.5, position = c("right", "bottom"))+
tm_style( "beaver")
tm1
tm2<-tm_shape(thailand_district_lonlat_s)+
tm_polygons()+
tm_shape(ex2) +
tm_bubbles("scrubcases",col = "lightblue",scale = 2,
border.col = "black", border.alpha = .5,
contrast=1,
title.size="cases / district")
tm2
library(dplyr)
library(tidyr)
library(tmap)
data(World)
names(World)
mygideon<-read_csv("data.gideon.iso.final.csv") %>%
group_by(iso_a3) %>%
summarise(total.outbreaks=n())
world2<-dplyr::left_join(World,mygideon2,by="iso_a3")
tm_shape(world2) +
tm_polygons("total.outbreaks",
style = "fixed",
breaks = c(1,50,100,250,500,750, 1000, 1500, 2500),
palette="Oranges",
title = "Total outbreaks (1940-2018)", contrast = 1.2,
border.col = "gray30", id = "name", n=6,
legend.hist = TRUE,alpha = 1)+
tm_layout(legend.outside = TRUE)
**Error in data.frame(province_id, district_id, thailand_district_centroids[, :
arguments imply differing number of rows : 0, 77.use coordinates method**
2n code.
library(raster)
library(rasterVis)
library(rgdal)
library(rgeos)
library(dismo)
library(sp)
library(maptools)
library(maps)
library(mapdata)
library(XML)
library(foreign)
library(latticeExtra)
library(shapefiles)
library(RColorBrewer)
library(GISTools)
#library(SDMTools)
library(dplyr)
library(tidyr)
library(tidyverse)
library(rgeos) # to fortify without needing gpclib
library(ggplot2)
library(scales) # for formatting ggplot scales with commas
thamap <- readOGR("C:/usa/archive/TH_Province2012.shp")
thamap
crs(thamap)
thamap_lonlat<- spTransform(thamap, CRS("+proj=longlat +datum=WGS84"))
crs(thamap_lonlat)
thamap_lonlat_s<-gSimplify(thamap_lonlat, tol=0.02, topologyPreserve=TRUE)
thamap.fort <- fortify(thamap)
idList <-thamap#data$PROV_CODE
centroids.df <- as.data.frame(coordinates(thamap))
names(centroids.df) <- c("Longitude", "Latitude")
info <- read.csv("h.csv")
pop.df <- data.frame(idList,info,centroids.df)
ggplot(pop.df, aes(map_id = idList)) + #"id" is col in your df, not in the map object
geom_map(aes(fill = info), colour= "grey", map = thamap.fort) +
expand_limits(x = thamap.fort$long, y = thamap.fort$lat) +
scale_fill_gradient(high = "red", low = "white", guide = "colorbar", labels = comma) +
geom_text(aes(label = id, x = Longitude, y = Latitude)) + #add labels at centroids
coord_equal(xlim = c(-90,-30), ylim = c(-60, 20)) +
labs(x = "Longitude", y = "Latitude", title = "map Thailand") +
theme_bw()
Don't know how to automatically pick scale for object of type function. Defaulting to continuous.
Aesthetics must be valid data columns. Problematic aesthetic(s): label = id.
Did you mistype the name of a data column or forget to add after_stat()?
I would really appreciate it if you could help me to fix my codes a little to create the map.
Could you tell me please also,how is it possible to add the data(77 values) from csv file on the map near the codes of provinces?
Thank you very much for your help
Here's a solution using tmap. The shapefile containing the borders of Thailand (country and provinces) is available from https://data.humdata.org/dataset/thailand-administrative-boundaries. The province codes (10-96) are also included in the dataset in character format and can easily be extracted.
library(tmap)
library(sf)
library(tidyverse)
provinces <- st_read(dsn = "tha_adm_rtsd_itos_20190221_SHP_PART_1/tha_admbnda_adm1_rtsd_20190221.shp") %>%
as.tibble() %>%
separate(ADM1_PCODE, into = c("pcode_text", "pcode_num"), sep = "(?<=[A-Za-z])(?=[0-9])") %>%
select(geometry, pcode_num) %>%
st_as_sf()
tm_shape(provinces) +
tm_fill(col = "MAP_COLORS") +
tm_text("pcode_num", size = .5) +
tm_borders(lwd = .7, col = "black")
What I have:
points in the arctic and antarctic
raster data from various geophysical entities in arctic and antarctic
What I want:
A map in stereographic or any other polar projection with background map or coastlines, cropped to the extent of the points. In other words: A map like above with base map of my own choice.
What I did so far:
I loaded all the data (including land surface data from naturalearthdata; see MWE), projected them into stereographic and plotted that. The result including the polygon data looks then like this:
My MWE:
library(raster)
library(sf)
library(ggplot2)
library(rgdal)
# file load ---------------------------------------------------------------
# sea ice raster data
if (!file.exists("seaiceraster.tif")) {
url = "https://seaice.uni-bremen.de/data/smos/tif/20100514_hvnorth_rfi_l1c.tif"
download.file(url, destfile = 'seaiceraster.tif')
}
si.raster = raster::raster('seaiceraster.tif')
# land surface shapefile
if (!file.exists("110m-admin-0-countries")) {
url_land = "https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/10m/physical/ne_10m_land.zip"
download.file(url_land, destfile = "110m-admin-0-countries")
unzip("110m-admin-0-countries")
}
world_shp = rgdal::readOGR("ne_10m_land.shp")
# points
p.data = structure(
list(
Lat = c(
73.0114126168676,70.325555278764,77.467797903163,
58.6423827457304,66.3616310851294,59.2097857474643,
75.3135274436283,60.1983078512275,72.6614399747201,
61.1566678672946,73.0822309615673,55.7759666826898,
75.1651656433833,69.0130753414173,62.3288262448589
),
Lon = c(
-59.9175490701543,-80.1900239630732,-40.4609968914928,
-61.0914448815381,-60.0703668488408,-21.027205418284,
-100.200463810276,-74.861777073788,-55.1093773178206,
-29.4108649230234,-64.5878251008461,-36.5343322019187,
-31.647365623387,-67.466355105829,-64.1162329769077
)
),
row.names = c(
1911L, 592L,2110L,3552L,3426L,1524L,635L,4668L,
3945L,2848L,3609L,36L,4262L,3967L,2725L
),
class = "data.frame"
)
p = sf::st_as_sf(p.data, coords = c("Lon", "Lat"),
crs = "+init=epsg:4326")
# project -----------------------------------------------------------------
polar.crs = CRS("+init=epsg:3995")
si.raster.proj = projectRaster(si.raster, crs = polar.crs)
world_shp.proj = sp::spTransform(world_shp, polar.crs)
p.proj = sf::st_transform(p, polar.crs)
# preparation -------------------------------------------------------------
AG = ggplot2::fortify(world_shp.proj)
# make raster to data.frame
si.raster.df = si.raster.proj %>%
raster::crop(., p.proj) %>%
raster::rasterToPoints(., spatial = TRUE) %>%
as.data.frame(.)
colnames(si.raster.df) = c("val", "x", "y")
# plot --------------------------------------------------------------------
ggplot() +
# geom_polygon(data = AG, aes(long, lat, group = group)) + # un-comment to see
geom_raster(data = si.raster.df, aes(x = x, y = y, fill = val)) +
geom_sf(data = p.proj, color = "green", size = 3)
I've changed the workflow in your example a bit to add the stars package for the sea ice data, but I think it should get you what you're looking for. You'll need to adjust the crop size to expand it a little, as the points p are right on the edge of the plotted area. st_buffer might help with that.
I used the crs from the seaicebuffer.tif file for all of the objects.
The .tif file has a crs that I'm not able to easily transform on my computer. It seems to be able to use meters as a lengthunit and might be a polar stereographic (variant B) projection. The points & world data don't seem to have a problem transforming to it though, which is why I've used it throughout.
library(raster)
library(sf)
library(ggplot2)
library(rgdal)
library(stars)
si <- stars::read_stars('seaiceraster.tif')
world_sf = rgdal::readOGR("ne_10m_land.shp") %>%
st_as_sf() %>%
st_transform(st_crs(si))
# p <- ... same as example and then:
p <- st_transform(p, st_crs(si))
# get a bounding box for the points to crop si & world.
p_bbox <- st_bbox(p) %>%
st_as_sfc() %>%
st_as_sf() %>%
st_buffer(100000)
# crop si & world_sf to an area around the points (p)
world_cropped <- st_crop(world_sf, p_bbox)
si_cropped <- st_crop(si, p_bbox)
#Plot
ggplot() +
geom_sf(data = world_cropped,
color = 'black',
fill = 'NA',
size = .2) +
geom_stars(data = si_cropped) +
geom_sf(data = p, color = 'red') +
scale_fill_continuous(na.value = 0)
Ugly hack for the southern .tif that stars reads as factors:
si <- stars::read_stars('20150324_hvsouth_rfi_l1c.tif', NA_value = 0 )
si$"20150324_hvsouth_rfi_l1c.tif" <- as.numeric(si$"20150324_hvsouth_rfi_l1c.tif")
ggplot() + geom_stars(data = si)
Often there is the need to produce stylish maps for inclusion in publications.
How can one possibly include projected grid coordinates in a map generated preferably with levelplotto look like those in the map shown here:
I provide sample data (for Canada) below for reproducibility. A typical projcetion for Canada is dat = projectRaster(dem, crs = ('+proj=stere +lat_0=90 +lat_ts=60 +lon_0=-110 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')) and SpTransform can be used to tranform the boundary lines (can1).
require(colorRamps)
require(raster)
require(rasterVis)
require(mapproj)
library(raster)
library(proj4)
# Get province borders and project it to same CRS than raster
can1 <- getData('GADM', country="CAN", level=1)
getData('ISO3') # country name
dem=getData('alt', country='CAN', mask=TRUE)
require( colorRamps )
my.at <- unique(round(seq(ceiling(5800), floor(1), length.out = 51),0))#at: numeric vector specifying where the colors change. must be of length 1 more than the col vector.
col<-colorRampPalette(c("#d9d9d9", "#bdbdbd", "#969696", "#737373", "#525252", "#252525", "#000000"))
levelplot(dem,maxpixel=ncell(dem),panel=panel.levelplot.raster,names.attr=names(dem),
interpolate=F,margin=FALSE,xlab=list(label="Longitude",cex=1.5),yscale.components = yscale.raster.subticks,
xscale.components = xscale.raster.subticks,
ylab=list(label="Latitude",cex=1.5),
par.strip.text=list(cex=1),xlim=c(-158, -48.99485),
ylim=c(38.00513, 85),col.regions=col,at = seq(0, 5800,100),
colorkey = list(space = "bottom", labels = list(at = seq(0, 5800,800), rot=0,cex=1.1,font=6,fontface=1,
labels =c("0", "800", "1600", "2400", "3200", "4000", "4800", "5600")),
height=0.99,width=1.8,tck = c(0,0)),
par.settings=list(panel.background=list(col="white"),axis.line=list(lwd=1.9), strip.border=list(lwd=1.9),layout.heights=list(xlab.key.padding=-0.2)),
cex=0.8, scales = list(x=list(draw=TRUE,cex=1.2), y=list(draw=TRUE,cex=1.2)))+
layer(sp.polygons(can1,lwd=0.5,col="gray40"))
Next code provides a solution using the graticule package:
library(raster)
library(rasterVis)
library(graticule)
r <- getData('alt', country='CAN', mask=TRUE)
## Here is where the graticule routine starts
crs.longlat <- CRS("+init=epsg:4326")
prj <- CRS(projection(r))
extLL <- projectExtent(r, crs = crs.longlat)
lons <- pretty(c(xmin(extLL), xmax(extLL)))
lats <- pretty(c(ymin(extLL), ymax(extLL)))
## optionally, specify the extents of the meridians and parallels
## here we push them out a little on each side
xl <- range(lons) + c(-0.4, 0.4)
yl <- range(lats) + c(-0.4, 0.4)
## build the lines with our precise locations and ranges
grat <- graticule(lons, lats, proj = prj,
xlim = xl, ylim = yl)
## Labels
labs <- graticule_labels(lons, lats,
xline = lons[2],
yline = lats[2],
proj = prj)
labsLon <- labs[labs$islon,]
labsLat <- labs[!labs$islon,]
## Display the raster
levelplot(r) +
## and the graticule
layer(sp.lines(grat)) +
layer(sp.text(coordinates(labsLon),
txt = parse(text = labsLon$lab),
adj = c(1.1, -0.25),
cex = 0.6)) +
layer(sp.text(coordinates(labsLat),
txt = parse(text = labsLat$lab),
adj = c(-0.25, -0.25),
cex = 0.6))
I am trying to fortify a large shp file to raster file for analyzing (‘Koeppen Geiger’ climatic zones) with several locations. I got an error message running the ggplot and final line of code:
Error in points2grid(points, tolerance, round) : dimension 1 :
coordinate intervals are not constant
library(raster)
library(sp)
library(maptools)
library(rgdal)
library(ggplot2)
library(rgeos)
##reading shp file [https://www.climond.org/Core/Authenticated/KoppenGeiger.aspx][1]
shape.dir <- "WC05_1975H_Koppen_Shapefile"
lon.shape <- readOGR(shape.dir, layer = "WC05_1975H_Koppen")
##fortify the data
lon.df <- fortify(lon.shape, region = "Koppen")
##Using ggplot2 and get the wrong color zones
map <- get_map(location = c(73.60226, 15.77538, 153.9856, 53.56944),
color = "color",source = "google",
maptype = "terrain")
ggmap(map) +
geom_polygon(aes(x = long,
y = lat,
fill = id),
data = lon.df) +
labs(x = "Longitude",
y = "Latitude")
## The color presented was wrong with ‘Koeppen Geiger’ climatic zones
#convert to sp SpatialPointsDataFrame
coordinates(lon.df) = c("long", "lat")
#promote to SpatialPixelsDataFrame
gridded(lon.df) <- TRUE
Perhaps do
x <- lon.shape
gridded(x) <- TRUE