1

Great R Gurus,

I am struggling to find a way to randomly mix discrete colors for my leaflet map for a large number of observations. The problem is the following command put similar colors next to each other which makes it hard to distinguish on the map.

library(leaflet) 
previewColors(colorFactor("RdYlBu", domain = NULL), LETTERS[1:26])

enter image description here

Is there any way to mix colors in a way it becomes A,Z,B,Y and so on...

Your time to answer is highly appreciated...

2 Answers 2

3

Maybe something like this:

library(leaflet) 
set.seed(50)
previewColors(colorFactor(sample(colors(),26), domain = NULL), LETTERS[1:26])

To get an output as follows:enter image description here

Or you could do something like this: library(leaflet) set.seed(500) previewColors(colorFactor(sample(rainbow(26),26), domain = NULL), LETTERS[1:26])

To get the output as follows: enter image description here

0
0

If you want to make it simpler, here is the code to randomize the basic colors:

    var colors = ['#FF5733', '#FFC300', '#36A2EB', '#4BC0C0', '#9966FF']; 
    function getRandomColor() {
        var randomcolor = Math.floor(Math.random() * colors.length);
        return colors[randomcolor];
    }
    var triangle = L.polygon([
    [10.251887,105.8978935],  // Toạ độ của vĩnh long
    [10.2354, 106.3753],   // Toạ độ của Bến Tre
    [10.0341844,105.7163705]    // Toạ độ của cần thơ
], {
        color: randomColor,     // Màu của đường viền
        fillColor: randomColor, // Màu của vùng bên trong
        fillOpacity: 0.5,       // Độ mờ của vùng bên trong
      
    }).addTo(map);             // Thêm polygon vào bản đồ
});
1
  • Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community? Commented May 25 at 1:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.