I want to plot each polygon with the color stated in the column 'Categories' in the dataframe 'new'
This is what the dataframe 'new' looks like:
palcat <- colorFactor(new$Categories)
## to delete the special characters in each polygon value (new$Polygon)
new$Polygon <- chartr('()[]',' ', new$Polygon)
#subset Polygon column
blocks <- new$Polygon
#### PLOT TO LEAFLET ####
map <- leaflet()
counter <- 1
for(i in blocks){
m <- matrix(as.numeric(strsplit(blocks,",")[[counter]]),ncol=2,byrow=TRUE)
palcat <- colorFactor(viridis(20), new$Categories)
map <- addPolygons(map, data = m, color = 'black', weight = 0.25,
smoothFactor = 0.5,opacity = 1.0, fillOpacity = 0.1,fillColor = ~palcat(Categories))
counter <- counter + 1
}
# map %>% addPolygons(new$Polygon, fillColor = colorFactor(new$Categories))
map
map %>% addProviderTiles(providers$CartoDB.Positron)
If you change the color directly in fillColor = "blue", it works
fillColor = colorFactor(new$Categories))
inside the addPolygon part but since it's inside the loop that turns each Polygon Cell to a Matrix its not working. Any ideas on how to fix this?
Answer
You need to use an id so that your function fillcolor
know which color of the vector is to be used. I proposed a reproducible example as you did not provide your own data:
# Create a polygons
xy = cbind(
x = c(13.4, 13.4, 13.6, 13.6, 13.4),
y = c(48.9, 49, 49, 48.9, 48.9)
)
# Create blocks as in your data
blocks <- c(paste(c(t(xy)), collapse = ", "), paste(c(t(xy+0.1)), collapse = ", "))
# Create vector of colors like your categories
fillColor <- c("blue", "red")
# Create id
id <- 1:2
map <- leaflet()
counter <- 1
for(i in blocks){
m <- matrix(as.numeric(strsplit(blocks,",")[[counter]]),ncol=2,byrow=TRUE)
map <- addPolygons(map, data = m, color = 'black', weight = 0.25,
smoothFactor = 0.5,opacity = 1.0, fillOpacity = 0.1,
fillColor = fillColor[id[counter]])
counter <- counter + 1
}
map
I did a blog article on multiple polygons in a loop with leaflet if needed.
Edit: Be careful when using color names, they should exist in html/css. Otherwise, you should better use hexa code.
So, doing that with your dataset should be:
# Create vector of colors like your categories
fillColor <- new$Categories
# Create id
id <- 1:nrow(new)
map <- leaflet()
counter <- 1
for(i in blocks){
m <- matrix(as.numeric(strsplit(blocks,",")[[counter]]),ncol=2,byrow=TRUE)
map <- addPolygons(map, data = m, color = 'black', weight = 0.25,
smoothFactor = 0.5,opacity = 1.0, fillOpacity = 0.1,
fillColor = fillColor[id[counter]])
counter <- counter + 1
}
map
If you still have problems, this may be in your dataset. In that case, you will need to share it.
No comments:
Post a Comment