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
Related
I am using an excel sheet for data. One column has FIPS numbers for GA counties and the other is labeled Count with numbers 1 - 5. I have made a map with these values using the following code:
library(usmap)
library(ggplot2)
library(rio)
carrierdata <- import("GA Info.xlsx")
plot_usmap( data = carrierdata, values = "Count", "counties", include = c("GA"), color="black") +
labs(title="Georgia")+
scale_fill_continuous(low = "#56B1F7", high = "#132B43", name="Count", label=scales::comma)+
theme(plot.background=element_rect(), legend.position="right")
I've included the picture of the map I get and a sample of the data I am using. Can anyone help me put the actual Count numbers on each county?
Thanks!
Data
The usmap package is a good source for county maps, but the data it contains is in the format of data frames of x, y co-ordinates of county outlines, whereas you need the numbers plotted in the center of the counties. The package doesn't seem to contain the center co-ordinates for each county.
Although it's a bit of a pain, it is worth converting the map into a formal sf data frame format to give better plotting options, including the calculation of the centroid for each county. First, we'll load the necessary packages, get the Georgia data and convert it to sf format:
library(usmap)
library(sf)
library(ggplot2)
d <- us_map("counties")
d <- d[d$abbr == "GA",]
GAc <- lapply(split(d, d$county), function(x) st_polygon(list(cbind(x$x, x$y))))
GA <- st_sfc(GAc, crs = usmap_crs()#projargs)
GA <- st_sf(data.frame(fips = unique(d$fips), county = names(GAc), geometry = GA))
Now, obviously I don't have your numeric data, so I'll have to make some up, equivalent to the data you are importing from Excel. I'll assume your own carrierdata has a column named "fips" and another called "values":
set.seed(69)
carrierdata <- data.frame(fips = GA$fips, values = sample(5, nrow(GA), TRUE))
So now we left_join our imported data to the GA county data:
GA <- dplyr::left_join(GA, carrierdata, by = "fips")
And we can calculate the center point for each county:
GA$centroids <- st_centroid(GA$geometry)
All that's left now is to plot the result:
ggplot(GA) +
geom_sf(aes(fill = values)) +
geom_sf_text(aes(label = values, geometry = centroids), colour = "white")
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))
Hi I've been working a lot but have not gotten really any clear answers. Basically I have a dataframe with sites and chemical analyses from those sites, whose coordinates I was able to convert into a geometry using st_as_sf. I am also using a separate shapefile named Cave_initial. Now what I want to do is plot the points from the dataframe on top of the shapefile as a single map.
I have tried using geom_sf() but at the very best it plots the points on one graph and then the shapefile as a separate graph. But I need them together.
Master_cave_data <- read_xlsx("./JW_cave_master_version.xlsx", range = "C2:AK85") #dataset containing chemical data and lat/long as numerics
cave_system <- st_read("./IllinoisCaverns/Cave_System.shp") #shapefile created by colleague
Master_cave_data <- Master_cave_data %>%
st_as_sf(coords = c('Long_DD', 'Lat_DD'), crs = 4326, sf_column_name = NULL)
#transforming my coordinate data into lat/long
#due to size of datashet dput will not be advisable to display. New column is created using Long/Lat_DD as geometry.
Jul_Data <- filter(Master_cave_data, Month == "Jul") # filtering data for one month
Jul_Coliform_Data_map <- Jul_Data %>%
ggplot() +
geom_sf(data = Jul_Data$Geometry) +
Cave_initial
Jul_Coliform_Data_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 trying to map the different denominations of the pencil in France. With the following code, I can achieve the map I want, the different colors representing the different items, and the score the rate of use of each item per department/region.
ggplot() +
geom_polygon(data = plotDatafr, aes(x=long, y = lat, group = group, fill=item, alpha=score), colour = NA) +
scale_fill_manual(values = c("#009E73", "#F0E442", "#0072B2", "#D55E00"), name = "", na.value=NA) +
coord_map()
I m now trying to find a way to smooth a little bit the color transitions between departments/regions. The map here gives an idea of what I m trying to achieve. My data is here. I'm aware of this post and I tried to follow this tutorial, but none of them is helpful for my problem.
EDIT
To create the map above, I calculated for each department the percentage of answers for a given item (5 different items) according to the total number of participants for each department (8272 participants in total). For each department, I then selected the item that received the max percentage, and plot these items on the map. I provided in this folder the raw data of the survey.
Description of the data
"id_part": the participant ; "PLZ": the zipcode of the participant's city
; "Lat"/"Long": long and lat values of the participant's city
; "NOM_DEPT": the department/region where the participant's city is located
; The rest of the columns indicate the answers (5 choices)
Shapefile is provided in the folder, I used this code to join the data (after having calculated and extracted the item with max percentage for each department) with the shapefile:
library(rgdal)
mapa <- readOGR(dsn="France",layer="DEPARTEMENT")
mapa <- spTransform(mapa, CRS("+proj=longlat +datum=WGS84"))
mapa#data$id <- rownames(mapa#data)
mapa#data <- join(mapa#data, data, by="NOM_DEPT")
mapa.df <- fortify(mapa)
mapa.df <- join(mapa.df,mapa#data, by="id")
plotDatafr <- join(mapa.df, data)