I'm very new to R and I was just playing around with a project to plot projected population growth of Alabama counties from 2010 to 2020. Here's my code:
dat <- read.table("C:/Users/rasmus/Documents/countyinfo.txt", sep="\t", header=TRUE)
library(ggplot2)
library(maps)
library(ggmap)
mdat <- map_data('county')
str(mdat)
al1 = get_map(location = c(lon = -86.304474, lat = 32.362563),
zoom = 7, maptype = 'roadmap')
al1MAP = ggmap(al1) +
geom_point(data=dat,inherit.aes = FALSE,
aes(y=Lat, x=Lon, map_id=County, size=Growth), col="red") +
borders("state", colour="red", alpha=0.8) +
borders("county", colour="blue", alpha=0.5)
al1MAP
Now, I have two questions.
1) The state borders seem to be doing weird things. Here's a screenshot with the county overlay turned off:
2) Given that this is only about Alabama, I would like to turn borders outside the state borders off, but I don't know how to do that. My guess would be to experiment with xlim and ylim, but I don't know how to restrict those to the Alabama border polygon.
It seems that with function borders() for coordinates of some states are connected together.
To solve this problem you can store state borders as separate data frame using map_data() and then add state borders using geom_path() to your map. In geom_path() add group=region to ensure that points are connected only according one region.
To show borders just for the Alabama counties you should add argument region="alabama" to function borders().
al1 = get_map(location = c(lon = -86.304474, lat = 32.362563),
zoom = 6, maptype = 'roadmap')
mdat <- map_data('state')
ggmap(al1) +
geom_path(data=mdat,aes(x=long,y=lat,group=region),colour="red",alpha=0.8)+
borders("county", colour="blue", alpha=0.5,region="alabama")
Related
I am trying to get the black and white version of a stamen map and its giving me the color version. I've tried downloading the map with get_map and get_stamenmap and both give me the color version regardless of whether I specify color as "bw" or "color". Any ideas or work arounds?
library(ggmap)
mapImage <- get_map(location = c(lon = -110.8, lat = 34.7),
source = "stamen",
maptype = "terrain",
color = "bw",
zoom = 7)
g <- ggmap(mapImage)
To get black-and-white stamen maps, use maptype = "toner". The color argument has no effect on stamen maps. You might also want a panel border around the plot. If so, use ggplot's theme_bw() or theme(panel.border = element_rect(fill = NA, colour = "black")).
library(ggmap)
mapImage <- get_map(location = c(lon = -110.8, lat = 34.7),
source = "stamen",
maptype = "toner",
# color = "bw",
zoom = 7)
ggmap(mapImage) + theme_bw()
My solution was get_stamenmap with maptype="toner".
It is like get_map with source="stamen" speaks with a southern soft R and sloppy lisp dialect that stamen does not understand.
library(ggmap)
mapImage <- get_stamenmap(bbox = c(-114,32,-107,37),
source = "stamen",
maptype = "toner",
zoom = 7)
ggmap(mapImage) +theme_bw()
did the trick for me (using Rstudio in Linux, potential bug)
Notice bbox as the alternative to location and theme_bw() as Sandy suggested
I'm using library(choroplethr) for some market analysis and I have some questions about making my county_choropleth and either overlaying it on top of a ggmap() or using reference_map=TRUE in my code. What I'm trying to do is take my county choropleth and place state interstates/highways and draw circles/radii on top of it.
What I currently have is this:
library(choroplethr)
data <- Data.frame(County.FIPS = c(19153,19163,19153,19153,19153,19153,19153,19113,19007,19169), Score=c(812.6,769.5,757.9,757.2,722.6,712.4,69727,690.2,64539,642.5)
county <-aggregate(data$Score~data$County.FIPS,data=data,sum)
colnames(county) <- c("region", "value")
mp <- county_choropleth(county, state_zoom=c("iowa"), num_colors = 1) +
theme(legend.position="none")+
scale_fill_gradient2("Score",
high = "dark green",
low = "red",
na.value = "grey90",
breaks = pretty(county$value, n = 10),
label = scales::dollar_format())
...which gives me this plot.
From here, what I would like to do is overlay the main interstates in the state of Iowa on top of my map and also create some radius circles to show distance from certain cities in miles. I would like it to take elements from this map and ideally incorporate them into my choroplethr map because, in my opinion, it looks a lot cleaner than in this example:
I used this code to retrieve the second map:
library(ggmap)
test<-get_map(location = c(lon=-93.57217,lat=41.67269), maptype="roadmap",source="google",zoom=7,scale="auto")
yup <- data.frame(lon=c(-93.57217,-95.87509), lat=c(41.67269,41.23238),score=c(1,1))
ggmap(test) + stat_density2d(aes(x = lon, y = lat, fill = score,alpha=score),
size = 2, bins = 2, data = yup, geom = "polygon") +
theme(legend.position="none")
My main problem with using reference_map=TRUE in the choroplethr library is that it grays out labels, roads, etc. when I place my county_choropleth on top of it. e.g.,
So, is there an easy workaround for including roads and drawing circles on a map or do I need to abandon using choroplethr and move to ggmap, ggplot2 or something else? I also have been able to locate the Iowa DOT shapefiles for roads on their website, so that is an option to include, but I don't know how specifically to only ask it to use main interstates/highways when plotting and reading into R.
Here is my "ideal" MS Paint solution to this problem:
Thank you in advance for any and all help and please let me know if you have any clarification questions that need to be answered in order to help!
For those who stumble upon this later. I was able to achieve what I was hoping to do by changing libraries to leaflet and tigris.
I plan on making final tweaks for personal use, but here is the code used:
library(tigris)
library(leaflet)
data <- data.frame(County.FIPS = c(19153,19163,19153,19153,19153,19153,19153,19113,19007,19169), Score=c(812.6,769.5,757.9,757.2,722.6,712.4,69727,690.2,64539,642.5))
county <-aggregate(data$Score~data$County.FIPS,data=data,sum)
colnames(county) <- c("GEOID", "Score")
IA_counties <- counties(state="IA", cb=TRUE, resolution ="20m")
IA_merged <- geo_join(IA_counties,county,"GEOID", "GEOID")
pal <- colorQuantile("Greens",NULL,n=3)
popup <- paste0("Profitability: ", as.character(IA_merged$Score))
yup2 <- data.frame(lon=c(-93.57217,-95.93779),lat=c(41.67269,41.25861),score=c(1,1))
leaflet() %>%
addProviderTiles("Esri.WorldStreetMap") %>%
addLegend(pal = pal,
values = IA_merged$Score,
position = "bottomright",
title = "County Profitablity: ") %>%
addCircles(lng=yup2$lon, lat=yup2$lat,weight=1,fillOpacity=0.05,color="red",
radius = 96560) %>%
addCircles(lng=yup2$lon, lat=yup2$lat,weight=1,fillOpacity=0.025,color="blue",
radius = 193121) %>%
addPolygons(data = IA_counties,
fillColor = ~pal(IA_merged$Score),
fillOpacity = 0.15,
weight = 0.2,
popup = popup)
I would like to create a map that is not perfectly square but rectangular and is the size I dictate.
require(ggmap)
tenmile <- get_map(location = c(lon = -122.486328, lat = 48.862813),
color = "color",
source = "google",
maptype = "roadmap",
zoom = 12)
tenmile.map <- ggmap(tenmile,
extent = "device",
ylab = "Latitude",
xlab = "Longitude")+ggtitle("GEOMean for Data from Oct 2013-Nov 2014")
tenmile.map + geom_point(data=pp, aes(x=lon, y=lat, size=geomean), color="red", alpha=0.5) +
geom_text(data=pp, aes(x=lon, y=lat, label = site), size=3, vjust = 1.25, hjust = -0.1)
I would post pictures of what I get and what I want but I do not have enough reputation points to post images. =-(
Sandy Muspratt's answer produces a rectangular map, but it gets stretched. To get an unstretched map, ratio must be adjusted to the ratio between spacing of parallels and meridians at the place of the map. That is:
ratio = 1/cos(latitude)
If latitude is given in degrees, that becomes:
ratio = 1/cos(pi*latitude/180)
I give here an example using a map of Barcelona (Barcelona makes a good example to check for stretching because most of our streets form an square grid and deformation becomes easily noticeable).
library(ggmap) library(mapproj) mapbcn <- get_map(location =
'Barcelona, Catalonia', zoom = 13)
# square map (default) ggmap(mapbcn)
# map cropped by latitude
ggmap(mapbcn) +
coord_fixed(ylim=c(41.36,41.41),
ratio=1/cos(pi*41.39/180))
# map cropped by longitude
ggmap(mapbcn) +
coord_fixed(xlim=c(2.14, 2.18),
ratio=1/cos(pi*41.39/180))
It must be noted that this way coordinates keep working for the whole map (for example to add points to the map) if the area of the map is small enough not to take in account Earth's curvature - that is, to assume that meridians are parallel in the area shown by the map. It may be inaccurate in a map spanning some hundreds of kilometres and very wrong in a continent-scale map.
If you want to keep the original limits of the bounding box but simply to change its shape, you can adjust the aspect ratio. If you want to change the limits of the bounding box, then obtain the map as before but set its limits using coord_fixed() (or coord_cartesian()). Or you can adjust both the aspect ratio and the limits of the bounding box.
tenmile <- get_map(location = c(lon = -122.486328, lat = 48.862813),
color = "color",
source = "google",
maptype = "roadmap",
zoom = 12)
tenmile.map <- ggmap(tenmile,
ylab = "Latitude",
xlab = "Longitude")+ggtitle("GEOMean for Data from Oct 2013-Nov 2014") +
coord_fixed(xlim = c(-122.55, -122.40), ratio = 2/1)
I am creating maps using ggmap and am having trouble displaying some polygons and borders in my code. I have a map of a city that has parts of 3 counties in it. I would like to display the city along with the appropriate county lines. If I set the zoom such that all 3 counties are completely visible, then the county lines appear in the map. However, if I zoom to the portion of the city, the county lines disappear.
Example 1: County lines visible on map
tempplot <- get_map(location = c(lon = -97.37605, lat = 32.94748), zoom=9, maptype = 'roadmap')
myplot <- ggmap(tempplot) + borders ("county", colour = "red", alpha = 0.5, region = "Texas")
myplot <- myplot + geom_point(aes(x = -97.37605, y = 32.94748), color = "dodgerblue4", pch = 20, size = 9)
myplot
Image: http://imgur.com/nx3XU2I
Example 2: County lines partially visible on map
tempplot <- get_map(location = c(lon = -97.37605, lat = 32.94748), zoom=10, maptype = 'roadmap')
myplot <- ggmap(tempplot) + borders ("county", colour = "red", alpha = 0.5, region = "Texas")
myplot <- myplot + geom_point(aes(x = -97.37605, y = 32.94748), color = "dodgerblue4", pch = 20, size = 9)
myplot
Example 3: No county lines visible on map
tempplot <- get_map(location = c(lon = -97.37605, lat = 32.94748), zoom=12, maptype = 'roadmap')
myplot <- ggmap(tempplot) + borders ("county", colour = "red", alpha = 0.5, region = "Texas")
myplot <- myplot + geom_point(aes(x = -97.37605, y = 32.94748), color = "dodgerblue4", pch = 20, size = 9)
myplot
Image: http://imgur.com/dIpp6kp
The only difference between these 3 examples is the zoom on the map. I need the map to be at zoom 12 to see the additional details that I will be adding (individual homes), but when I zoom in, the county lines vanish. Any suggestions?
(Sorry about the links to the images ... I am new to the forum and don't have a 10 reputation yet!)
It appears that also the borders you get in example 1 are not 100% correct. You may check with a lower Zoom lever (eg 5).
To me it looks like there is a problem with borders that are cut off by the picture; the function then tries to connect it to an edge that is still visible. In the zoom level you provided even that is not possible, and therefore it has unexpected behaviour.
To sum up: I don't know what exactly the problem is, but maybe this short analysis helps in any way!
I am trying to plot my coordinates using R. I have tried already to follow different post (R: Plot grouped coordinates on world map ; Plotting coordinates of multiple points at google map in R) but I am not having much success with my data.
I am trying to achieve a flat map of the world with my gps coordinate as colored dots (each area a specific color):
area lat long
Agullhas -38,31 40,96
Polar -57,59 76,51
Tasmanian -39,47 108,93
library(RgoogleMaps)
lat <- c(-38.31, -35.50) #define our map's ylim
lon <- c(40.96,37.50) #define our map's xlim
center = c(mean(lat), mean(lon)) #tell what point to center on
zoom <- 2 #zoom: 1 = furthest out (entire globe), larger numbers = closer in
terrmap <- GetMap(center=center, zoom=zoom, maptype= "satallite", destfile = "satallite.png")
problem that now I don't know how to add my points and I will like one color for each region.
Could anyone help me going forward with it?
the other option I have tried is :
library(maps)
library(mapdata)
library(maptools)
map(database= "world", ylim=c(-38.31, -35.5), xlim=c(40.96, 37.5), col="grey80", fill=TRUE, projection="gilbert", orientation= c(90,0,225))
lon <- c(-38.31, -35.5) #fake longitude vector
lat <- c(40.96, 37.5) #fake latitude vector
coord <- mapproject(lon, lat, proj="gilbert", orientation=c(90, 0, 225)) #convert points to projected lat/long
points(coord, pch=20, cex=1.2, col="red") #plot converted points
but the coordinates ends in a wrong position and I am not sure why
Hope someone can help
As an alternative to RgoogleMaps, you can also use the combination ggplot2 with ggmap.
With this code:
# loading the required packages
library(ggplot2)
library(ggmap)
# creating a sample data.frame with your lat/lon points
lon <- c(-38.31,-35.5)
lat <- c(40.96, 37.5)
df <- as.data.frame(cbind(lon,lat))
# getting the map
mapgilbert <- get_map(location = c(lon = mean(df$lon), lat = mean(df$lat)), zoom = 4,
maptype = "satellite", scale = 2)
# plotting the map with some points on it
ggmap(mapgilbert) +
geom_point(data = df, aes(x = lon, y = lat, fill = "red", alpha = 0.8), size = 5, shape = 21) +
guides(fill=FALSE, alpha=FALSE, size=FALSE)
you get this result:
Another option is using the leaflet package (as suggested here). Unlike Google Maps it does not require any API key.
install.packages(c("leaflet", "sp"))
library(sp)
library(leaflet)
df <- data.frame(longitude = runif(10, -97.365268, -97.356546),
latitude = runif(10, 32.706071, 32.712210))
coordinates(df) <- ~longitude+latitude
leaflet(df) %>% addMarkers() %>% addTiles()
An other alternative, is the plotGoogleMaps package which allows to plot in a navigator, allowing to zoom in and out etc. You can then make a screenshot of your picture to save it (though remember google maps are legally supposed to be used for the internet).
library("plotGoogleMaps")
lat <- c(-38.31, -35.50) #define our map's ylim
lon <- c(40.96,37.50) #define our map's xlim
# make your coordinates a data frame
coords <- as.data.frame(cbind(lon=lon,lat=lat))
# make it a spatial object by defining its coordinates in a reference system
coordinates(coords) <- ~lat+lon
# you also need a reference system, the following should be a fine default
proj4string(coords) <- CRS("+init=epsg:4326")
# Note: it is a short for:
CRS("+init=epsg:4326")
> CRS arguments:
> +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
# then just plot
a <- plotGoogleMaps(coords)
# here `a <-` avoids that you get flooded by the html version of what you plot
And you get :
Here is a solution using only Rgooglemaps, as requested by the user.
# get map (from askers OP, except changed map type = "Satallite" to type = "Satellite")
library(RgoogleMaps)
lat <- c(-38.31, -35.50) #define our map's ylim
lon <- c(40.96,37.50) #define our map's xlim
center = c(mean(lat), mean(lon)) #tell what point to center on
zoom <- 2 #zoom: 1 = furthest out (entire globe), larger numbers = closer in
terrmap <- GetMap(center=center, zoom=zoom, type= "satellite", destfile = "satellite.png")
# plot points and save image
lat <- c(-38.31, -57.59, -39.47)
lon <- c(40.96, 76.51, 108.93)
png('map.png')
PlotOnStaticMap(terrmap, lat = lat, lon = lon, pch = 20, col = c('red', 'blue', 'green'))
dev.off()