Related
Adapting a histogram with D3 (v3) I find two problems to solve (original code here):
<script type="text/javascript">
var faithfulData = [20,21,26,18,24,24,25,25,21,20,20,18,28,23,17,26,27,27,20,28,23,26,];
var datos_unicos = Array.from(new Set(faithfulData))
var margin = {top: 4, right: 10, bottom: 40, left: 40},
width = 360 - margin.left - margin.right,
height = 180 - margin.top - margin.bottom;
var cant_ticks = datos_unicos.length;
var edad_min = Math.min.apply(Math, datos_unicos) - 3;
var edad_max = Math.max.apply(Math, datos_unicos) + 3;
var vartickValues = []
var tope = (edad_max)+1;
for (var i =edad_min; i< tope; i++) {
vartickValues.push(i);
}
var x = d3.scale.linear()
.domain([edad_min, edad_max])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, .1])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.tickValues(vartickValues)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format("%"));
var line = d3.svg.line()
.x(function(d) { return x(d[0]); })
.y(function(d) { return y(d[1]); });
var histogram = d3.layout.histogram()
.frequency(false)
.bins(cant_ticks);
var svg = d3.select("#plantel_distribucion").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x plantel_axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("class", "label")
.attr("x", width)
.attr("y", 34)
.style("text-anchor", "end")
.text("Edad de las jugadoras");
svg.append("g")
.attr("class", "y plantel_axis")
.call(yAxis);
var data = histogram(faithfulData),
kde = kernelDensityEstimator(epanechnikovKernel(7), x.ticks(100));
svg.selectAll(".plantel_bar")
.data(data)
.enter().insert("rect", ".axis")
.attr("class", "plantel_bar")
.attr("x", function(d) { return x(d.x) + 1; })
.attr("y", function(d) { return y(d.y); })
.attr("width", x(data[0].dx + data[0].x) - x(data[0].x) - 1)
.attr("height", function(d) { return height - y(d.y); });
svg.append("path")
.datum(kde(faithfulData))
.attr("class", "plantel_line")
.attr("d", line);
//});
function kernelDensityEstimator(kernel, x) {
return function(sample) {
return x.map(function(x) {
return [x, d3.mean(sample, function(v) { return kernel(x - v); })];
});
};
}
function epanechnikovKernel(scale) {
return function(u) {
return Math.abs(u /= scale) <= 1 ? .75 * (1 - u * u) / scale : 0;
};
}
</script>
1) How to place the labels on the x axis in the center of the bin? In other words, the tick mark and its label on the center of the bar.
2) How do I place the quantity (frequency) of each bin above its bar?
I appreciate your comments and leave an image with the current development:
Thanks
For question1, if you just want to add some ticks at the center of each bin, there are x and dx attributes in histogram that indicate the position and step of each bin. You can compute the x tick by xtick = x + dx / 2.
For question2, I think you can draw a line chart above the histogram, and set the z-index to be 2.
I hope the above helps. :)
I implement chart to display some financial data for time period, x-axis contains javascript dates but y-axis numbers. The chart must provide zoom and pan functionality. I set x-axis for max available period, like:
var data = [
[{'x':'2017-01-02','y':0},{'x':'2017-02-03','y':5.0},{'x':'2017-03-04','y':10},{'x':'2017-04-05','y':0},{'x':'2017-05-06','y':6},{'x':'2017-06-07','y':11},{'x':'2017-07-08','y':9},{'x':'2017-08-09','y':4},{'x':'2017-09-10','y':11},{'x':'2017-10-11','y':2}],
[{'x':'2017-01-02','y':1},{'x':'2017-02-03','y':6.0},{'x':'2017-03-04','y':11},{'x':'2017-04-05','y':1},{'x':'2017-05-06','y':7},{'x':'2017-06-07','y':12},{'x':'2017-07-08','y':8},{'x':'2017-08-09','y':3},{'x':'2017-09-10','y':13},{'x':'2017-10-11','y':3}]
];
var json = JSON.parse('[[{"x":"2017-08-22T20:27:53.181+0200","y":4.0},{"x":"2017-09-01T20:27:53.181+0200","y":9.0},{"x":"2017-09-11T20:27:53.181+0200","y":15.0},{"x":"2017-09-21T20:27:53.181+0200","y":6.0},{"x":"2017-10-01T20:27:53.181+02:00","y":13.0},{"x":"2017-10-11T20:27:53.181","y":10.0},{"x":"2017-10-21T20:27:53.181","y":1.0},{"x":"2017-10-31T20:27:53.181","y":13.0},{"x":"2017-11-10T20:27:53.181","y":2.0},{"x":"2017-11-20T20:27:53.181","y":13.0},{"x":"2017-11-30T20:27:53.181","y":2.0},{"x":"2017-12-10T20:27:53.181","y":14.0},{"x":"2017-12-20T20:27:53.181","y":15.0},{"x":"2017-12-30T20:27:53.181","y":11.0},{"x":"2018-01-09T20:27:53.181","y":5.0},{"x":"2018-01-19T20:27:53.181","y":11.0},{"x":"2018-01-29T20:27:53.181","y":5.0},{"x":"2018-02-08T20:27:53.181","y":2.0},{"x":"2018-02-18T20:27:53.181","y":4.0},{"x":"2018-02-28T20:27:53.181","y":3.0},{"x":"2018-03-10T20:27:53.181","y":2.0},{"x":"2018-03-20T20:27:53.181","y":10.0},{"x":"2018-03-30T20:27:53.181","y":15.0},{"x":"2018-04-09T20:27:53.181","y":3.0},{"x":"2018-04-19T20:27:53.181","y":2.0},{"x":"2018-04-29T20:27:53.181","y":11.0},{"x":"2018-05-09T20:27:53.181","y":7.0},{"x":"2018-05-19T20:27:53.181","y":13.0},{"x":"2018-05-29T20:27:53.181","y":8.0},{"x":"2018-06-08T20:27:53.181","y":1.0},{"x":"2018-06-18T20:27:53.181","y":4.0},{"x":"2018-06-28T20:27:53.181","y":10.0},{"x":"2018-07-08T20:27:53.181","y":13.0},{"x":"2018-07-18T20:27:53.181","y":13.0},{"x":"2018-07-28T20:27:53.181","y":12.0},{"x":"2018-08-07T20:27:53.181","y":13.0},{"x":"2018-08-17T20:27:53.181","y":13.0},{"x":"2018-08-27T20:27:53.181","y":1.0},{"x":"2018-09-06T20:27:53.181","y":8.0},{"x":"2018-09-16T20:27:53.181","y":14.0},{"x":"2018-09-26T20:27:53.181","y":7.0},{"x":"2018-10-06T20:27:53.181","y":9.0},{"x":"2018-10-16T20:27:53.181","y":15.0},{"x":"2018-10-26T20:27:53.181","y":15.0},{"x":"2018-11-05T20:27:53.181","y":11.0},{"x":"2018-11-15T20:27:53.181","y":13.0},{"x":"2018-11-25T20:27:53.181","y":9.0},{"x":"2018-12-05T20:27:53.181","y":5.0},{"x":"2018-12-15T20:27:53.181","y":5.0},{"x":"2018-12-25T20:27:53.181","y":6.0}],[{"x":"2017-08-22T20:27:53.181","y":8.0},{"x":"2017-09-01T20:27:53.181","y":13.0},{"x":"2017-09-11T20:27:53.181","y":15.0},{"x":"2017-09-21T20:27:53.181","y":11.0},{"x":"2017-10-01T20:27:53.181","y":12.0},{"x":"2017-10-11T20:27:53.181","y":10.0},{"x":"2017-10-21T20:27:53.181","y":2.0},{"x":"2017-10-31T20:27:53.181","y":10.0},{"x":"2017-11-10T20:27:53.181","y":12.0},{"x":"2017-11-20T20:27:53.181","y":6.0},{"x":"2017-11-30T20:27:53.181","y":10.0},{"x":"2017-12-10T20:27:53.181","y":2.0},{"x":"2017-12-20T20:27:53.181","y":3.0},{"x":"2017-12-30T20:27:53.181","y":10.0},{"x":"2018-01-09T20:27:53.181","y":12.0},{"x":"2018-01-19T20:27:53.181","y":12.0},{"x":"2018-01-29T20:27:53.181","y":6.0},{"x":"2018-02-08T20:27:53.181","y":2.0},{"x":"2018-02-18T20:27:53.181","y":7.0},{"x":"2018-02-28T20:27:53.181","y":1.0},{"x":"2018-03-10T20:27:53.181","y":10.0},{"x":"2018-03-20T20:27:53.181","y":4.0},{"x":"2018-03-30T20:27:53.181","y":14.0},{"x":"2018-04-09T20:27:53.181","y":15.0},{"x":"2018-04-19T20:27:53.181","y":5.0},{"x":"2018-04-29T20:27:53.181","y":14.0},{"x":"2018-05-09T20:27:53.181","y":4.0},{"x":"2018-05-19T20:27:53.181","y":3.0},{"x":"2018-05-29T20:27:53.181","y":7.0},{"x":"2018-06-08T20:27:53.181","y":1.0},{"x":"2018-06-18T20:27:53.181","y":14.0},{"x":"2018-06-28T20:27:53.181","y":2.0},{"x":"2018-07-08T20:27:53.181","y":14.0},{"x":"2018-07-18T20:27:53.181","y":11.0},{"x":"2018-07-28T20:27:53.181","y":12.0},{"x":"2018-08-07T20:27:53.181","y":3.0},{"x":"2018-08-17T20:27:53.181","y":13.0},{"x":"2018-08-27T20:27:53.181","y":6.0},{"x":"2018-09-06T20:27:53.181","y":3.0},{"x":"2018-09-16T20:27:53.181","y":11.0},{"x":"2018-09-26T20:27:53.181","y":3.0},{"x":"2018-10-06T20:27:53.181","y":15.0},{"x":"2018-10-16T20:27:53.181","y":13.0},{"x":"2018-10-26T20:27:53.181","y":9.0},{"x":"2018-11-05T20:27:53.181","y":2.0},{"x":"2018-11-15T20:27:53.181","y":14.0},{"x":"2018-11-25T20:27:53.181","y":15.0},{"x":"2018-12-05T20:27:53.181","y":4.0},{"x":"2018-12-15T20:27:53.181","y":2.0},{"x":"2018-12-25T20:27:53.181","y":5.0}]]');
var a = jsonToArray(json);
var parseDate = d3.time.format("%Y-%m-%d").parse;
data.forEach(function(d) {
d.forEach(function(d2) {
d2.x = parseDate(d2.x);
});
});
var colors = [
'steelblue',
'green'
]
var pWidth = document.getElementById('chart1').offsetWidth;
var margin = {top: 20, right: 30, bottom: 30, left: 50},
width = pWidth - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.time.scale()
.domain([new Date('2016-01-01T00:00:00.000+02:00'), new Date('2018-10-01T00:00:00.000+02:00')])
.range([0, width]);
var y = d3.scale.linear()
.domain([-1, 16])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.tickSize(-height)
.tickPadding(10)
.tickSubdivide(true)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.tickPadding(10)
.tickSize(-width)
.tickSubdivide(true)
.orient("left");
var zoom = d3.behavior.zoom()
.x(x)
.scaleExtent([1, Infinity])
.on("zoom", zoomed);
var svg = d3.select("#chart1").append("svg")
.call(zoom)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "y axis")
.append("text")
.attr("class", "axis-label")
.attr("transform", "rotate(-90)")
.attr("y", (-margin.left) + 10)
.attr("x", -height/2)
.text('Axis Label');
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var line = d3.svg.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
svg.selectAll('.line')
.data(data)
.enter()
.append("path")
.attr("class", "line")
.attr("clip-path", "url(#clip)")
.attr('stroke', function(d,i){
return colors[i%colors.length];
})
.attr("d", line);
var points = svg.selectAll('.dots')
.data(data)
.enter()
.append("g")
.attr("class", "dots")
.attr("clip-path", "url(#clip)");
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.selectAll('path.line').attr('d', line);
var arr = [[]];
for ( var i = 0; i < 2; i++ ) {
arr[i] = new Array();
for ( var j = 0; j < 50; j++ ) {
arr[i][j] = {'x': addDays(x.domain()[0], 10*j), 'y':Math.floor((Math.random() * 15) + 1)};
}
}
svg.selectAll('.line')
.data(arr)
.enter()
.append("path")
.attr("class", "line")
.attr("clip-path", "url(#clip)")
.attr('stroke', function(d,i){
return colors[i%colors.length];
})
.attr("d", line);
}
function addDays(startDate,numberOfDays)
{
var returnDate = new Date(
startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate()+numberOfDays,
startDate.getHours(),
startDate.getMinutes(),
startDate.getSeconds());
return returnDate;
}
function jsonToArray(json) {
var result = new Array();
for(var i in json) {
var arr = new Array();
for(var j in json[i]) {
arr.push({'x':new Date(json[i][j].x), 'y':json[i][j].y});
}
result.push(arr);
}
return result;
}
}
but default time period when chart is loaded must be current date - one month back. And when I draw path for this period, chart displays it on the x-axis with max period. How can I programmatically zoom in to the default period (current date - one month back) so afterwards I can make both zoom in and zoom out?
Or I can set default period (current date - one month back) when chart is loaded but how can then make zoom out scrolling mouse wheel to wider period?
So I'm dynamically creating a bunch of simple line charts with D3 and everything is going well, but for some reason charts with ranges that go from 9-10 get inverted and look absolutely terrible/do not function properly.
the first one, the values are upside down
this one is fine...
Here is some code...
var dataRange = d3.extent(quoteObjects, function(d){ return d.close });
var dateRange = d3.extent(quoteObjects, function(d){ return d.date });
// Set chart variables
var vis = d3.select("#"+type),
WIDTH = $('#chart-box').width(),
HEIGHT = $('#'+type).innerHeight(),
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 60,
},
// set scales
xScale = d3.time.scale().range([MARGINS.left, WIDTH - MARGINS.right]).domain(dateRange),
yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain(dataRange),
// create displayed axis
xAxis = d3.svg.axis()
.scale(xScale)
.tickValues( xScale.ticks(6) )
yAxis = d3.svg.axis()
.scale(yScale)
.tickValues( yScale.ticks(6) )
.orient("left");
console.log("WH", WIDTH, HEIGHT);
if (type == "intraday"){
xAxis.tickFormat(d3.time.format("%H"))
}
// append x axis
vis.append("svg:g")
.attr("class", "axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.top) + ")")
.call(xAxis);
// append y axis
vis.append("svg:g")
.attr("class", "axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
// create line based on "close" values
var lineGen2 = d3.svg.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(d.close);
})
.interpolate("basis");
// append "close" line
vis.append('svg:path')
.attr('d', lineGen2(quoteObjects))
.attr('stroke', '#931a28')
.attr('stroke-width', 3)
.attr('fill', '#222');
I recently started working on d3.js. I am trying to develop a interactive multiple line graph. Please take a look at my work so far: http://jsfiddle.net/dalapati/cdkn14j3/6/
data1 = [
{"date": 1357717800000,"value": "5.6"},
{"date": 1357718400000,"value": "5.6"},
{"date": 1357719000000,"value": "6"},
{"date": 1357719600000,"value": "5.1"},
{"date": 1357720200000,"value": "5.3"},
// {"date": 1357720800000,"value": "5.4"}
];
data2 = [
{"date": 1357714800000,"value": "5.2"},
{"date": 1357715400000,"value": "5.2"},
{"date": 1357716000000,"value": "5.2"},
{"date": 1357716600000,"value": "5.1"},
{"date": 1357717200000,"value": "5.5"},
];
// date manipulation to format UTC to js Date obj
data1.forEach(function(d){ d.time = new Date(d.time * 1000);});
data2.forEach(function(d){ d.time = new Date(d.time * 1000);});
// helpers and constants
var margin = {"top": 50, "right": 50, "bottom": 50, "left": 100, "axis": 55};
var width = 1500 - margin.left - margin.right;
var height = 580 - margin.top - margin.bottom;
var timeFormat = d3.time.format("%X");
// find data range
var findXMin = function(_data){
return d3.min(_data, function(d){
return Math.min(d.date);
});
}
var findXMax = function(_data){
return d3.max(_data, function(d){
return Math.max(d.date);
});
}
var findYMin = function(_data){
return d3.min(_data, function(d){
return Math.min(d.value);
});
}
var findYMax = function(_data){
return d3.max(_data, function(d){
return Math.max(d.value);
});
}
var x1Min = findXMin(data1);
var x1Max = findXMax(data1);
var x2Min = findXMin(data2);
var x2Max = findXMax(data2);
var y1Min = findYMin(data1);
var y1Max = findYMax(data1);
var y2Min = findYMin(data2);
var y2Max = findYMax(data2);
var yMin = (y1Min < y2Min) ? y1Min:y2Min;
var yMax = (y1Max > y2Max) ? y1Max:y2Max;
// scales
var x1Scale = d3.time.scale()
.domain([x1Min,x1Max])
.range([0, width]);
var x2Scale = d3.time.scale()
.domain([x2Min,x2Max])
.range([0, width]);
var yScale = d3.scale.linear()
.domain([yMin,yMax]).range([height, 0]);
var renderXAxis = function(scale, className, tickFormat, index0, index1, orient){
var axis = d3.svg.axis()
.scale(scale)
.orient(orient)
.ticks(5)
.tickPadding(5)
.tickFormat(tickFormat);
svg.append("g")
.attr("class", className)
.attr("transform", function() {
return "translate(" +index0+", " +index1+ ")";})
.call(axis);
}
var renderYAxis = function(scale, className, tickFormat, index0, index1, orient){
var axis = d3.svg.axis()
.scale(scale)
.orient(orient)
.ticks(5)
.tickPadding(5)
.tickFormat(tickFormat);
svg.append("g")
.attr("class", className)
.attr("transform", function(){
return "translate(" +index0+", " +index1+ ")";})
.call(axis);
// grid plot
svg.append("g")
.attr("class", "y grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat(""));
}
var make_y_axis = function () {
return d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5)
.tickPadding(5);
};
// Set up chart type
// create a line function that can convert data into x and y points
var line1 = d3.svg.line().interpolate("basis")
.x(function (d) {
return x1Scale(d.date);
})
.y(function (d) {
return yScale(d.value);
});
var line2 = d3.svg.line().interpolate("basis")
.x(function (d) {
return x2Scale(d.date);
})
.y(function (d) {
return yScale(d.value);
});
// Create Zoom feature
var zoomBottom = d3.behavior.zoom()
.x(x1Scale)
.scaleExtent([1,10]);
var zoom = d3.behavior.zoom()
.x(x2Scale)
.scaleExtent([1,10])
.on("zoom",zoomed);
// Create Drag behaviour
var drag = d3.behavior.drag()
.origin(function(d){
var t = d3.select(this);
return {
x: t.attr("x"),
y: t.attr("y")
};
})
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", dragended);
// create svg container
var svg = d3.select('#chart')
.append("svg:svg")
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append("svg:g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var plot = svg.append("svg:rect")
.attr("width", width)
.attr("height", height)
.attr("class", "plot")
.call(zoom);
//Draw Axes
var x1Axis = renderXAxis(x1Scale, "x1Axis", timeFormat, 0, height, "bottom");
var x2Axis = renderXAxis(x2Scale, "x2Axis", timeFormat, 0, 0, "top");
var yAxis = renderYAxis(yScale, "yAxis", function(d){return d;}, 0, 0, "left");
// add lines
// do this AFTER the axes above so that the line is above the tick-lines
var clip = svg.append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("x1Scale", 0)
.attr("x2Scale", 0)
.attr("yScale", 0)
.attr("width", width)
.attr("height", height);
var chartBody = svg.append("g")
.attr("clip-path", "url(#clip)");
chartBody.append("svg:path")
.datum(data1)
.attr("class", "data1")
.attr("d", line1(data1))
.attr("cursor", "move")
.call(drag);
chartBody.append("svg:path")
.datum(data2)
.attr("class", "data2")
.attr("d", line2(data2))
.attr("cursor", "move")
.call(drag);
/************************** ADDING ZOOMING FEATURE****************************************/
function zoomed() {
zoomBottom.scale(zoom.scale()).translate(zoom.translate());
d3.select(".x1Axis").remove();
renderXAxis(x1Scale, "x1Axis", timeFormat, 0, height, "bottom");
d3.select(".x2Axis").remove();
renderXAxis(x2Scale, "x2Axis", timeFormat, 0, 0, "top");
d3.select(".yAxis").remove();
renderYAxis(yScale, "yAxis", function(d){return d;}, 0, 0, "left");
svg.select(".data1").attr("d",line1(data1));
svg.select(".data2").attr("d",line2(data2));
}
/***************** Adding Dragging feature*****************************************************/
function dragstarted(d){
d3.event.sourceEvent.stopPropagation();
//d3.event.preventDefault();
//d3.select(this).attr( 'pointer-events', 'none' );
d3.select(this).classed("dragging", true);
console.log(d);
}
function dragged(d){
var lineToMove = d3.event.x;
d3.select(this)
.transition()
.ease("linear")
.attr("transform", "translate(" +lineToMove+ ",0)");
d3.select(".x1Axis").remove();
renderXAxis(x1Scale, "x1Axis", timeFormat, lineToMove, height, "bottom");
d3.select(".x2Axis").remove();
renderXAxis(x2Scale, "x2Axis", timeFormat, lineToMove, 0, "top");
d3.select(".yAxis").remove();
renderYAxis(yScale, "yAxis", function(d){return d;}, 0, 0, "left");}
function dragended(d){
d3.select(this).classed("dragging", false);
}
I am trying to implement a dragging behavior to each line graph with respect to its axis. I could able to achieve implementing the dragging behavior to a particular line graph but, I am not sure how to dynamically update its respective axis. Can anyone please share your idea to solve this problem.
Thank you in advance.
This is the general comment I gave to solve the problem:
I would not completely re-render each axis with the update function. Instead, update its existing properties as needed and draw the axis a single time.
You can access these by just using a method like axis.scale(scale).tickFormat(tickFormat). This adds efficiency. Then you can do something like: d3.select(".x.axis").transition().duration(1600).call(axis)
I'm working on a horizontal line chart in d3js that displays several lines based on json input. It has zooming and panning, but also need to display a y-axis for each of the drawn lines. In my case, three.
First off, is this bad practice? Should I stack all three on one side, or should I keep two on the left, one on the right or any other combination?
I've tried following this tutorial, but that did really just create more mess and confusing code.
I was hoping someone could guide me in the direction of how to add the additional y axes and how I could have them work with the zooming and panning as well, like the one I have now.
Here's my current view:
And here's my code:
<script>
var margin = { top: 20, right: 80, bottom: 20, left: 40 },
width = ($("#trendcontainer").width() - 50) - margin.left - margin.right,
height = 650 - margin.top - margin.bottom;
var svg;
var format = d3.time.format("%Y-%m-%dT%H:%M:%S").parse;
var x = d3.time.scale()
.range([0, width]);
var y0 = d3.scale.linear()
.range([height, 0]);
var y1 = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(-height);
// TODO: Rename axis to instrument name (i.e 'depth')
var yAxis0 = d3.svg.axis()
.scale(y0)
.orient("left")
.tickSize(-width);
var yAxis1 = d3.svg.axis()
.scale(y1)
.orient("right")
.tickSize(-width);
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y0(d.value);
});
d3.json('#Url.Action("DataBlob", "Trend", new {id = Model.Unit.UnitId, runId = Request.Params["runId"]})', function(error, tmparray) {
var json = JSON.parse(tmparray);
$('#processing').hide();
color.domain(d3.keys(json[0]).filter(function(key) {
return key !== "Time" && key !== "Id";
}));
json.forEach(function(d) {
var date = format(d.Time);
d.Time = date;
});
var instruments = color.domain().map(function(name) {
return {
name: name,
values: json.map(function(d) {
return {
date: d.Time,
value: +d[name]
};
})
};
});
x.domain(d3.extent(json, function(d) {
return d.Time;
}));
y0.domain([
d3.min(instruments, function (c) {
if (c.name == "Depth") {
return d3.min(c.values, function (v) {
return v.value;
});
}
//return d3.min(c.values, function (v) {
// return v.value;
//});
}),
d3.max(instruments, function(c) {
return d3.max(c.values, function(v) {
return v.value;
});
})
]);
y1.domain([
d3.min(instruments, function (c) {
console.log("In y1.domain c is: " + c);
if (c.name == "Weight") {
return d3.min(c.values, function (v) {
return v.value;
});
}
//return d3.min(c.values, function (v) {
// return v.value;
//});
}),
d3.max(instruments, function(c) {
return d3.max(c.values, function(v) {
return v.value;
});
})
]);
var zoom = d3.behavior.zoom()
.x(x)
.y(y0)
.scaleExtent([1, 10])
.on("zoom", zoomed);
svg = d3.select(".panel-body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
svg.append("rect")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis0);
svg.append("g")
.attr("class", "y axis")
.call(yAxis1);
var instrument = svg.selectAll(".instrument")
.data(instruments)
.enter().append("g")
.attr("class", "instrument");
instrument.append("path")
.attr("class", "line")
.attr("d", function(d) {
return line(d.values);
})
.style("stroke", function(d) {
return color(d.name);
});
instrument.append("text")
.datum(function(d) {
return {
name: d.name,
value: d.values[d.values.length - 1]
};
})
.attr("transform", function(d) {
return "translate(" + x(d.value.date) + "," + y0(d.value.value) + ")";
})
.attr("x", 3)
.attr("dy", ".35em")
.text(function(d) {
return d.name;
});
});
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis0);
svg.select(".x.grid")
.call(make_x_axis()
.tickSize(-height, 0, 0)
.tickFormat(""));
svg.select(".y.grid")
.call(make_y_axis()
.tickSize(-width, 0, 0)
.tickFormat(""));
svg.selectAll(".line")
.attr("d", function(d) { return line(d.values); });
};
var make_x_axis = function() {
return d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5);
};
var make_y_axis = function() {
return d3.svg.axis()
.scale(y0)
.orient("left")
.ticks(5);
};
</script>
Finally, here's what I'm trying to achieve (This component is way too slow, and does not handle large datasets well):
Finally ended up at a solution, with some kind assistance from #LarsKotthoff. Also added multiple axes zoom, based on this post.
<script>
/* d3 vars */
var x;
var y1;
var y2;
var y3;
var graph;
var m = [];
var w;
var h;
/* d3 axes */
var xAxis;
var yAxisLeft;
var yAxisLeftLeft;
var yAxisRight;
/* d3 lines */
var line1;
var line2;
var line3;
/* d3 zoom */
var zoom;
var zoomLeftLeft;
var zoomRight;
/* Data */
var speed = [];
var depth = [];
var weight = [];
var timestamp = [];
var url = '#Url.Action("DataBlob", "Trend", new {id = Model.Unit.UnitId, runId = Request.Params["runId"]})';
var data = $.getJSON(url, null, function(data) {
var list = JSON.parse(data);
var format = d3.time.format("%Y-%m-%dT%H:%M:%S").parse;
list.forEach(function(d) {
speed.push(d.Speed);
depth.push(d.Depth);
weight.push(d.Weight);
var date = format(d.Time);
d.Time = date;
timestamp.push(d.Time);
});
m = [10, 80, 30, 100]; // margins: top, right, bottom, left
w = $("#trendcontainer").width() - m[1] - m[3]; // width
h = 550 - m[0] - m[2]; // height
x = d3.time.scale().domain(d3.extent(timestamp, function (d) {
return d;
})).range([0, w]);
y1 = d3.scale.linear().domain([0, d3.max(speed)]).range([h, 0]);
y2 = d3.scale.linear().domain([0, d3.max(depth)]).range([h, 0]);
y3 = d3.scale.linear().domain([0, d3.max(weight)]).range([h, 0]);
line1 = d3.svg.line()
.interpolate("basis")
.x(function (d, i) {
return x(timestamp[i]);
})
.y(function (d) {
return y1(d);
});
line2 = d3.svg.line()
.interpolate("basis")
.x(function (d, i) {
return x(timestamp[i]);
})
.y(function (d) {
return y2(d);
});
line3 = d3.svg.line()
.interpolate("basis")
.x(function (d, i) {
return x(timestamp[i]);
})
.y(function (d) {
return y3(d);
});
zoom = d3.behavior.zoom()
.x(x)
.y(y1)
.scaleExtent([1, 10])
.on("zoom", zoomed);
zoomLeftLeft = d3.behavior.zoom()
.x(x)
.y(y3)
.scaleExtent([1, 10]);
zoomRight = d3.behavior.zoom()
.x(x)
.y(y2)
.scaleExtent([1, 10]);
// Add an SVG element with the desired dimensions and margin.
graph = d3.select(".panel-body").append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.call(zoom)
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
// create xAxis
xAxis = d3.svg.axis().scale(x).tickSize(-h).tickSubdivide(false);
// Add the x-axis.
graph.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
// create left yAxis
yAxisLeft = d3.svg.axis().scale(y1).ticks(10).orient("left");
// Add the y-axis to the left
graph.append("svg:g")
.attr("class", "y axis axisLeft")
.attr("transform", "translate(-15,0)")
.call(yAxisLeft);
// create leftleft yAxis
yAxisLeftLeft = d3.svg.axis().scale(y3).ticks(10).orient("left");
// Add the y-axis to the left
graph.append("svg:g")
.attr("class", "y axis axisLeftLeft")
.attr("transform", "translate(-50,0)")
.call(yAxisLeftLeft);
// create right yAxis
yAxisRight = d3.svg.axis().scale(y2).ticks(10).orient("right");
// Add the y-axis to the right
graph.append("svg:g")
.attr("class", "y axis axisRight")
.attr("transform", "translate(" + (w + 15) + ",0)")
.call(yAxisRight);
// add lines
// do this AFTER the axes above so that the line is above the tick-lines
graph.append("svg:path").attr("d", line1(speed)).attr("class", "y1");
graph.append("svg:path").attr("d", line2(depth)).attr("class", "y2");
graph.append("svg:path").attr("d", line3(weight)).attr("class", "y3");
});
function zoomed() {
zoomRight.scale(zoom.scale()).translate(zoom.translate());
zoomLeftLeft.scale(zoom.scale()).translate(zoom.translate());
graph.select(".x.axis").call(xAxis);
graph.select(".y.axisLeft").call(yAxisLeft);
graph.select(".y.axisLeftLeft").call(yAxisLeftLeft);
graph.select(".y.axisRight").call(yAxisRight);
graph.select(".x.grid")
.call(make_x_axis()
.tickFormat(""));
graph.select(".y.axis")
.call(make_y_axis()
.tickSize(5, 0, 0));
graph.selectAll(".y1")
.attr("d", line1(speed));
graph.selectAll(".y2")
.attr("d", line2(depth));
graph.selectAll(".y3")
.attr("d", line3(weight));
};
var make_x_axis = function () {
return d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5);
};
var make_y_axis = function () {
return d3.svg.axis()
.scale(y1)
.orient("left")
.ticks(5);
};
</script>