full usa map in R - r

I am trying to plot the dataset nycflight 2013. However I can't show the full usa map in r. Airports that are located in Hawaii and Alaska are not showing.
this is my code:
library(tidyverse)
library(plotly)
#reading
flight<-read.csv('flight.csv')
airports<-read.csv('airports.csv')
flighsort<-flight[order(flight$airline),]
#airports locations
airports<-read.csv('airports.csv')
#clearning data for map
#converting lon_Dest_airport from factor to character to map it
AirportsMap <- flight %>%
mutate(lon_Dest_airport = parse_number(as.character(lon_Dest_airport)))
#cleaning the original file to get the number of flights between each two airports
AirportsMap<-AirportsMap %>% group_by(origin_airport,dest_airport,lon_origin_airport,lat_origin_airport,
lon_Dest_airport,lat_Dest_airport) %>% tally()
#drawing the map
geo <- list(
scope = 'usa',
projection = list(type = 'world'),
showland = TRUE,
landcolor = toRGB("gray95"),
countrycolor = toRGB("gray80")
)
#adding marker for the three origin airports
plot_geo(locationmode = 'USA-states') %>%
add_markers(
data=airports, x = ~lon, y = ~lat, text=~airport,size = 0.1,
hoverinfo = "text",alpha = 0.5) %>%
#adding flights routes
add_segments(
data = AirportsMap,
x = ~lon_origin_airport, xend = ~lon_Dest_airport,
y = ~lat_origin_airport, yend = ~lat_Dest_airport,
alpha = 0.3
) %>%
#adding a title
layout(
title = 'NYC Flights 2013<br>(Hover for airport names)',
geo = geo, showlegend = FALSE
)
any help is appreciated. thanks

Related

Plotly Map New York City Using R

Plotly creates nice maps where the scope term defines the area. I'm wondering if I can make the map so it only shows New York City?
I've read the documentation on scope (https://plotly.com/python/reference/#layout-geo-scope), and see it does not involve any cities, so maybe someone else has a way to solve this?
library(plotly)
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
# geo styling
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showland = TRUE,
landcolor = toRGB("gray95"),
subunitcolor = toRGB("gray85"),
countrycolor = toRGB("gray85"),
countrywidth = 0.5,
subunitwidth = 0.5
)
fig <- plot_geo(df, lat = ~lat, lon = ~long)
fig <- fig %>% add_markers(
text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "<br />"),
color = ~cnt, symbol = I("square"), size = I(8), hoverinfo = "text"
)
fig <- fig %>% colorbar(title = "Incoming flights<br />February 2011")
fig <- fig %>% layout(
title = 'Most trafficked US airports<br />(Hover for airport)', geo = g
)
fig

Animated map using R

I have 30 years data for 15 stations with average temperature and want to create an animation using r studio (leaflet). I was looking at the some codes but it not working. An explanation on how to create timeseries animation using leaflet in r studio would be helpfull.
# install libraray
library(sp)
library(raster)
library(leaflet)
Temp53Yrs_df <- read.csv("C:/Users/Sownal/Documents/53YearsTemp.csv")
View(Temp53Yrs_df)
#make plots for the points in the map
leaflet() %>%
addTiles() %>%
addCircleMarkers(lat = Temp53Yrs_df$lat,
lng = Temp53Yrs_df$long)
# Add Data for Average Yearly Annual Temperature
col_pal <- colorNumeric(palette = "viridis",
domain = Temp53Yrs_df$X1965, reverse = TRUE)
#make years plot in the map
leaflet() %>%
addTiles() %>%
addCircles(lat = Temp53Yrs_df$lat,
lng = Temp53Yrs_df$long,
color = col_pal(Temp53Yrs_df$X1965),
radius = 20000,
fillOpacity = 0.4,
label = Temp53Yrs_df$X1965) %>%
addLegend(Temp53Yrs_df, position = "bottomleft", pal = col_pal,
values = Temp53Yrs_df$X1965, title = "Average Temperature in Year
1965")
#make years plot in the map
leaflet() %>%
addTiles() %>%
addCircles(lat = Temp53Yrs_df$lat,
lng = Temp53Yrs_df$long,
color = col_pal(Temp53Yrs_df$X1966),
radius = 20000,
fillOpacity = 0.4,
label = Temp53Yrs_df$X1966) %>%
addLegend(Temp53Yrs_df, position = "bottomleft", pal = col_pal,
values = Temp53Yrs_df$X1966, title = "Average Temperature in Year
1966")
#make years plot in the map
leaflet() %>%
addTiles() %>%
addCircles(lat = Temp53Yrs_df$lat,
lng = Temp53Yrs_df$long,
color = col_pal(Temp53Yrs_df$X1967),
radius = 20000,
fillOpacity = 0.4,
label = Temp53Yrs_df$X1967) %>%
addLegend(Temp53Yrs_df, position = "bottomleft", pal = col_pal,
values = Temp53Yrs_df$X1967, title = "Average Temperature in Year
1967")
#make years plot in the map
leaflet() %>%
addTiles() %>%
addCircles(lat = Temp53Yrs_df$lat,
lng = Temp53Yrs_df$long,
color = col_pal(Temp53Yrs_df$X1968),
radius = 20000,
fillOpacity = 0.4,
label = Temp53Yrs_df$X1968) %>%
addLegend(Temp53Yrs_df, position = "bottomleft", pal = col_pal,
values = Temp53Yrs_df$X1968, title = "Average Temperature in Year
1968")
Sample Data is attached below
enter image description hereenter image description here

Plotly animated map not showing countries with NA values

I posted this in the plotly community forum but got absolutely no activity! Hope you can help here:
I have map time-series data, some countries don’t have data and plotly does not plot them at all. I can have them outlined and they look different but it appears nowhere that the data is missing there (i.e. I want a legend entry). How can I achieve this? Here is a reprex:
library(plotly)
library(dplyr)
data = read.csv('https://github.com/lc5415/COVID19/raw/master/data.csv')
l <- list(color = toRGB("grey"), width = 0.5)
g <- list(
scope = 'world',
countrycolor = toRGB('grey'),
showframe = T,
showcoastlines = TRUE,
projection = list(type = 'natural earth')
)
map.time = data %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code, marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
map.time
Note that the countries with missing data (e.g. Russia) have as many data points as all other countries, the issue is not that they do not appear in the dtaframe passed to plotly.
The obvious way to handle this is to create a separate labels column for the tooltip that reads "No data" for NA values (with the actual value otherwise), then make your actual NA values 0. This will give a uniform appearance to all the countries but correctly tells you when a country has no data.
map.time = data %>%
mutate_if(is.numeric, function(x) {x[is.na(x)] <- -1; x}) %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code,
marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
Which gives:

Data mismatch between dataset and value in the leaflet map

I'm trying to create a choropleth map in county level using leaflet R package and I actually do it. But when I check my data file and the hover text of any county I find that the values are not correct. For example check the Conejos county. Any explanation? Or a better way to process tha data and create this map without the mismatches?
Code:
library(raster)
library(leaflet)
library(tidyverse)
# Get USA polygon data
USA <- getData("GADM", country = "usa", level = 2)
### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
stringsAsFactors = FALSE) %>%
dplyr::select(COUNTY_NAME, Avg_yield)
### Check counties that exist in USA, but not in mydata
### Create a dummy data frame and bind it with mydata
mydata <- data.frame(COUNTY_NAME = setdiff(USA$NAME_2, mydata$COUNTY_NAME),
Avg_yield = NA,
stringsAsFactors = FALSE) %>%
bind_rows(mydata)
### Create a color palette
mypal <- colorNumeric(palette = "viridis", domain = mydata$Avg_yield)
leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
addPolygons(data = USA, stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
fillColor = ~mypal(mydata$Avg_yield),
popup = paste("Region: ", USA$NAME_2, "<br>",
"Avg_yield: ", mydata$Avg_yield, "<br>")) %>%
addLegend(position = "bottomleft", pal = mypal, values = mydata$Avg_yield,
title = "Avg_yield",
opacity = 1)

Counting how many point are in the polygon of region [R]

I would like to ask how to calculate number of point that are in some region when we have longtitue and latitude variables of point and polygon of country and its regions.
I provided example below:
I would like to calculate how many point are in what regions (including zero when there is no point) and than add this variables to data2#data object so one can use count measures to fill each regions polygons.
library(leaflet)
library(tidyverse)
set.seed(101)
URL2 <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_FRA_2_sp.rds"
data2 <- readRDS(url(URL2))
URL3 <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_ESP_2_sp.rds"
data3 <- readRDS(url(URL3))
URL4 <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_PRT_2_sp.rds"
data4 <- readRDS(url(URL4))
URL5 <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_GBR_2_sp.rds"
data5 <- readRDS(url(URL5))
random_long_lat <-
data.frame(
long = sample(runif(300, min = -2.5, max = 15.99), replace = F),
lat = sample(runif(300, min = 42.69, max = 59.75), replace = F)
)
all <- rbind(data2, data3, data4, data5)
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(data=all, stroke = TRUE, color = "black", weight="", smoothFactor = 0.95,
fill = F) %>%
addCircles(lng = random_long_lat$long, lat = random_long_lat$lat)
# Here add new variable called count, that would count how many point are in the region
all#data
I would like the result so one can calculate something like this:
all#data <-
all#data %>%
mutate(counts = rnorm(nrow(all), 100, sd = 20))
cuts <- c(0, 5, 20, 40, 80, 150, max(all#data$counts))
cuts <- colorBin("Greens", domain = all$counts, bins = cuts)
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(data=all, stroke = TRUE, color = "white", weight="", smoothFactor = 0.95,
fillOpacity = 0.65, fillColor = ~cuts(all$counts)) %>%
addLegend(pal = cuts,
values = all$counts,
labFormat = labelFormat(suffix = " "),
opacity = 0.85, title = "How many point were counted in each region", position = "topright")
however I dont know is it posible to calculate number of point in each regions having just coordinances?
If you transform the points and France polygons to sf objects, you can use st_intersects() to count the number of points in each polygon.
Note that I updated your sample points so that each quintile break in cuts is unique. With your original data, the first three quintiles were just 0 so the coloring in the leaflet map didn't work.
new sample data
library(leaflet)
library(tidyverse)
set.seed(101)
URL2 <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_FRA_2_sp.rds"
data2 <- readRDS(url(URL2))
random_long_lat <-
data.frame(
long = sample(runif(1000, min = -2.5, max = 5.99), replace = F),
lat = sample(runif(1000, min = 42.69, max = 49.75), replace = F)
)
make sf objects and count points in polygons
library(sf)
data_sf <- data2 %>% st_as_sf()
random_long_lat_sf <- random_long_lat %>%
st_as_sf(coords = c("long", "lat"), crs = 4326)
data_sf_summary <- data_sf %>%
mutate(counts = lengths(st_intersects(., random_long_lat_sf)))
define breaks for legend and draw map
cuts <- quantile(data_sf_summary$counts, probs = seq(0, 1, 0.2))
cuts <- colorBin("Greens", domain = data_sf_summary$counts, bins = cuts)
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(data=data_sf_summary, stroke = TRUE, color = "white", weight="", smoothFactor = 0.95,
fillOpacity = 0.65, fillColor = ~cuts(data_sf_summary$counts)) %>%
addLegend(pal = cuts,
values = data_sf_summary$hdp,
labFormat = labelFormat(suffix = " "),
opacity = 0.85, title = "How many point were counted in each region", position = "topright")
Also note that tmap package, which lets you switch between static and interactive maps using the same syntax (which resembles ggplot syntax).
same map with tmap:
library(tmap)
tmap_mode("view") # make map interactive
tm_shape(data_sf_summary) +
tm_polygons(col = "counts",
n = 5,
palette = "Greens",
title = "How many point were counted in each region")
static map with tmap:
library(tmap)
tmap_mode("plot") # make map static
tm_shape(data_sf_summary) +
tm_polygons(col = "counts",
n = 5,
palette = "Greens",
title = "How many point were counted in each region") +
tm_layout(legend.position = c("right","top"))
For multiple countries
First create new sample points that cover Europe:
random_long_lat <-
data.frame(
long = sample(runif(1000, min = -7.5, max = 19.99), replace = F),
lat = sample(runif(1000, min = 38.69, max = 60.75), replace = F)
)
all <- rbind(data2, data3, data4, data5)
Then make the sf objects and find the counts of points in every polygon:
all_sf <- all %>% st_as_sf()
random_long_lat_sf <- random_long_lat %>%
st_as_sf(coords = c("long", "lat"), crs = 4326)
all_sf_summary <- all_sf %>%
mutate(counts = lengths(st_intersects(., random_long_lat_sf)))
qtm(random_long_lat_sf)
Option 1: Choose maps from a list object by name using the NAME_0 column.
tmap_mode("view") # make maps interactive
list_of_maps <- map(unique(all_sf_summary$NAME_0),
~ tm_shape(all_sf_summary %>%
filter(NAME_0 == .x)) + # filter the data for your country of interest
tm_polygons(col = "counts",
n = 5,
palette = "Greens",
alpha = 0.85,
border.col = NA,
title = "How many point were counted in each region") +
tm_layout(legend.position = c("right","top"))) %>%
set_names(unique(all_sf_summary$NAME_0))
list_of_maps[['France']]
list_of_maps[['Portugal']]
Option 2: Show all the maps at once
### all maps at once
tm_shape(all_sf_summary) + # filter the data for your country of interest
tm_polygons(col = "counts",
n = 5,
palette = "Greens",
alpha = 0.85,
border.col = NA,
title = "How many point were counted in each region") +
tm_layout(legend.position = c("right","top")) +
tm_facets(by = c("NAME_0"), ncol = 2, showNA = FALSE)

Resources