sjaikumar sjaikumar - 10 days ago 5
Javascript Question

Color code LineString drawing using D3.js

How do I color code line strings based on a unique value that I read from a CSV file? I wish to generate a line string which have different colors based on every row read from a CSV file.

for(var i=0, len=data.length-1; i<len; i++){
// (note: loop until length - 1 since we're getting the next
// item with i+1)

links.push({
type: "LineString",
coordinates: [
[ data[i].OperatorOwnerLon, data[i].OperatorOwnerLat ],
[ data[i].CountryOfContractorLon, data[i].CountryOfContractorLat ],
[ data[i].lon, data[i].lat ]
]
})

Answer

d3.js doesn't have any native display features. It relies on HTML, CSS, SVG, Canvas, or whatever other display technology you choose. Since you're doing text lines, HTML and CSS are more than adequate.

You didn't say how you wanted to make lat/lon coordinates to colors, so I will choose a simpler example, using city names. Assume the CSV is:

City,Country,Population
Shanghai,China,24256800
Karachi,Pakistan,23500000
Beijing,China,21516000
São Paulo,Brazil,11895893

Say your HTML has a div where you want to put the text:

<div id='cities'></div>

First you should probably define a function to choose the color based on each row of data. I'll use a standard color scheme. Then loop through your data, adding colored lines:

var cities = d3.select('#cities');
var colorPick = d3.scaleOrdinal(d3.schemeCategory10);

data.forEach(d => {
  cities.append('p')
        .style('color', colorPick(d.City))
        .text(d.City + ', ' + d.Country);
});

That's the core of it. With a little more prettification, the result looks like:

This is a simple "first one gets first color, second one gets second color, ..." coloring scheme. It works well for a lot of things.

Comments