Tuesday, 26 November 2019

carto - Automatically coloring a large number of polygons in CartoDB


I see that I can use the CartoDB wizard to color polygons I have based on a column value. This works great except that it only colors 6 or so polygons and the rest are lumped as “others”.



I see that I can edit the CSS and add the other polygons one at a time. My map has about 250 of these, so doing it one at a time isn’t practical. Is there a more automated way to, say, randomly assign a color from the palette to all the polygons based on a value in the table? It’s fine if there are duplicate colors.



Answer



I wrote a little script for this that solves the problem by generating all the CSS properties that you can then cut and paste into CartDB:


for (rep = 1; rep <= 800; rep++) {
var color = Math.floor(Math.random()*16777215).toString(16);
if (rep < 10) {
document.write('#mydiv[territory="T00' + rep + '"] {
polygon-fill:#' +color+';
}
');
}
if (rep >=10 && rep <100)
{

document.write('#mydiv[territory="T0' + rep + '"] {
polygon-fill:#' +color+';
}
');
}
if (rep >= 100) {
document.write('#mydiv[territory="T' + rep + '"] {
polygon-fill:#' +color+';
}
');
}
}

The extra if statements were necessary in my case because I had territories formatted like this "T001" and "T099".


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...