########################################################################## # # PREP SCRIPT: STAT22 ########################################################################## # # Dear all, # Please load in the following packages and data # before our presentation. In the case that something # does not work, please contact us BEFORE our presentation. # Many thanks and best, # Mason Wirtz # Melanie Achleitner ################################## # # PRELIMINARIES ---- ################################## # # empty workspace rm(list = ls()) # libraries if (!require("pacman")) install.packages("pacman") pacman::p_load( tidyverse, # data manipulation leaflet, # mapping sf, # for working with spatial data gplots, # hex colors (see col2hex() function) tidygeocoder # geocoding ) # set ggplot theme (optional) theme_set(theme_minimal(12)) theme_update(plot.background = element_rect(fill = "white", color = NA)) # set seed set.seed(4444) ################################## # # DATA ---- ################################## # # Please run the following codes. This will load in the data sets we will need # for our presentation. If something does NOT work, please contact us # immediately so we can figure it out BEFORE our presentation :) # BARS IN SALZBURG DATASET barsSalzburg = read_csv('https://raw.githubusercontent.com/MasonWirtz/STAT22/main/barsSalzburg.csv') # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DESCRIPTION # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # This data set is self made and has to be directly downloaded from my github page. # The data set houses all the bars in Salzburg, with their long and lat data. # The rating variable is their stars, and the reviews is the NUMBER of reviews # left on Google. # HOME ADDRESS # Add your home address in the following code, # making sure it is under quotation marks! address = tribble( ~name, ~street, ~city, ~country, "Home", "Glaserstraße 30A", "Salzburg", "Austria", "Uni", "Hellbrunnerstraße 34", "Salzburg", "Austria") %>% geocode(street = street, city = city, country = country, method = "osm") # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DESCRIPTION # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # This provides a data frame containing your home adress and # the address of the university (NAWI). It creates the long # and lat of both addresses. # BIKERIDE DATASET bikeRoute = read_csv("https://raw.githubusercontent.com/MasonWirtz/STAT22/main/bikeRoute.csv") # can also be loaded via the following code: # read_csv("https://www.dropbox.com/s/zc6jan4ltmjtvy0/mallorca_bike_day7.csv?dl=1") %>% # select(1:4, speed) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DESCRIPTION # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # This data set is taken from Lisa Lendway and provides the data for a bike # ride. It has the long and lat data, and the ele variable stands for # elevation. Note that speed is in miles per hour. # STARKBUCKS DATASET starbucks = read_csv("https://www.macalester.edu/~ajohns24/Data/Starbucks.csv") %>% # rename variables with space to make # plotting easier rename(storeNumber = "Store Number", storeName = "Store Name", ownType = "Ownership Type", strtAdd = "Street Address", state = "State/Province", phone = "Phone Number") # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DESCRIPTION # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # The starbucks dataset comprises many Starbucks stores (I think all of them?) # and has information pertaining to their location. The most important # information for us will be the long and lat variables. # AMAZONE DATASET stations_df = read_csv('http://s3.amazonaws.com/assets.datacamp.com/production/course_6355/datasets/stations_data.csv') # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DESCRIPTION # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # The stations_df dataframe has information on Amazon's warehouses, including # the rough address and the long and lat variables. # INFO # For a list of maps, see providers preview: https://leaflet-extras.github.io/leaflet-providers/preview/ # NORTH CAROLINA DATASET nc = st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE) %>% mutate(sid_per_1000birth_79 = SID79/BIR79*1000) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DESCRIPTION # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # North Carolina births and sids deaths. The function st_read() downloads # the shape file for the counties of North Carolina. This function is # included in the sf package. # The dataset has the number of births and number of SIDS cases # in each county (like a Bezirk) of NC from 1974-1979 and 1979-1984. # As in (https://mapping-in-r.netlify.app/#Using_leaflet_to_create_maps), # we computed a variable `sid_per_1000birth_79'. This is the number of # SIDS cases per 1000 births in 1979. ################################## # # POWERPOINT EXAMPLES ---- ################################## # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Example 1: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ barsSalzburg %>% # data frame leaflet() %>% # base plot addTiles() %>% # base map addMarkers() # add makers (lat and long automatically read) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Example 2: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ barsSalzburg %>% # data frame leaflet() %>% # base plot addTiles() %>% # base map # variables MUST be marked by ~ addMarkers(lng = ~long, lat = ~lat, label = ~name) # popup also possible # of cause lng, lat & label can be also entered manually, but it's #not so handy especially for larger data sets leaflet()%>% addTiles()%>% addMarkers(lng= 13.05803, lat= 47.80684, label = "The Jigger Bar") #OR leaflet()%>% addTiles()%>% addMarkers(lng= barsSalzburg$long, lat= barsSalzburg$lat, label = barsSalzburg$name) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Example 3: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ leaflet()%>% addTiles() #using setView() to set center & zoom level leaflet()%>% addTiles()%>% setView(lng= 13.05803, lat= 47.80684, zoom=10) # center & zoom to The Jigger Bar #using fitBounds() to center & zoom to an specific geographical point leaflet()%>% addTiles()%>% fitBounds(lng1=13.05803,lat1=47.80684, lng2=13.05803,lat2=47.80684) #center & zoom to The Jigger Bar #using setMaxBounds() that you don't lose the focus leaflet()%>% addTiles()%>% setView(lng= 13.05803, lat= 47.80684, zoom=10)%>% setMaxBounds(lng1=13.05803,lat1=47.80684, lng2=13.05803,lat2=47.80684) #using leaflet(options=leafletOptions()) to stay focused barsSalzburg%>% leaflet(options = leafletOptions(dragging= FALSE, minZoom = 12, maxZoom = 14))%>% addTiles()%>% addMarkers() #additional information about the zoom: #the following link gives a good overview about the zoom in leaflet: #https://leafletjs.com/examples/zoom-levels/ #to sum up: at zoom level 0 the whole world ist depicted in 256 pixels wide and 256 pixels high #zoom level one: it doubles its width and height, and can be represented by four 256-pixel-by-256-pixel images #At each zoom level, each tile is divided in four, #and its size doubles, quadrupling the area. #in other words, the width and height of the world is 256·2zoomlevel pixels # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Brief activity 1: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create a simple map of the bars in Salzburg # Using addMarkers(), add # label each bar in Salzburg with the # NAME of the bar (i.e., label argument) # use the popup argument to have the street # name of bar appear on click # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Brief activity 1: Solution ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ barsSalzburg %>% # data frame leaflet() %>% # base plot addTiles() %>% # base map addMarkers(lng = ~long, lat = ~lat, label = ~name, popup = ~street) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Example 4: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ providers # browse through the more than 100 base maps names(providers) barsSalzburg %>% leaflet() %>% addProviderTiles(providers$Stamen.Watercolor) %>% addMarkers(lng = ~long, lat = ~lat, label = ~name) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Example 5: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ?addControl #info about graphics elements and layers barsSalzburg %>% leaflet() %>% addProviderTiles(providers$Stamen.Watercolor) %>% addCircleMarkers(lng = ~long, lat = ~lat, label = ~name, weight = 8, opacity = 1, color = col2hex("hotpink")) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Example 6: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ barsSalzburg %>% leaflet() %>% addProviderTiles(providers$CartoDB.DarkMatter) %>% addCircleMarkers(lng = ~long, lat = ~lat, label = ~name, weight = 8, opacity = 1, color = col2hex("hotpink")) %>% addPolylines(lng = ~long, lat = ~lat, color = col2hex("darkred")) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Brief activity 2: UGLY MAP CONTETST ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Using the starbucks df, create a map of all starbucks in Austria # (hint: you’ll need ‘filter’ to include only stores in “ATâ€) # Experiment with the different provider tiles using # addProviderTiles(providers$...) to create base map # Experiment with extra addControl functions, colors, etc. # Label the stores by ‘storeNumber’ # GOAL: Who can create the UGLIEST map? # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Example 7: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ col = colorNumeric(palette = "magma", # domain: possible values that can be mapped domain = bikeRoute$ele) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Example 8: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ bikeRoute %>% leaflet() %>% addProviderTiles(providers$CartoDB.DarkMatter) %>% addCircles(lng = ~lon, lat = ~lat, # since col is a function # we need to apply the # function to a variable color = ~col(ele)) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Example 9: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #legend order: from small elevation to large elevation: bikeRoute %>% leaflet() %>% addProviderTiles(providers$CartoDB.DarkMatter) %>% addCircles(lng = ~lon, lat = ~lat, color = ~col(ele)) %>% addLegend(position = "topright", pal = col, values = ~ele) #legend order: from large elevation to small elevation bikeRoute %>% leaflet() %>% addProviderTiles(providers$CartoDB.DarkMatter) %>% addCircles(lng = ~lon, lat = ~lat, color = ~col(ele)) %>% addLegend(position = "topright", pal = col, values = ~ele, labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE))) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Example 10: ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ nc %>% leaflet() %>% addTiles() %>% addPolygons() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Brief activity 3: COLOR THE CHOROPLETH MAP ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Using the map created in Example 9: # 1. Color the the counties by sid_per_1000birth_79. # 2. Use the color palette "viridis" # 3. Change the base map to one of your choosing # NOTE: The colors will be difficult to see. We # will cover how to fix this in the next set # of examples. And you can ignore the warning. # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Brief activity 3: SOLUTION ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ col = colorNumeric("viridis", domain = nc$sid_per_1000birth_79) nc %>% leaflet() %>% addProviderTiles(providers$Stamen.Watercolor) %>% addPolygons( fillColor = ~col(sid_per_1000birth_79)) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Brief activity 4: ADDING AESTHETICS ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 1. Using the map from the previous activity, ... # 1.1. Change fillOpacity to change the transparancy of the choropleth map # 1.2. Add highlights to each polygon. In the addPolygons() function, # add highlight = highlightOptions(...) and experiment with # the different highlight options (see ?highlightOptions) # 1.3. Add a popup for each polygon with the NAME of each county # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Brief activity 4: SOLUTION ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ col = colorNumeric("viridis", domain = nc$sid_per_1000birth_79) nc %>% leaflet() %>% addProviderTiles(providers$Stamen.Watercolor) %>% addPolygons( fillColor = ~col(sid_per_1000birth_79), fillOpacity = .5, highlight = highlightOptions(weight = 5, color = "black", fillOpacity = 0.9, bringToFront = FALSE), popup = ~NAME) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Brief activity 5: Find your way to the NAWI ---- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # save your address and the NAWI address in a dataframe #(hint: maybe you already did it at the beginning of the lesson) # 1. map your home address and the NAWI address # in a base map of your choice # 2. set boundaries that you don't lose the focus # 3. add fancy markers & and a popup with the name # 4. mark your way from home to the NAWI in your favourite color # (colors: https://www.rapidtables.com/convert/color/rgb-to-hex.html) address = tribble( ~name, ~street, ~city, ~country, "Home", "Glaserstraße 30A", "Salzburg", "Austria", "Uni", "Hellbrunnerstraße 34", "Salzburg", "Austria") %>% geocode(street = street, city = city, country = country, method = "osm") address%>% leaflet()%>% setMaxBounds(lng1=13.08,lat1=47.77, lng2=13.08,lat2=47.77)%>% addTiles()%>% addCircleMarkers(lng = address$long, lat = address$lat, label = address$name, weight = 5, opacity =0.5, color = col2hex("cyan"), popup= address$name)%>% addPolylines(lng = address$long, lat = address$lat, color = col2hex("hotpink"))