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)
Related
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?
I am trying to create a scatterplot with a zooming. The following code I have used in my angular application and its working till a certain extent when I run it in my local server. However putting the same code in Stackblitz, the zooming is not working. I want to achieve a zooming where the zooming is limited to just the values on the graph. There should be no zooming of the axis accept the value changes in both the axis. Something exactly like : http://bl.ocks.org/peterssonjonas/4a0e7cb8d23231243e0e .
Here in the example, on zooming, only the values are zoomed and the axis values changed correspondingly. It doesn't zoom the whole graph plot area. How do I achieve it? Here is my Stackblitz code:
https://stackblitz.com/edit/angular-hu2thj
ANSWER :
Finally I figure out the graph for this problem in case of any future reference:
import { Component, OnInit, Input, ViewChild, ElementRef } from '#angular/core';
import * as d3 from 'd3';
#Component({
selector: 'app-scatterplot',
templateUrl: './scatterplot.component.html',
styleUrls: ['./scatterplot.component.css']
})
export class ScatterplotComponent implements OnInit {
#ViewChild('chart1') private chartContainer: ElementRef;
dataValue = [{ x: "67", y: "188", },
{ x: "200", y: "163" },
{ x: "254", y: "241" },
{ x: "175", y: "241" },
];
ngOnInit() {
this.graph();
}
graph() {
const element = this.chartContainer.nativeElement;
var svgWidth = 400;
var svgHeight = 400;
var margin = { top: 30, right: 40, bottom: 50, left: 60 };
var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;
var originalCircle = {
"cx": -150,
"cy": -15,
"r": 20
};
var svgViewport = d3.select(element)
.append('svg')
.attr('width', svgWidth)
.attr('height', svgHeight)
// create scale objects
var x = d3.scaleLinear()
.domain([1, 500])
.range([0, width]);
var y = d3.scaleLinear()
.domain([1, 500])
.range([height, 0]);
// create axis objects
var xAxis = d3.axisBottom(x);
var yAxis = d3.axisLeft(y);
// Zoom Function
var zoom = d3.zoom()
.on("zoom", zoomFunction);
// Inner Drawing Space
var innerSpace = svgViewport.append("g")
.attr("class", "inner_space")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
// append some dummy data
var data = innerSpace.selectAll("circle")
.data(this.dataValue)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function (d) {
return x(d.x)
;
})
.attr("cy", function (d) {
return y(d.y);
})
.attr("r", 2);
// Draw Axis
var gX = innerSpace.append("g")
.attr("class", "axis")
.attr("transform", "translate(0, " + height + ")")
.call(xAxis);
var gY = innerSpace.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
// append zoom area
var view = innerSpace.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height - 10)
.attr("fill", "transparent")
.attr("fill-opacity", 0.1)
.call(zoom)
function zoomFunction() {
// create new scale ojects based on event
var new_xScale = d3.event.transform.rescaleX(x)
var new_yScale = d3.event.transform.rescaleY(y)
console.log(d3.event.transform)
// update axes
gX.call(xAxis.scale(new_xScale));
gY.call(yAxis.scale(new_yScale));
// update circle
data.attr("transform", d3.event.transform)
};
}
}
The problem on stackblitz is that d3.event is null.
Try this to zoom the points in your local server.
You need to add a clip path and animate the axis, see the second example (heatmap)
var svg = d3.select(element)
.append("svg:svg")
.attr("width", w + left_padding)
.attr("height", h + top_padding);
var g = svg.append("g");
var zoom = d3.zoom().on("zoom", function () {
console.log("zoom", d3, d3.event);
g.attr("transform", d3.event.transform);
});
svg.call(zoom);
g.selectAll("circle")
.data(this.dataValue)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", d => x(d.x) )
.attr("cy", d => y(d.y) )
.attr("r", 2);
I have been trying this for a couple of days but not able to find solution for it. I have a time series data which comes every 5 minutes and can extend for days. I am quiet new to D3 and Java Script. It took me some time to build it. Following is a link of the jsfiddle, i have been working on:
https://jsfiddle.net/adityap16/d61gtadm/2/
Code:
var data = [
{"mytime": "2015-12-01T11:10:00.000Z", "value": 64},
{"mytime": "2015-12-01T11:15:00.000Z", "value": 67},
{"mytime": "2015-12-01T11:20:00.000Z", "value": 70},
{"mytime": "2015-12-01T11:25:00.000Z", "value": 64},
{"mytime": "2015-12-01T11:30:00.000Z", "value": 72},
{"mytime": "2015-12-01T11:35:00.000Z", "value": 75},
{"mytime": "2015-12-01T11:40:00.000Z", "value": 71},
{"mytime": "2015-12-01T11:45:00.000Z", "value": 80}
];
var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ").parse;
data.forEach(function(d) {
d.mytime = parseDate(d.mytime);
});
//var margin = { top: 30, right: 30, bottom: 40, left:50 },
var margin = { top: 30, right: 30, bottom: 40, left:50 },
height = 200,
width = 800;
var color = "green";
var xaxis_param = "mytime";
var yaxis_param = "value"
var params1 = {margin:margin,height:height,width:width, color: color, xaxis_param:xaxis_param, yaxis_param :yaxis_param};
draw_graph(data,params1);
function draw_graph(data,params){
//Get the margin
var xaxis_param = params.xaxis_param;
var yaxis_param = params.yaxis_param;
var color_code = params.color;
var margin = params.margin;
var height = params.height - margin.top - margin.bottom,
width = params.width - margin.left - margin.right;
console.log("1")
var x_extent = d3.extent(data, function(d){
return d[xaxis_param]});
console.log("2")
var y_extent = d3.extent(data, function(d){
return d[yaxis_param]});
var x_scale = d3.time.scale()
.domain(x_extent)
.range([0,width]);
console.log("3")
var y_scale = d3.scale.linear()
.domain([0,y_extent[1]])
.range([height,0]);
//Line
var lineGen = d3.svg.line()
.x(function (d) {
return x_scale(d[xaxis_param]);
})
.y(function (d) {
return y_scale(d[yaxis_param]);
});
var myChart = d3.select('body').append('svg')
.style('background', '#E7E0CB')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate('+ margin.left +', '+ margin.top +')');
myChart
.append('svg:path')
.datum(data)
.attr('class', 'line')
.attr("d",lineGen)
.attr('stroke', color_code)
.attr('stroke-width', 1)
.attr('fill', 'none');
var legend = myChart.append("g")
.attr("class", "legend")
.attr("transform", "translate(" + 5 + "," + (height - 25) + ")")
legend.append("rect")
.style("fill", color_code)
.attr("width", 20)
.attr("height", 20);
legend.append("text")
.text(yaxis_param)
.attr("x", 25)
.attr("y", 12);
var vGuideScale = d3.scale.linear()
.domain([0,y_extent[1]])
.range([height, 0])
var vAxis = d3.svg.axis()
.scale(vGuideScale)
.orient('left')
.ticks(5)
var hAxis = d3.svg.axis()
.scale(x_scale)
.orient('bottom')
.ticks(d3.time.minute, 5);
myChart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(hAxis);
myChart.append("g")
.attr("class", "y axis")
.call(vAxis)
}
I am currently stumped with two problems.
a.)I have to place vertical markers for end of each day. How to place vertical lines to show these transition (markers) from one day to another (just a simple black vertical line would do?
b.) Can we deal with missing data suppose i don't get data for a day, can i get blanks for that period of time and straight away plot the next day data. (This one is not that important)?
Here is a working jsfiddle: https://jsfiddle.net/kmandov/d61gtadm/3/
This is how you can achieve the desired results:
Problem a.) Vertical ticks for each day:
First, create a new major axis and set the tickSize to -height, so the ticks go all the way through your chart:
var majorAxis = d3.svg.axis()
.scale(x_scale)
.orient('bottom')
.ticks(d3.time.day, 1)
.tickSize(-height);
and then create the corresponding svg element:
myChart.append("g")
.attr("class", "x axis major")
.attr("transform", "translate(0," + height + ")")
.call(majorAxis);
Then remove the label for the major ticks(you don't want them to overlap):
.axis.major text {
display: none;
}
Here is a nice example by M. Bostock himself: http://bl.ocks.org/mbostock/4349486
Problem B.) Missing Data
Set .defined() on the line:
var lineGen = d3.svg.line()
.defined(function(d) { return d[yaxis_param]; })
.x(function (d) {
return x_scale(d[xaxis_param]);
})
.y(function (d) {
return y_scale(d[yaxis_param]);
});
Here is an example on how to deal with gaps in your data: http://bl.ocks.org/mbostock/3035090
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>
I have a line chart with several axes, using zooming and panning. Works fine, however when I pan or zoom, my lines extend outside the 'graph' component. I've tried following this example, adding a clipPath to my chart.
When highlighting the code in chromes code inspector, I see the following (which at least indicates that I've got a path present I guess)
Here's my grid:
<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] + ")");
graph.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", w)
.attr("height", h);
// 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>
Any suggestions on what I'm missing here?
Solved by appending the following to the lines being drawn:
graph.append("svg:path").attr("d", line1(speed)).attr("class", "y1").attr("clip-path", "url(#clip)");
graph.append("svg:path").attr("d", line2(depth)).attr("class", "y2").attr("clip-path", "url(#clip)");
graph.append("svg:path").attr("d", line3(weight)).attr("class", "y3").attr("clip-path", "url(#clip)");