0

I get to plot the location of properties on Google Maps. But as you can see I divided it into clusters. So, I need the points that were from the same clusters to have the same color. Can you help me?

Thank you very much!

library(googleway)
library(geosphere)

set_key( "API_KEY" )

swf1<-structure(list(Properties = c(1,2,3,4,5,6), Lat = c(-24.781624,-24.775017,-24.769196,-24.761741,-24.752019,-24.748008), 
                     Lon = c(-49.937369,-49.950576,-49.927608,-49.92762,-49.920608,-49.927707)), 
                    class="data.frame",row.names = c(NA, -6L))

#clusters
d<-as.dist(distm(swf1[,2:1]))
fit.average<-hclust(d,method="average") 
clusters<-cutree(fit.average, 5) 
swf1$cluster<-clusters

google_map() %>%
  add_markers(
    data = swf1, lon = "Lon", lat = "Lat")

enter image description here

Antonio
  • 1,091
  • 7
  • 24

1 Answers1

2

There are only 4 possible colors - red, blue, green and lavender.

The following code assigns one of those colors to each cluster based on modulo 4.

marker_colors<-c("red", "blue", "green", "lavender")
swf1$color <- marker_colors[swf1$cluster%% 4 +1]

google_map() %>%
  add_markers(
    data = swf1, lon = "Lon", lat = "Lat", colour="color")
norie
  • 9,609
  • 2
  • 11
  • 18
  • Thanks for the answer. There's some way to make a general function for color, you know? Because there will be cases with up to 20 clusters. – Antonio Aug 19 '21 at 21:17
  • The code I posted will work for however many clusters there are - each cluster will be assigned one of the 4 available colors. – norie Aug 19 '21 at 21:23
  • Cluster 5 got the same color as cluster 1 (in this case, blue). This I want to avoid. In this case, I want each cluster to have only one color. – Antonio Aug 19 '21 at 21:41
  • There are only 4 available colors. – norie Aug 19 '21 at 21:42
  • Can I insert more? – Antonio Aug 19 '21 at 21:43
  • I don't think so. If I try adding another color, say yellow, I get the error message `Error in markerColourIconCheck(data, objArgs, colour, marker_icon) : colours must be either red, blue, green or lavender` – norie Aug 19 '21 at 21:47
  • In leaflet map I got it, but not in Google Maps. If you can, take a look at this example: https://stackoverflow.com/questions/61591674/general-function-to-insert-the-colors-of-the-clusters-in-my-map-made-by-the -leaf – Antonio Aug 19 '21 at 21:55
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/236217/discussion-between-norie-and-jose). – norie Aug 19 '21 at 22:13
  • any idea for this question: https://stackoverflow.com/questions/71499596/generate-routes-between-two-points-in-google-maps-on-shiny – Antonio Mar 16 '22 at 15:27