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
Related
Here is my code:
m <- leaflet() %>%
addProviderTiles(providers$Stamen.Toner) %>%
setView(lng = -107.9917071, lat = 59.5, zoom = 3.5) %>%
addPolygons(data = plant,
color = "#660000",
weight = 1,
smoothFactor = 0.5) %>%
addCircleMarkers(lng = plant$lon, lat = plant$lat)
m
No matter what I try I get the following error message:
Error in polygonData.default(data) : Don't know how to get path
data from object of class spec_tbl_df
My data frame from which my data comes is a simple 5 row by 3 columns of coordinates and the name of the place.
Thoughts?
You had point data, not polygons.
library(leaflet)
plant <- data.frame(
stringsAsFactors = FALSE,
Name = c("University","University",
"University","University","University"),
lat = c(43.5339923, 49.8091536, 3.52682, 49.2519564, 45.5069177),
lon = c(-80.2244647,-97.1330418,
-113.5244937,-123.2465285,-73.5791163)
)
leaflet() %>%
addProviderTiles(providers$Stamen.Toner) %>%
setView(lng = -107.9917071, lat = 59.5, zoom = 3.5) %>%
# I removed the addPolygons(), you are adding points, not polygons
addCircleMarkers(lng = plant$lon, lat = plant$lat)
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)
With the code below I get my dataframe with US county data
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)
My object is to crate an interactive leaflet choropleth map of Avg_yield so first I fortify my USA polygon data
library(rgeos)
library(maptools)
library(ggplot2)
states.shp.f <- fortify(USA, region = "NAME_2")
Then I subset my dataset and merge it with the fortified:
mydata2<-mydata[,c("COUNTY_NAME","Avg_yield")]
colnames(mydata2)[1]<-"id"
## merge shape file with data
merge.shp.coef <- merge(states.shp.f, mydata2, by = "id")
but now I have a dataset with every county name many times and also some counties have different values of Avg_yield. Whats the proper way to process those data in order to use the leaflet code like:
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)
The propoer way to do this is to transform your polygon object into a sf object
with st_as_sf()
Here you have a working example :
(I did used some other data for the polygon, I thought yours too precise and require a lot of resources, plus I made it work with shiny)
library(leaflet)
library(tidyverse)
library(ggplot2)
library(sf)
library(shiny)
USA <- st_read(dsn = '[your path]/cb_2018_us_county_500k.shp')
### Get data
mydata <- read.csv("https://www.betydb.org/miscanthus_county_avg_yield.csv",
stringsAsFactors = FALSE)
states_sf <- st_as_sf(USA)
mydata2<-mydata[,c("COUNTY_NAME","Avg_yield")]
colnames(mydata2)[1]<-"NAME"
## merge shape file with data
states_sf_coef <- left_join(states_sf, mydata2, by = "NAME")
ui <- fluidPage(
leafletOutput("map", height = "100vh")
)
server <- function(input, output, session) {
bins <- c(0, 5, 10, 15, 20, 25, 30, 35, 40)
mypal <- colorBin("YlOrRd", domain = states_sf_coef$Avg_yield, bins = bins)
#Sortie map
output$map <- renderLeaflet({
leaflet()%>%
addProviderTiles("OpenStreetMap.Mapnik")%>%
setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
addPolygons(
data = states_sf_coef,
fillColor = ~mypal(states_sf_coef$Avg_yield),
stroke = FALSE,
smoothFactor = 0.2,
fillOpacity = 0.3,
popup = paste("Region: ", states_sf_coef$NAME_2, "<br>",
"Avg_yield: ", states_sf_coef$Avg_yield, "<br>"))%>%
addLegend(position = "bottomleft",
pal = mypal,
values = states_sf_coef$Avg_yield,
title = "Avg_yield",
opacity = 1)
})
}
# Create Shiny app ----
shinyApp(ui = ui, server = server)
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
My leaflet map looks something like this:
library(sp)
library(leaflet)
circleFun <- function(center = c(0,0),diameter = 1, npoints = 100){
r = diameter / 2
tt <- seq(0,2*pi,length.out = npoints)
xx <- center[1] + r * cos(tt)
yy <- center[2] + r * sin(tt)
Sr1 = Polygon(cbind(xx, yy))
Srs1 = Polygons(list(Sr1), "s1")
SpP = SpatialPolygons(list(Srs1), 1:1)
return(SpP)
}
Circle.Town <- circleFun(c(1,-1),2.3,npoints = 100)
df1 <- data.frame(long=c(0.6,1,1.4), lat=c(-2, -.8, -0.2), other=c('a', 'b', 'c'), VAM=c(10,8,6),
type=c('Public', 'Public', 'Private'), id=c(1:3)) %>%
mutate(X=paste0('<strong>id: </strong>',
id,
'<br><strong>type</strong>: ',
type,
'<br><strong>VAM</strong>: ',
VAM))
# Create a continuous palette function
pal <- colorNumeric(
palette = "RdYlBu",
domain = df1$VAM
)
leaflet(height = "400px") %>%
addTiles() %>%
addPolygons(data = Circle.Town, color = 'green', fillOpacity = .7) %>%
addCircleMarkers(data = df1, lat = ~lat, lng =~long,
radius = ~VAM, popup = ~as.character(X),
fillColor = ~pal(VAM),
stroke = FALSE, fillOpacity = 0.8,
clusterOptions = markerClusterOptions()) %>%
addLegend(position = "topright",
pal = pal, values = df1$VAM,
title = "VAM",
opacity = 1
) %>%
setView(lng = 1, lat = -1, zoom = 8)
Right now, I get a popup when I click one of the circles. Is it possible to get the information when I hover the mouse instead of click? Ideally, I would like something like this.
Thanks!
This may have been added to the leaflet package since this question was posed a year ago, but this can be done via the label argument. I am using leaflet R package version 1.1.0.
Read the data in as above:
library(sp)
library(leaflet)
library(dplyr)
circleFun <- function(center = c(0,0),diameter = 1, npoints = 100){
r = diameter / 2
tt <- seq(0,2*pi,length.out = npoints)
xx <- center[1] + r * cos(tt)
yy <- center[2] + r * sin(tt)
Sr1 = Polygon(cbind(xx, yy))
Srs1 = Polygons(list(Sr1), "s1")
SpP = SpatialPolygons(list(Srs1), 1:1)
return(SpP)
}
Circle.Town <- circleFun(c(1,-1),2.3,npoints = 100)
df1 <- data.frame(long=c(0.6,1,1.4), lat=c(-2, -.8, -0.2), other=c('a', 'b', 'c'), VAM=c(10,8,6),
type=c('Public', 'Public', 'Private'), id=c(1:3)) %>%
mutate(X=paste0('<strong>id: </strong>',
id,
'<br><strong>type</strong>: ',
type,
'<br><strong>VAM</strong>: ',
VAM))
# Create a continuous palette function
pal <- colorNumeric(
palette = "RdYlBu",
domain = df1$VAM
)
But create a list of labels instead of vector:
labs <- as.list(df1$X)
And then lapply the HTML function over that list within the label argument. Note to use label instead of popup.
library(htmltools)
leaflet(height = "400px") %>%
addTiles() %>%
addPolygons(data = Circle.Town, color = 'green', fillOpacity = .7) %>%
addCircleMarkers(data = df1, lat = ~lat, lng =~long,
radius = ~VAM, label = lapply(labs, HTML),
fillColor = ~pal(VAM),
stroke = FALSE, fillOpacity = 0.8,
clusterOptions = markerClusterOptions()) %>%
addLegend(position = "topright",
pal = pal, values = df1$VAM,
title = "VAM",
opacity = 1
) %>%
setView(lng = 1, lat = -1, zoom = 8)
This method is described in an an answer to this SO question: R and Leaflet: How to arrange label text across multiple lines
There is more info on HTML in labels in leaflet documentation:
https://rstudio.github.io/leaflet/popups.html
Here is an alternative:
library(leaflet)
library(htmltools)
library(htmlwidgets)
yourmap <- leaflet(height = "400px") %>%
addTiles() %>%
addPolygons(data = Circle.Town, color = 'green', fillOpacity = .7) %>%
addCircleMarkers(data = df1, lat = ~lat, lng =~long,
radius = ~VAM, popup = ~as.character(X),
fillColor = ~pal(VAM),
stroke = FALSE, fillOpacity = 0.8,
clusterOptions = markerClusterOptions()) %>%
addLegend(position = "topright",
pal = pal, values = df1$VAM,
title = "VAM",
opacity = 1
) %>%
setView(lng = 1, lat = -1, zoom = 8)
setwd("~/Desktop/")
saveWidget(yourmap, file="yourmap.html")
In your desktop, you will have an html and a folder saved under yourmap. Open the leaflet.js file located in /pathTo/yourmap_files/leaflet-binding-1.0.1.9002.
In leaflet.js, scroll down to var popup = df.get(i, 'popup');
and paste just below:
marker.on('mouseover', function (e) {
this.openPopup();
});
marker.on('mouseout', function (e) {
this.closePopup();
});
Save and reopen yourmap.html file. Hover on one of your point!!