Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning different icons based on a factor

Tags:

r

leaflet

I'm trying to plot a map of all trees located in Melbourne. The link to the dataset I'm using is over here - Melbourne Urban Tree Data

In the dataset i want to assign different icons based on the column name "Genus" which looks something like this: enter image description here

Right now I'm able to get circles in the final plot: enter image description here

The code that I've used so far:

library(leaflet)
library(dplyr)

td <- read.csv("treedata.csv", header = TRUE)
m <- leaflet(td) %>% addTiles('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', 
                              attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>')
m %>% addCircles(~Longitude, ~Latitude, popup=paste("Name:", td$CommonName), weight = 3, radius=3, 
                 color="#ffa500", stroke = TRUE, fillOpacity = 0.8)
like image 469
Arvind Suryanarayana Avatar asked Jun 07 '26 04:06

Arvind Suryanarayana


1 Answers

As mentioned in the comment from @TimSalabim, try using markers with icons. For the fun of it:

library(leaflet)
library(dplyr)
library(readr)
download.file("https://data.melbourne.vic.gov.au/api/views/fp38-wiyy/rows.csv?accessType=DOWNLOAD", tf <- tempfile(fileext = ".csv"))
set.seed(1)
td <- read_csv(tf) %>% 
  sample_n(500) %>% 
  mutate(Genus = factor(ifelse(Genus %in% c("Quercus", "Corymbia", "Platanus", "Ulmus", "Eucalyptus"), Genus, "other"))) 
m <- leaflet(td) %>% 
  addTiles(urlTemplate = 'http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
           attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>')
myicons <- iconList(
  Quercus = makeIcon("https://i.sstatic.net/okgqd.png",iconWidth = 8, iconHeight = 8),
  Corymbia = makeIcon("https://i.sstatic.net/nfGZT.png",iconWidth = 8, iconHeight = 8),
  Platanus = makeIcon("https://i.sstatic.net/J47uj.png",iconWidth = 8, iconHeight = 8),
  Ulmus = makeIcon("https://i.sstatic.net/idnpO.png",iconWidth = 8, iconHeight = 8),
  Eucalyptus = makeIcon("https://i.sstatic.net/6GzzW.png",iconWidth = 8, iconHeight = 8),
  other = makeIcon("https://i.sstatic.net/x0bOg.png",iconWidth = 8, iconHeight = 8)
)
m %>% addMarkers(~Longitude, ~Latitude, popup=paste("Name:", td$`Common Name`),
                 icon = ~myicons[Genus])

gives something like:

enter image description here

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

like image 150
lukeA Avatar answered Jun 09 '26 08:06

lukeA