d3: linearly interpolate only close-enough points - javascript

Suppose I have an array of values with corresponding dates, [{date: d1, value: v1}, ..., {date: dn, value: vn}], that I'd like to visualize using d3.js. As long as subsequent measurements are within a certain time range, for example not more than a week apart, I am happy with d3 interpolating between the measurements.
However, when subsequent records are farther apart, I don't want d3 to connect them. What would be the easiest way to achieve this?

Your question is not exactly clear: by "interpolate", I believe you mean "connecting the dots".
If you use a time scale for your x axis, D3 will automatically connect the dots for you and create a line (an SVG path element), regardless the time separation in the data points. But there is a way for making "gaps" in that line: using line.defined(). According to the API:
If defined is specified, sets the defined accessor to the specified function or boolean and returns this line generator.
The problem is, for this approach to work, you'll have to set a given value (let's say, null) in your dataset, between the dates in which you don't want to draw the line (that is, the dates that are not close enough, as you say in your question). You can do this manually or using a function.
This is a working demo: in my dataset, my data jumps from 7-Oct to 17-Oct (more than 1 week). So, I just created a null value in any date between these two (in my demo, 16-Oct). Then, in the line generator, the line jumps this null value, using defined:
d3.line().defined(function(d){return d.value != null;})
The result is that the line jumps from 7-Oct to 17-Oct:
var data = [{date: "1-Oct-16",value: 14},
{date: "2-Oct-16",value: 33},
{date: "3-Oct-16",value: 12},
{date: "4-Oct-16",value: 43},
{date: "5-Oct-16",value: 54},
{date: "6-Oct-16",value: 71},
{date: "7-Oct-16",value: 32},
{date: "16-Oct-16",value: null},
{date: "17-Oct-16",value: 54},
{date: "18-Oct-16",value: 14},
{date: "19-Oct-16",value: 34},
{date: "20-Oct-16",value: 32},
{date: "21-Oct-16",value: 56},
{date: "22-Oct-16",value: 24},
{date: "23-Oct-16",value: 42},
{date: "24-Oct-16",value: 52},
{date: "25-Oct-16",value: 66},
{date: "26-Oct-16",value: 34},
{date: "27-Oct-16",value: 62},
{date: "28-Oct-16",value: 48},
{date: "29-Oct-16",value: 51},
{date: "30-Oct-16",value: 42}];
var parseDate = d3.timeParse("%d-%b-%y");
data.forEach(function (d) {
d.date = parseDate(d.date);
});
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 200);
var xScale = d3.scaleTime().range([20, 480]);
var yScale = d3.scaleLinear().range([180, 10]);
xScale.domain(d3.extent(data, function (d) {
return d.date;
}));
yScale.domain([0, d3.max(data, function (d) {
return d.value;
})]);
var xAxis = d3.axisBottom(xScale).tickFormat(d3.timeFormat("%d"));
var yAxis = d3.axisLeft(yScale);
var baseline = d3.line()
.defined(function(d){return d.value != null;})
.x(function (d) {
return xScale(d.date);
})
.y(function (d) {
return yScale(d.value);
});
svg.append("path") // Add the valueline path.
.attr("d", baseline(data))
.attr("fill", "none")
.attr("stroke", "teal");
svg.append("g")
.attr("transform", "translate(0,180)")
.call(xAxis);
svg.append("g")
.attr("transform", "translate(20,0)")
.attr("class", "y axis")
.call(yAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>

If you're trying to draw a broken line chart, then I don't think interpolation is what you're looking for. Building a custom SVG path is probably the way to go. See an example here:
https://bl.ocks.org/joeldouglass/1a0b2e855d2bedc24c63e396b04c8e36

Related

Dynamically update directive data

Sorry, maybe it's stupid question but i'm still learning.
I'm trying to make one simple line chart using D3.js in angularJS. everything working fine and in that i am using a custom directive to plot the chart using D3. I am adding the chart data in the controller itself by using $scope.initially it will plot but i will change the data in one button click but the chart is not updating automatically,
after reading angularjs documentation i understand by using $scope we can able to change the UI content dynamically.whether it is possible here or any other scenario is present in angularJs
I am a beginner in AngularJS
<div data-ng-app="chartApp" data-ng-controller="SalesController">
<h1>Today's Sales Chart</h1>
<div linear-chart chart-data="salesData"></div>
<button type="button" data-ng-click="Change()">Click Me!</button>
</div>
My JS code
var app = angular.module('chartApp', []);
app.controller('SalesController', ['$scope', function($scope){
$scope.salesData=[
{hour: 1,sales: 54},
{hour: 2,sales: 66},
{hour: 3,sales: 77},
{hour: 4,sales: 70},
{hour: 5,sales: 60},
{hour: 6,sales: 63},
{hour: 7,sales: 55},
{hour: 8,sales: 47},
{hour: 9,sales: 55},
{hour: 10,sales: 30}
];
$scope.Change = function () {
//here i am changing the data so i need to replot the chart
$scope.salesData=[
{hour: 1,sales: 14},
{hour: 2,sales: 16},
{hour: 3,sales: 77},
{hour: 4,sales: 10},
{hour: 5,sales: 60},
{hour: 6,sales: 63},
{hour: 7,sales: 55},
{hour: 8,sales: 47},
{hour: 9,sales: 55},
{hour: 10,sales: 30}
];
}
}]);
//creating one custom directive to plot the chart
app.directive('linearChart', function($window){
return{
restrict:'EA',
template:"<svg width='850' height='200'></svg>",
link: function(scope, elem, attrs){
var salesDataToPlot=scope[attrs.chartData];
//if u gave like this u can remove attributr chart-data
// var salesDataToPlot=scope.salesData
var padding = 20;
var pathClass="path";
var xScale, yScale, xAxisGen, yAxisGen, lineFun;
var d3 = $window.d3;
var rawSvg=elem.find('svg');
var svg = d3.select(rawSvg[0]);
function setChartParameters(){
xScale = d3.scale.linear()
.domain([salesDataToPlot[0].hour, salesDataToPlot[salesDataToPlot.length-1].hour])
.range([padding + 5, rawSvg.attr("width") - padding]);
yScale = d3.scale.linear()
.domain([0, d3.max(salesDataToPlot, function (d) {
return d.sales;
})])
.range([rawSvg.attr("height") - padding, 0]);
xAxisGen = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(salesDataToPlot.length - 1);
yAxisGen = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5);
lineFun = d3.svg.line()
.x(function (d) {
return xScale(d.hour);
})
.y(function (d) {
return yScale(d.sales);
})
.interpolate("basis");
}
function drawLineChart() {
setChartParameters();
svg.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0,180)")
.call(xAxisGen);
svg.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(20,0)")
.call(yAxisGen);
svg.append("svg:path")
.attr({
d: lineFun(salesDataToPlot),
"stroke": "blue",
"stroke-width": 2,
"fill": "none",
"class": pathClass
});
}
drawLineChart();
}
};
});
Fiddle
Here you go a live example:
http://jsfiddle.net/7dc3efrc/1/
scope.$watch(attrs.chartData, function(newValue) {
if (newValue) {
svg.selectAll("*").remove();
drawLineChart(newValue);
}
}, true);
Use $watch method of scope to trigger update on model change. Also, don't forget to clear previous graph if you don't need it (svg.selectAll("*").remove()).
Please, see full example as I've made some minor modifications to your salesDataToPlot variable (it is now a function parameter).
You can use $watch on scope to listen to salesData data changes and rebuild your chart when it's done.
//...
scope.$watch('salesData', function (newSalesData){
// drawLineChart();
// redraw logic
});
//...

Invalid value for <circle> attribute r="NaN" in D3 scatterplot code

I am getting a NaN error on the r value in a d3 scatterplot.
Console error: Error: Invalid value for attribute r="NaN"
From this section of the code:
g.selectAll(".response")
.attr("r", function(d){
return responseScale(d.responses);
})
.attr("cx", function(d){
return x(d.age);
})
.attr("cy", function(d){
return y(d.value);
})
Here is how the scale is set up:
var responseScale = d3.scale.linear()
.domain(d3.extent(data, function(d){
return d.responses;
}))
.range(2, 15);
Here is a sample of the data:
var data = [
{glazed: 3.14, jelly: 4.43, powdered: 2.43, sprinkles: 3.86, age: 18, responses: 7},
{glazed: 3.00, jelly: 3.67, powdered: 2.67, sprinkles: 4.00, age: 19, responses: 3},
{glazed: 2.00, jelly: 4.00, powdered: 2.33, sprinkles: 4.33, age: 20, responses: 3},
I have tried putting a plus sign in front of d.responses and using parseFloat().
The code is an example used in this course, Learning to Visualize Data with D3.js (chapter on Creating a Scatterplot)
Any suggestions would be greatly appreciated!
In your code:
var responseScale = d3.scale.linear()
.domain(d3.extent(data, function(d){
return d.responses;
}))
.range(2, 15);
The parameter for the range() function should be an array of values, like this: .range([2,15]);
corrected scale:
var responseScale = d3.scale.linear()
.domain(d3.extent(data, function(d){
return d.responses;
}))
.range([2, 15])
;
More info on scales can be found here. If you are still in trouble, let me know!

d3 force directed graph, links not being drawn

I'm new to d3 and haven't much web frontend development experience. For a web application I have I'm trying to draw a force directed graph. I've been trying the last few hours to get it to work. I've been looking at lots of different code example and what I'm doing looks very similar. I eventually got nodes to draw but the links between the nodes don't show up and I was trying different things and nothing seems to work. I don't know why my code wouldn't draw the edges.
From printing the nodes and links to the console I saw that the nodes got extra attributes like the d3 docs had mentioned but the links never seem to get these attributes. Below is my javascript file and the JSON file. I reduced the JSON file to only 3 entries to try and make it easier to solve the problem.
var height = 1080;
var width = 1920;
var color = d3.scale.category20();
var force = d3.layout.force()
.linkDistance(-120)
.linkStrength(30)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("/static/javascript/language_data.json", function(data){
force
.nodes(data.languages)
.links(data.language_pairs)
.start();
var link = svg.selectAll(".link")
.data(data.language_pairs)
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(data.languages)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.call(force.drag);
node.append("title")
.text(function(d) { return d.language; });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
});
Here is the JSON file:
From looking at few examples my understanding is that the source and target are index positions from the list of nodes.
{
"languages":[
{"language": "TypeScript", "group": 1},
{"language": "Java", "group": 2},
{"language": "VHDL", "group": 3}
],
"language_pairs":[
{"source": "0", "target": "1", "value": 5},
{"source": "1", "target": "2", "value": 5},
{"source": "2", "target": "0", "value": 5}
]
}
Sorry if I left out anything! Thanks for any help!
Two issues:
1.) Your "language_pairs" source/target indexes are strings and not numbers. Get rid of the quotes:
"language_pairs":[
{"source": 0, "target": 1, "value": 5},
{"source": 1, "target": 2, "value": 5},
{"source": 2, "target": 0, "value": 5}
]
2.) Your linkDistance and linkStrength parameters don't make sense:
var force = d3.layout.force()
.linkDistance(-120) // negative distance?
.linkStrength(30) // according to the docs, this must be between 0 and 1?
.size([width, height]);
Here's an example that fixes these problems.

Updating a choropleth map with a dropdown button

First, please excuse my poor english.
I'm working on a project with a grid-map and an external csv.
The grid-map is not composed of rectangles or hexagons but only with the centroid of any kind of symbol that will be use at the end.
So I have a Topojson file with centroids "ID" and centroids "Coordinates".
The external CSV is composed of several columns, the first one with the same centroids "ID" and the other one with value for different year.
"ID","C2001","C2002","C2003","C2004","C2005","C2006","C2007","C2008","C2009","C2010","C2000"
6050,"-5.55753","-5.55914","-5.75444","-5.76307","-5.81660","-5.99361","-6.02150","-6.15979","-5.73530","-6.30509","-5.52990"
6051,"-5.55753","-5.55914","-5.75444","-5.76307","-5.81660","-5.99361","-6.02150","-6.15979","-5.73530","-6.30509","-5.52990"
Here is my code
var width = 960,
height = 600;
var options = [
{date: "2000", selected: "+d.C2000"},
{date: "2001", selected: "+d.C2001"},
{date: "2002", selected: "+d.C2002"},
{date: "2003", selected: "+d.C2003"},
{date: "2004", selected: "+d.C2004"},
{date: "2005", selected: "+d.C2005"},
{date: "2006", selected: "+d.C2006"},
{date: "2007", selected: "+d.C2007"},
{date: "2008", selected: "+d.C2008"},
{date: "2009", selected: "+d.C2009"},
{date: "2010", selected: "+d.C2010"},
];
var color = d3.scale.threshold()
.domain([-1985, -1400, -1000, -700, -300, -100, -25, -0])
.range(["#7f0000", "#b30000", "#d7301f", "#ef6548", "#fc8d59", "#fdbb84", "#fdd49e", "#fee8c8", "#fff7ec"]);
var path = d3.geo.path()
.projection(null)
.pointRadius(1.5);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
queue()
.defer(d3.json, "CO2_light.json")
.defer(d3.csv, "tdd_CO2_emissions.csv")
.await(ready);
function ready(error, centroid, CO2) {
var rateById = {};
console.log(rateById); //To
//CO2.forEach(function(d) { rateById[+d.ID] = +d.C2000; }); WORKING FINE = value in rateById
CO2.forEach(function(d) { rateById[+d.ID] = options[0].selected; }); //NOT WORKING = inside rateById "+d.C2000" instead the value
svg.selectAll("path")
.data(topojson.feature(centroid, centroid.objects.CENTROID).features)
.enter().append("path")
.attr("class", "centerGrid")
.attr("d", path)
.style("fill", function(d) { return color(rateById[+d.properties.ID]); });
d3.select(".loading").remove();
For the moment I leave the button for my next problem and I'm focus on this two line below
//CO2.forEach(function(d) { rateById[+d.ID] = +d.C2000; }); WORKING FINE = value in rateById
CO2.forEach(function(d) { rateById[+d.ID] = options[0].selected; }); //NOT WORKING = inside rateById "+d.C2000" instead the value
If I use the first line I get a nice grid-map (see image) but if I'm trying to access at value of a specific year from the options array with the second line and do console.log(rateById); I get this
Object
6050: "+d.C2000"
6051: "+d.C2000"
6712: "+d.C2000"
Instead of this
Object
6050: -6.30509
6051: -6.30509
6712: -7.0441
Fixed here: http://jsfiddle.net/z7sLdyu2/2/
2 changes to do in your code:
First, your options select should not contain javascript code to be executed (+d.), but only the year values:
var options = [
{date: "2000", selected: "C2000"},
{date: "2001", selected: "C2001"},
{date: "2002", selected: "C2002"},
{date: "2003", selected: "C2003"},
{date: "2004", selected: "C2004"},
{date: "2005", selected: "C2005"},
{date: "2006", selected: "C2006"},
{date: "2007", selected: "C2007"},
{date: "2008", selected: "C2008"},
{date: "2009", selected: "C2009"},
{date: "2010", selected: "C2010"}
];
Then in the loop, assign the rateById value by accessing the data d property for the selected year like this:
rateById[+d.ID] = +d[options[0].selected];
P.S.: I had to remove part of your code in your jsfiddle, as the centroids json was not found in your version of the jsfiddle, leading to errors not related to the problem of this question.

Configure fixed-layout static graph in d3.js

I have a working code example (only the <script type="text/javascript"> part) of a static graph using d3.js as below:
/* Create graph data */
var nodes = [];
for (var i = 0; i < 13; i++)
{
var datum = {
"value": i
};
nodes.push(datum);
}
var links = [{"source": 0, "target": 1},
{"source": 1, "target": 2},
{"source": 2, "target": 0},
{"source": 1, "target": 3},
{"source": 3, "target": 2},
{"source": 3, "target": 4},
{"source": 4, "target": 5},
{"source": 5, "target": 6},
{"source": 5, "target": 7},
{"source": 6, "target": 7},
{"source": 6, "target": 8},
{"source": 7, "target": 8},
{"source": 9, "target": 4},
{"source": 9, "target": 11},
{"source": 9, "target": 10},
{"source": 10, "target": 11},
{"source": 11, "target": 12},
{"source": 12, "target": 10}];
/* Create force graph */
var w = 800;
var h = 500;
var size = nodes.length;
nodes.forEach(function(d, i) { d.x = d.y = w / size * i});
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("weight", h);
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.linkDistance(200)
.size([w, h]);
setTimeout(function() {
var n = 400
force.start();
for (var i = n * n; i > 0; --i) force.tick();
force.stop();
svg.selectAll("line")
.data(links)
.enter().append("line")
.attr("class", "link")
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
svg.append("svg:g")
.selectAll("circle")
.data(nodes)
.enter().append("svg:circle")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 15);
svg.append("svg:g")
.selectAll("text")
.data(nodes)
.enter().append("svg:text")
.attr("class", "label")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.attr("text-anchor", "middle")
.attr("y", ".3em")
.text(function(d) { return d.value; });
}, 10);
and it produces this rather scrambled layout:
While it is technically the correct graph, the ideal layout should be something like this (ignoring the different visual graphics):
Note that the layout should be fixed so that reloading the page does not change the positioning of each node; the layout should also be static, in that there is no animation effect and the nodes are not draggable. Both requirements are already achieved in the script above.
So how should I further configure this d3 script to produce a layout shown in the second image?
First, increase the charge strength and reduce the link distance. Doing so places a greater emphasis on global structure rather than local connections. Also, if you increase the charge strength enough, the repulsive charge will push even directly-connected nodes farther apart, thus effectively increasing the link distance while giving better overall structure. (The downside of a stronger charge force is that graph initialization is more chaotic, but this shouldn’t be a problem for static layouts.)
Second, you may need to increase the number of iterations or add custom forces to get better results. Force layouts often work well on arbitrary graphs, but there’s no guarantee that they will produce an optimal (or even good) result. For any graph where you can make simplifying assumptions (for example, trees), there may be additional forces or constraints that you can apply to encourage the simulation to converge onto a better solution.

Categories