Sorry for this very basic question but I'm new using Tigris. I would like create a shapefile (and then plot it) of county boundaries + places boundaries for the state of Minnesota.
Here is my code to get the counties:
mn_counties = tigris::counties(cb = T) %>%
filter(STUSPS == 'MN')
And here is my code to get the intersection between places and counties:
mn_places = tigris::places(cb = T) %>%
filter(STUSPS == 'MN') %>%
sf::st_intersection(mn_counties)
However, when I plot the intersection of these maps (counties and places), I just can see the polygons for the places map, but not for the counties.
tm_shape(mn_places) + tm_polygons()
Can anyone please tell me how to get an intersection of counties and places: 1. using tigris and, 2. that I'm able to see both places and county boundaries?
Many thanks in advance!!!
If I am understanding you correctly, you want places and counties in the same dataset. This is accomplished with dplyr::bind_rows():
library(tigris)
library(dplyr)
library(tmap)
mn_counties_and_places <- counties(state = "MN", cb = TRUE) %>%
bind_rows(
places(state = "MN", cb = TRUE)
)
tm_shape(mn_counties_and_places) +
tm_polygons()
Related
I am using Covid data & looking to plot State & district level Indian data on map.
I have State, District Name of India along with Cases but do not have needed lat, long for them.
I came across this so post How to map an Indian state with districts in r?
and tried raster::getData("GADM", country = "India", level = 2) %>% as_tibble() but this doesn't work as it doesnt have lat,lon, shapefile etc.
library(raster)
library(rgdal)
library(rgeos)
state_level_map <- raster::getData("GADM", country = "India", level = 1) %>%
as_tibble() %>%
filter(NAME_1 == "Rajasthan") %>%
fortify()
ggplot() +
geom_map(data= state_level_map, map = state_level_map,
aes(x = long, y = lat, map_id = id, group = group))
I am new to spatial data / maps and not sure how exactly I can proceed in this situation. Is it possible to get lat, lon, shapefile etc. for State/districts name's info from any r packages or the only way is to manually google them for lat,lon ?
Appreciate any help.
You were almost there. Use sf for that.
library(raster)
library(sf)
library(rgeos)
library(dplyr)
state_level_map <- raster::getData("GADM", country = "India", level = 1) %>%
st_as_sf() %>%
filter(NAME_1 == "Rajasthan")
ggplot() +
geom_sf(data = state_level_map)
you can then easily use aes() to change your aesthetics of the ggplot as you normally would using variables.
sf uses a dataframe-like notation that incorporates both attribute data as well as geometries into a single and easy to use dataframe. just have a look at print(state_level_map). That is, you could join data using district names to augment you attributes and visualize them through aes(color = yourjoinedvar).
I am using usmap and ggplot to plot population on a map. My data has two columns - population and zipcodes.
Question: How can I display data on city level using the same libraries or if you know of other libraries that can do the job.
Question: I am plotting California map and I want to zoom on LA county and nearby counties.
Below code gives me a nice California map and population as a color.
library(usmap)
library(ggplot2)
usmap::plot_usmap("counties",
include = ("CA") )
plot_usmap(data = data, values = "pop_2015", include = c("CA"), color = "grey") +
theme(legend.position = "right")+scale_fill_gradient(trans = "log10")
The tigris package makes downloading zip code tabulation areas fairly simple. You can download as a simple features dataframe so joining your data by zip code using dplyr functions is fairly easy. Here is a quick example:
library(tigris)
library(dplyr)
library(ggplot2)
df <- zctas(cb = TRUE,
starts_with = c("778"),
class = "sf")
## generate some sample data that
## can be joined to the downloaded data
sample_data <- tibble(zips = df$ZCTA5CE10,
values = rnorm(n = df$ZCTA5CE10))
## left join the sample data to the downloaded data
df <- df %>%
left_join(sample_data,
by = c("ZCTA5CE10" = "zips"))
## plot something
ggplot(df) +
geom_sf(aes(fill = values))
Rephrasing the question...I am preparing report and one part of it is spatial viz.
I have 2 datasets. First(Scores) is countries with their scores. Second one (Locations) is exact longitude and latitude that refers to an exact location inside those countries. Let that be examples:
Scores = data.frame( Country = c("Lebanon","UK","Chille"), Score =c(1,3.5,5))
Locations = data.frame(Location_Name = c("London Bridge", "US Embassy in Lebanon" , "Embassy of Peru in Santiago"),
LONG = c(-0.087749, 35.596614, -70.618236),
LAT = c(51.507911, 33.933586, -33.423285))
What i want to achieve is get filled map of the world (in my dataset i have every country) and color inside of its boundouries with the Score (Scores$Score) on continous scale.
On top of that I would like to add pins, bubbles or whatever marker of Locations from Locations dataframe.
So my desired outcome would be combination of this view:
and this view:
Ideally i would like also to be able to draw 2km radius around the Locations from Locations data.frame also.
I know to do them separately but cant seem to achieve it on one nice clean map.
I really appreciate any help or tips on this, got stuck for whole day on that one
As suggested by #agila you can use the tmap package.
First merge your Scores data with World so you can fill countries based on Scores data. Note that your Country column should match the name in World exactly when merging.
You will need to use st_as_sf from sf package to make your Locations an sf object to add to map.
tm_dots can show points. An alternative for bubbles is tm_bubbles.
library(tmap)
library(sf)
data(World)
Scores = data.frame(Country = factor(c("Mexico","Brazil","Chile"), levels = levels(World$name)),
Score =c(1,3.5,5))
Locations = data.frame(Location_Name = c("Rio de Janeiro", "US Embassy in Lebanon" , "Embassy of Peru in Santiago"),
LONG = c(-43.196388, 35.596614, -70.618236),
LAT = c(-22.908333, 33.933586, -33.423285))
map_data <- merge(World, Scores, by.x = "name", by.y = "Country", all = TRUE)
locations_sf <- st_as_sf(Locations, coords = c('LONG', 'LAT'))
tm_shape(map_data) +
tm_polygons("Score", palette = "-Blues") +
tm_shape(locations_sf) +
tm_dots(size = .1)
Map
I'm struggling with a problem. I'd like to separate two countries by adding some space between them. The idea is, for example, to explode europe, by still showing each country but with e predefined space between each country.
I'm using R and ggplot for the project I'm working and until now I tried to look for some answer on the web but could not find anything. You can get something by changing the size but that solution will also imply a loss on the details of the map.
If you could help that would be super great!
A bit hacky, but you can try to scale the polygons to <100% of the originals...
library(sf)
library(magrittr)
sample data
#read shapefile with country polygons
# source: http://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip
map <- st_read( "./data/countries/TM_WORLD_BORDERS-0.3.shp" )
#filter out some relevant countries
benelux <- c("Belgium", "Luxembourg", "Netherlands")
map <- map %>% filter( NAME %in% benelux )
#what do we have?
ggplot() + geom_sf( data = map )
code
#scale the polygons to 75% of original
#extract geometry
map.sfc = st_geometry(map)
#get centroids
map.centroid = st_centroid(map.sfc)
#recalculate geometry, scale to 75%
map.scale = ( map.sfc - map.centroid ) * 0.75 + map.centroid
#replace original geoemtry by recalculated geometry. set crs back to WGS84
map.scale_sf = st_set_geometry(map, map.scale) %>% st_set_crs( 4326 )
#ewhat do we have now?
ggplot() + geom_sf( data = map.scale_sf )
I'm making a map with arc lines connecting between counties for the US state of Missouri. I've calculated the 'good enough' centres of each county by taking the mean of each polygon's long/lat. This works good for the more or less square-shaped counties, but less so for the more intricately shaped counties. I think that this must be a common occurrence, but I can't find the answer online or with any function I've created. I'd like to use a tidyverse work flow (i.e. not transform to spatial objects if I can help it). Are there any tidyverse solutions to the problem at hand.
You can see the problem in the examples below.
library(tidyverse)
# import all state/county fortified
all_states <- as_tibble(map_data('county'))
# filter for missouri
mo_fortify <- all_states %>%
filter(region == 'missouri')
## Pull Iron county, which is relatively oddly shaped
mo_iron_fortify <- mo_fortify %>%
group_by(subregion) %>%
mutate(long_c = mean(long),
lat_c = mean(lat),
iron = ifelse(subregion == 'iron','Iron','Others')) %>%
ungroup()
# map a ggplot2 map
mo_iron_fortify %>%
ggplot(aes(long, lat, group = group))+
geom_polygon(aes(fill = iron),
color = 'white')+
geom_point(aes(long_c, lat_c))+
scale_fill_grey('Iron county is\na good example')+
coord_map()+
theme_bw()