I have Particulate Matter concentration difference (After - Before) for Port of Los Angeles area. I am trying to use ggmap to plot concentration contours on map but the result looks way different. The code I used is shown below (and data is below the code):
Code
install.packages('ggmap')
library(ggmap)
PM = read.csv('data.csv', stringsAsFactors = FALSE)
Get Longitude and Latitude
geocode("Port of Los Angeles") # Not centered
geocode("Compton, CA") # Now centered
Use Compton LON and LAT
POLA = c(lon = -118.220071, lat = 33.895849)
POLA.map = get_map(location = POLA, zoom = 10, color = 'bw')
ggmap(POLA.map) + geom_point(data = PM, mapping = aes(Longitude, Latitude)) +
stat_density2d(data = PM, mapping = aes(x = Longitude, y = Latitude, fill=..level..), geom = "polygon", alpha = 0.3, contour = TRUE)
However, the contour plot should have a pattern like this:
https://drive.google.com/file/d/0B3XVjcsci0y3VDBTc01PYkhOckE/view?usp=sharing
ggplot(PM, aes(UTM.X, UTM.Y)) + geom_tile(aes(fill = Value), alpha = 0.8, color = "black") +
scale_fill_gradient(low = 'green', high = 'red')
Data: Col-1: Longitude, Col-2: Latitude, Col-3: UTM-X, Col-4: UTM-Y , Col-5: Values
UTM Coordinates Units: Meters, UTM Zone = 11 N, Datum = WGS84. Data is available here: https://drive.google.com/file/d/0B3XVjcsci0y3LUpudko1S2c1cnc/view?usp=sharing
stat_density2d is used for plotting density maps, for example dark colours where there are lots of points and light colours where there's few. You have a regular grid with a Value attribute, not a density plot.
So you should be using geom_tile to get a regular grid map. But your lat-long coordinates do not form an axis-aligned grid. Try this:
ggplot(data = PM, mapping = aes(x = Longitude, y = Latitude, fill=Value)) + geom_tile()
and you get a blank plot, try this:
ggplot(data = PM, mapping = aes(x = UTM.X, y = UTM.Y, fill=Value)) + geom_tile()
and you get your plot. Of course its not in the same coordinate system as the ggmap background.
You can probably use base R's contourLines function to get the coordinates of contour lines in UTM coordinates, make a SpatialLinesDataFrame, then transform to Lat-long and add to a ggmap.
Another possibility to get what looks like a grid map is to use points with squares as the shape.
ggmap(POLA.map) + geom_point(data = PM, mapping = aes(Longitude, Latitude, colour=Value), size=4, alpha=0.5, shape=15) + scale_colour_gradient(low = 'green', high = 'red')
There's some artefacts where the grid cells overlap that look a bit like cell outlines, and the legend is showing with no opacity so looks more saturated than the cells. You'll have to get the size parameter right, as it depends on the size of your graphics device.
Failing all that, turn your data into a raster package raster object, save it as a GeoTIFF, and load it into QGIS, which can reproject UTM grids onto Lat-long on the fly.
QGIS also has some nice blending modes so you can do this pretty easily:
Note this is not transparency, this is multiplicative blending. Transparency causes dark colours to get washed out, whereas multiplicative blending lets black show through, so labelling and base map detail are still visible.
Also, note how the raster is not axis-aligned (especially obvious at the bottom).
Related
I am attempting to create a map for my PhD of some sampling locations in the rainforest, and I thought it would be cool to represent their elevation on the map as well, since it can be significant.
After much experimentation with plotting my points on DEM rasters I decided it is not the most visually clear way of doing it so I thought to turn the raster into a contour and represent it that way. So I found this wonderful tanaka package to create an astonishing contoured elevation map, and it looks great.
However now I run into the problem that I cannot seem to find the way how to plot my sampling points onto the tanaka plot.
I made a nice ggplot to represent the shape and color of the points with their longitude and latitude which would be great if I could integrate it. Is there a way?
Here are my lines for the tanakaplot and the ggplot.
tanaka(park, breaks = seq(25,250,25), legend.pos = "topright",
legend.title = "Elevation\n(meters)",
col = brewer.pal(n = 8, name = "Blues"))
ggplot(data = worldmap) +
geom_sf() +
geom_point(data = necropsies,
aes(x = lng, y = lat, color = anthrax, shape = anthrax), size = 2) +
scale_color_manual(values=c("green", "red")) +
coord_sf(xlim = c(-7.37, -7.255), ylim = c(5.775, 5.89))
Using ggplot I want to add points to a sf map. Take this code:
ggplot(data = shapefile) +
geom_sf()+
geom_point(x = -70.67,y =-33.45, size = 10, colour = "red")
This code works fine for one of my shapefiles but not for another, and I'm not sure why. Here's the code's output with my first shapefile:
And here's the code's output with the second shapefile:
Potential reasons for why the second call is not recognizing the coordinates? The only difference I'm seeing between the two plots is that in the first, longitude and latitude are annotated numerically, and in the second, after their north/south and east/west orientation.
The inconsistent behavior is due to different projections for each shapefile. You typically need to supply the point locations that match the units of the projection you are using. You could either convert the points to your shapefile's projection, or, if you don't care if the data are in a geographic coordinate system, you can convert to 4326 which is lat/long on WGS84 datum.
Method 1: Maintaining your shapefile's projection. This method will convert your point(s) to a spatial sf data type, so you can just plot with geom_sf.
pts <- st_point(c(-70.67, -33.45)) %>% st_sfc() %>% st_as_sf(crs=st_crs(4326))
ggplot(data = shapefile) +
geom_sf() +
geom_sf(data = pts, size = 10, colour = "red")
Method 2: Converting the shapefile to EPSG 4326.
ggplot(data = shapefile %>% st_transform(st_crs(4326))) +
geom_sf() +
geom_point(x = -70.67,y =-33.45, size = 10, colour = "red")
A few lines of code to expose my problem. When I work with a map of
the world and I introduce a projection, I always end up with some
weird looking horizontal lines.
Please have a look at
https://www.rdocumentation.org/packages/ggplot2/versions/1.0.0/topics/coord_map
from where I take the example for New Zeland
library(ggplot2)
nz <- map_data("nz")
# Prepare a map of NZ
nzmap <- ggplot(nz, aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "white", colour = "black")
# Plot it in cartesian coordinates
nzmap
# With correct mercator projection
nzmap + coord_map()
which works beautifully. Now let us do the same with the world
world <- map_data("world")
# Prepare a map of the world
worldmap <- ggplot(world, aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "white", colour = "black")
# Plot it in cartesian coordinates
worldmap
##but the following is a disaster!
# With correct mercator projection
worldmap + coord_map()
I see this issue of the horizontal lines with a projection has been
going on for quite a while, but I was able to find only seasoned posts
and I had assumed this was fixed long ago.
Please find below my sessionInfo.
Is there any solution to this? Is it still an open bug?
This is a pretty common problem in ggplot, but happily it is easily fixed:
worldmap + coord_map(xlim=c(-180,180))
produces
solution from: Why does coord_map produce a weird output?
I am trying to add a legend to a plot generated by ggmap package in R. The dataset I am working with is
Latitude Longitude amount
61.37072 -152.40442 436774
32.80667 -86.79113 3921030
34.96970 -92.37312 1115087
33.72976 -111.43122 5068957
The code I am using is
library(ggplot2)
library(ggmap)
MyMap <- get_map(location = c(lon = -96.5, lat = 40.68925), zoom = 4,maptype = "terrain", scale = 2)
ggmap(MyMap)+
geom_point(data = data,aes(x = Longitude , y = Latitude ),size=sqrt(data$amount)/800,col='darkred', shape = 19,alpha = .5)
Now I want to add legend to this plot. The legend should show the sizes of the circles on the map correspond to certain amount. How can I do it?
The size argument should be included within the aes() section of the geom_point function, as follows:
plot <- ggmap(MyMap) +
geom_point(data = data,aes(x = Longitude , y = Latitude, size=amount), col='darkred', shape = 19,alpha = .5)
plot
If you want to have further customisation of the scale, you can use the optional argument scale_size_area() to choose the breaks and labels for the legend. For example:
plot + scale_size_area(breaks = c(436774, 1115087, 4000000, 5068957),
labels = c("436774", "1115087", "4000000", "5068957"))
Change Point Size:
If you want to adjust the size of the points, you are better off using the scale_size function, which lets you specify a range:
plot + scale_size(range = c(5,9))
I am attempting to plot several shapefiles on top of a map generated through ggmap. This is working well, however I want to constrain the view area to the shapefile (and not rely on the zoom argument in ggmaps). I've done this by getting the bounding box and passing it as an argument in ggplot's coord_cartesian While this works, I am getting some tearing issues on the edges of the map - most specifically on the western portion. I've tried adjusting the x-y coordinates manually but it seems to only severely distort the picture.
My thoughts are to zoom out slightly to allow the entire shapefile to be plotted in the area, but I can't seem to figure it out. It's also possible I am going about this entirely in the wrong way.
Here's the code I used to generate the map. The shapefile can be downloaded here
library(dplyr)
library(ggmap)
library(rgdal)
library(broom)
# Read in shapefile, project into long-lat
# Create 'tbox' which is a minimum bounding box around the shapefile
tracts <- readOGR(dsn = ".", layer = "CensusTracts2010") %>%
spTransform("+proj=longlat +ellps=WGS84")
tbox <- bbox(tracts)
# Plot data
tract_plot <- tidy(tracts)
DetroitMap <- qmap("Detroit", zoom = 11)
DetroitMap + geom_polygon(data = tract_plot, aes(x = long, y = lat, group = id), color = "black", fill = NA) +
coord_cartesian(xlim = c(tbox[1,1], tbox[1,2]),
ylim = c(tbox[2,1], tbox[2,2]))
I followed your workflow, which resulted in the same problem as you mentioned above. Then I changed the zoom on the qmap option from 11 to 10 and it resulted in a much better picture, although you do lose some of the place names but you can add those in manually yourself with annotate:
DetroitMap <- qmap("Detroit", zoom = 10)
DetroitMap + geom_polygon(data = tract_plot, aes(x = long, y = lat, group = id), color = "black", fill = NA) +
coord_cartesian(xlim = c(tbox[1,1], tbox[1,2]),
ylim = c(tbox[2,1], tbox[2,2]))