sjaikumar sjaikumar - 1 year ago 123
Javascript Question

Color code LineString drawin using D3.js

How do I color code lines 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)

type: "LineString",
coordinates: [
[ data[i].OperatorOwnerLon, data[i].OperatorOwnerLat ],
[ data[i].CountryOfContractorLon, data[i].CountryOfContractorLat ],
[ data[i].lon, data[i].lat ]

Answer Source

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:

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 ='#cities');
var colorPick = d3.scaleOrdinal(d3.schemeCategory10);

data.forEach(d => {
        .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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download