I have d3.js line chart which is included as directive to angular.js application. Lines and xAxis added dynamically and on zoom lines overflows margins :( I have to create Ox axes on the top of the figure for every loaded line, with Ox and Oy separate zoom possibility. Oy zoom works fine accept this margin issue
Chart
// Define zoom beavior
var zoomLas = d3.behavior.zoom()
.y(y)
.scaleExtent([0, 20])
.on("zoom", zoomedLas);
var las = d3.select(element[0])
.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(zoomLas);
// Add the X Axis
las.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0, 0)")
.call(xAxis);
// Add the Y Axis
las.append("g")
.attr("class", "y axis")
.call(yAxis);
las.append("g")
.attr("class", "x grid")
.attr("transform", "translate(0," + height + ")")
.call(make_x_axis(10)
.tickSize(-height, 0, 0)
.tickFormat("")
);
las.append("g")
.attr("class", "y grid")
.call(make_y_axis(20)
.tickSize(-width, 0, 0)
.tickFormat("")
);
var xX={};
//Add lines to plot
var lineCounter = 0;
for (var property in linesObj) {
if (linesObj.hasOwnProperty(property)) {
++lineCounter;
var prop = property.toLowerCase();
xX['x' + prop] = d3.scale.linear().range([0, width]);
xX['x' + prop].domain([0, d3.max(linesObj[property], function (d) {
return Math.max(d.DATA);
})]);
// Define additional axes
xX['x' + prop +'Axis'] = d3.svg.axis().scale(xX['x' + prop])
.orient("top").ticks(5).tickSize(3).tickFormat(function (d) {
return d
});
// Add the X Axis
las.append("g")
.attr("class", "x axis " + "X" + prop + "LineClass")
.attr("stroke", colors[lineCounter])
.attr("stroke-width", "1px")
.attr("transform", "translate(0, " + (-20) * lineCounter + ")")
.call(xX['x' + prop +'Axis']);
xX['x' + prop +'Line'] = d3.svg.line()
.x(function (d) {
// return the X coordinate where we want to plot this datapoint
var data = parseFloat(d.DATA);
var crv = d.CURVE.toLowerCase();
return xX['x' + crv](data);
})
.y(function (d) {
// return the Y coordinate where we want to plot this datapoint
var depth = parseFloat(d.DEPTH);
return y(depth);
});
las.append("path")
.attr("class", "line " + prop + "LineClass")
.attr("stroke", colors[lineCounter])
.attr("stroke-width", "1.5px")
.attr("fill", "none")
.on('mouseover', function (d) {
d3.select(this).attr("stroke-width", "2.5px");
var thisClass = this.getAttribute('class');
var classForX = thisClass.replace('line ', '');
d3.selectAll(".x.axis.X" + classForX).attr("stroke-width", "2px")
})
.on('mouseout', function (d) {
d3.select(this).attr("stroke-width", "1.5px");
var thisClass = this.getAttribute('class');
var classForX = thisClass.replace('line ', '');
d3.selectAll(".x.axis.X" + classForX).attr("stroke-width", "1px")
})
.attr("d", xX['x' + prop +'Line'](linesObj[property]));
// .call(dragLas);
}
}
function zoomedLas() {
las.select(".y.axis").call(yAxis);
las.select(".y.grid")
.call(make_y_axis(20)
.tickSize(-width, 0, 0)
.tickFormat(""));
newVal.forEach(function (entry) {
if (entry != "DEPTH") {
var curveClass = entry.toLowerCase();
las.selectAll('.line.' + curveClass + 'LineClass').attr('d', xX['x' + curveClass +'Line'](linesObj[entry]));
}
});
}
And here its result
Related
In Bellow code I am trying to use separate charts (i.e. Bar and line chart) and getting Error: attribute d: Expected number, "MNaN,116LNaN,117L…"
Tried with using different SVG elements for both charts. Give some suggestions if I am missing something.
If I commenting Bar chart code then Line chart works properly and same works with the Bar chart but both at a same time doesn't work.
<div>
<div>Simple Bar Chart</div>
<div class="simpleBar">
<svg width="960" height="500"></svg>
</div>
</div>
<div>
<div>Line Chart</div>
<div id="lineGraph"></div>
</div>
<script>
// --------------- Bar chart code starts -----------------------
var svg = d3.select(".simpleBar > svg"),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var tooltip = d3.select("body").append("div").attr("class", "toolTip");
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
var colours = d3.scaleOrdinal()
.range(["#6F257F", "#CA0D59"]);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("dataSample.json", function(error, data) {
if (error) throw error;
x.domain(data.map(function(d) { return d.Timestamp; }));
y.domain([0, d3.max(data, function(d) { return d.DayTotal; })]);
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y).ticks(5).tickFormat(function(d) { return parseInt(d) + "Rs"; }).tickSizeInner([-width]))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 1)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.attr("fill", "#5D6971")
.text("Average Expence(Rs)");
g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("x", function(d) { return x(d.Timestamp); })
.attr("y", function(d) { return y(d.DayTotal); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.DayTotal); })
.attr("fill", function(d) { return colours(d.Timestamp); })
.on("mousemove", function(d){
tooltip
.style("left", d3.event.pageX - 50 + "px")
.style("top", d3.event.pageY - 70 + "px")
.style("display", "inline-block")
.html((d.Timestamp) + "<br>" + "Rs" + (d.DayTotal));
})
.on("mouseout", function(d){ tooltip.style("display", "none");});
});
// --------------- Line chart code starts -----------------------
// parse the Timestamp / time
var parseTime = d3.timeParse("%d-%b-%y");
// set the ranges
var xLine = d3.scaleTime().range([0, width]);
var yLine = d3.scaleLinear().range([height, 0]);
// define the line
var valueline = d3.line()
.x(function(d) { return x(d.Timestamp); })
.y(function(d) { return y(d.DayTotal); });
var svgLine = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svgLine = d3.select("#lineGraph").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 + ")");
// Get the data
d3.json("dataSample.json", function(error, data) {
if (error) throw error;
// format the data
data.forEach(function(d) {
d.Timestamp = parseTime(d.Timestamp);
d.DayTotal = +d.DayTotal;
});
// Scale the range of the data
xLine.domain(d3.extent(data, function(d) { return d.Timestamp; }));
yLine.domain([0, d3.max(data, function(d) { return d.DayTotal; })]);
// Add the valueline path.
svgLine.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline);
// Add the X Axis
svgLine.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xLine).ticks(5));
// Add the Y Axis
svgLine.append("g")
.call(d3.axisLeft(yLine));
});
</script>
and bellow is the Json data format:
[
{
"DayTotal": "418",
"Timestamp": "15-Mar-18"
},{...}
]
You are supposed to use xLine, yLine in your d3 line function whereas you used the ones(x, y) that you meant for bar charts.
var valueline = d3.line()
.x(function(d) { return xLine(d.Timestamp); })
.y(function(d) { return yLine(d.DayTotal); });
Solved JSFiddle
i have plotted dynamic waves based on randomly generated data in d3.js. I am using "dot" (svg.selectAll("dot")) element to represent the data point(x and y axis) on the waves. Based on setinterval method my data is getting updated every 200ms and i am transforming the data from right to left. But the data points(dots) that i added to the waves are not moving along with the waves, they are fixed(not moving) and only waves are moving.
here's the code:
https://jsfiddle.net/rajatmehta/tm5166e1/4/
function updateData() {
var newData = GenData(N,lastUpdateTime);
lastUpdateTime = newData[newData.length-1].timestamp;
var newData2 = GenData2(N,lastUpdateTimeNew);
lastUpdateTimeNew = newData2[newData2.length-1].timestamp;
for (var i=0; i<newData.length; i++){
console.log(globalData.length);
if(globalData.length>99){
globalData.shift();
}
globalData.push(newData[i]);
}
for (var i=0; i<newData2.length; i++){
console.log(globalDataNew.length);
if(globalDataNew.length>99){
globalDataNew.shift();
}
globalDataNew.push(newData2[i]);
}
//code for transition start
x1 = newData[0].timestamp;
x2 = newData[newData.length - 1].timestamp;
dx = dx + (x(x1) - x(x2)); // dx needs to be cummulative
x1New = newData2[0].timestamp;
x2New = newData2[newData2.length - 1].timestamp;
dxNew = dxNew + (x(x1New) - x(x2New)); // dx needs to be cummulative
d3.select("path#path1")
.datum(globalData)
.attr("class", "line")
.attr("d", valueline(globalData))
.transition()
.ease("linear")
.attr("transform", "translate(" + String(dx) + ")");
d3.select("path#path2")
.datum(globalDataNew)
.attr("class", "line")
.attr("d", valueline2(globalDataNew))
.transition()
.ease("linear")
.attr("transform", "translate(" + String(dxNew) + ")");
svg.select(".x.axis").call(xAxis);
}
I am new to d3.js, so dont have much idea about this.
Two problems:
You are not appending the circles correctly: you cannot append a <circle> element to a <path>element. You have to use an "enter" selection, appending them to the SVG (or a group element):
chartBody.selectAll(null)
.data(globalData)
.enter()
.append("circle")
.attr("class", "dot1")
.attr("r", 3)
.attr("cx", function(d) {
console.log(d)
return x(d.timestamp);
})
.attr("cy", function(d) {
return y(d.value);
});
In the update function, select those circles by class:
d3.selectAll(".dot1")
.data(globalData)
.transition()
.ease("linear")
.attr("transform", "translate(" + String(dx) + ")");
Here is your code with those changes:
var lastUpdateTime = +new Date();
var lastUpdateTimeNew = +new Date();
var GenData = function(N, lastTime) {
var output = [];
for (var i = 0; i < N; i++) {
output.push({
value: Math.random() * 10,
timestamp: lastTime
});
lastTime = lastTime + 1000;
}
return output;
}
var GenData2 = function(N, lastTime) {
var output = [];
for (var i = 0; i < N; i++) {
output.push({
value: Math.random() * 20,
timestamp: lastTime
});
lastTime = lastTime + 1000;
}
return output;
}
var globalData;
var globalDataNew;
// plot the original data by retrieving everything from time 0
data = GenData(50, lastUpdateTime);
dataNew = GenData2(50, lastUpdateTimeNew);
lastUpdateTime = data[data.length - 1].timestamp;
lastUpdateTimeNew = dataNew[dataNew.length - 1].timestamp;
globalData = data;
globalDataNew = dataNew;
// Define the div for the tooltip
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
},
width = 800 - margin.left - margin.right,
height = 350 - margin.top - margin.bottom;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
x.domain(d3.extent(globalDataNew, function(d) {
return d.timestamp;
}));
y.domain(d3.extent(globalDataNew, function(d) {
return d.value;
}));
var xAxis = d3.svg.axis().scale(x)
.orient("bottom")
.ticks(d3.time.seconds, 20)
.tickFormat(d3.time.format('%X'))
.tickSize(5)
.tickPadding(8);
var xAxisTop = d3.svg.axis().scale(x)
.orient("bottom").tickFormat("").tickSize(0);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var yAxisRight = d3.svg.axis().scale(y)
.orient("right").tickFormat("").tickSize(0);
var valueline = d3.svg.line()
.x(function(d) {
return x(d.timestamp);
})
.y(function(d) {
return y(d.value);
});
var valueline2 = d3.svg.line()
.x(function(d) {
return x(d.timestamp);
})
.y(function(d) {
return y(d.value);
});
var svg = d3.select("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 + ")");
svg.append("rect")
.attr("width", width)
.attr("height", height)
.attr("class", "plot");
var clip = svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height);
var chartBody = svg.append("g")
.attr("clip-path", "url(#clip)");
/* .on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div .html(formatTime(d.timestamp) + "<br/>" + d.close)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
})*/
chartBody.append("path") // Add the valueline path
.datum(globalData)
.attr("id", "path1")
.attr("class", "line")
.attr("d", valueline);
chartBody.selectAll(null)
.data(globalData)
.enter()
.append("circle")
.attr("class", "dot1")
.attr("r", 3)
.attr("cx", function(d) {
return x(d.timestamp);
})
.attr("cy", function(d) {
return y(d.value);
});
chartBody.selectAll(null)
.data(globalDataNew)
.enter()
.append("circle")
.attr("class", "dot2")
.attr("r", 3)
.attr("cx", function(d) {
return x(d.timestamp);
})
.attr("cy", function(d) {
return y(d.value);
});
chartBody.append("path") // Add the valueline path
.datum(globalDataNew)
.attr("id", "path2")
.attr("class", "line")
.attr("d", valueline2);
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + width + ",0)")
.call(yAxisRight);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + String(0) + ")")
.call(xAxisTop);
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x", (0 - (height / 2)))
.attr("dy", "1em")
.style("text-anchor", "middle")
.style("font-weight", "bold")
.text("Return (%)");
var inter = setInterval(function() {
updateData();
}, 1000);
//////////////////////////////////////////////////////////////
var N = 3;
var dx = 0;
var dxNew = 0;
function updateData() {
var newData = GenData(N, lastUpdateTime);
lastUpdateTime = newData[newData.length - 1].timestamp;
var newData2 = GenData2(N, lastUpdateTimeNew);
lastUpdateTimeNew = newData2[newData2.length - 1].timestamp;
for (var i = 0; i < newData.length; i++) {
if (globalData.length > 99) {
globalData.shift();
}
globalData.push(newData[i]);
}
for (var i = 0; i < newData2.length; i++) {
if (globalDataNew.length > 99) {
globalDataNew.shift();
}
globalDataNew.push(newData2[i]);
}
//code for transition start
x1 = newData[0].timestamp;
x2 = newData[newData.length - 1].timestamp;
dx = dx + (x(x1) - x(x2)); // dx needs to be cummulative
x1New = newData2[0].timestamp;
x2New = newData2[newData2.length - 1].timestamp;
dxNew = dxNew + (x(x1New) - x(x2New)); // dx needs to be cummulative
d3.select("path#path1")
.datum(globalData)
.attr("class", "line")
.attr("d", valueline(globalData))
.transition()
.ease("linear")
.attr("transform", "translate(" + String(dx) + ")");
d3.select("path#path2")
.datum(globalDataNew)
.attr("class", "line")
.attr("d", valueline2(globalDataNew))
.transition()
.ease("linear")
.attr("transform", "translate(" + String(dxNew) + ")");
d3.selectAll(".dot1")
.data(globalData)
.transition()
.ease("linear")
.attr("transform", "translate(" + String(dx) + ")");
d3.selectAll(".dot2")
.data(globalDataNew)
.transition()
.ease("linear")
.attr("transform", "translate(" + String(dx) + ")");
svg.select(".x.axis").call(xAxis);
}
body {
font: 12px Arial;
}
path {
stroke: black;
stroke-width: 1;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: black;
stroke-width: 2;
shape-rendering: crispEdges;
}
text {
fill: black;
}
rect {
fill: #add8e6;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
PS: You have to append new circles as the lines move to the left. However, this is another issue.
I had developed for the line graph code, but unable to zoom behavior for the given code,how to add for the zoom in line graph,i had tried for the zoom behavior,but unable to show the zoom in the line graph,the given data i had developed.
function draw(){
var s1=data.map(function (d,i){return {key:d.key[0],value:d.value}})
//console.log(s1);
var margin = {top: 15, right: 20, bottom: 70, left: 85},
width = 440,height = 450;
var parseDate = d3.time.format("%y").parse
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(7).tickFormat(d3.format("d"));
var yAxis = d3.svg.axis().scale(y).orient("left")
var area = d3.svg.area()
.interpolate("cardinal")
.x(function(d) { return x(d.key); })
.y0(y(0))
.y1(function(d) { return y(d.value); });
var line = d3.svg.line()
.x(function(d) { return x(d.key); })
.y(function(d) { return y(d.value); })
.interpolate("cardinal")
var div = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0);
var svg = d3.select("body").select("#lineCharts")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
x.domain(d3.extent(s1, function(d) { return d.key; }));
y.domain(d3.extent(s1, function(d) { return d.value; }));
var zoom = d3.behavior.zoom()
.on("zoom", drawZoom);
svg.append("g")
.attr("class", "x axis x-axis")
.attr("transform", "translate(0," + height + ")").attr("fill","steelblue")
.call(xAxis);
svg.append("path")
.datum(s1)
.attr("class", "area")
.attr("d", area);
svg.append("g").attr("class", "y axis y-axis").attr("fill","steelblue").call(yAxis)
svg.append("path").attr("class", "line").attr("d", line(s1));
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.style("fill","blue")
.attr("r","3.5")
.attr("cx",function (d,i){return x(d.key);})
.attr("cy",function(d,i){return y(d.value);})
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div .html((d.key) + "<br/>" + d.value)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY-28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
function drawZoom() {
svg.select("g.x axis x-axis").call(xAxis);
svg.select("g.y axis y-axis").call(yAxis);
svg.select("path.area").attr("d", area);
svg.select("path.line").attr("d", line(s1));
}
}
Try this maybe ?
{//-------------------------zoom
var minZoom = 0.2,
maxZoom = 2.5;
var zoom = d3.behavior.zoom()
.on("zoom", redraw)
.scaleExtent([minZoom, maxZoom])//-call zoom but put scale extent on to limit zoom in/out
;
}
function redraw() //-redraw
{
var trans=d3.event.translate;
var scale=d3.event.scale;
//var newScale = scale/2;
inner.attr("transform","translate(" + trans + ")" + " scale(" + scale + ")"); //-translates and scales
}
Call that on your background (svg) and use your mouse to pan and zoom :)
I'm having a bizarre d3 issue wherein my y-axis transition results in the axis switching sides. Besides that, I am happy with how the transition looks. A gif that demonstrates the issue is available at https://i.imgflip.com/g4kdc.gif. I have followed a few examples including http://bl.ocks.org/mbostock/4323929, but can't seem to figure out the issue.
var dataset = [{
"year_decided": 1982,
"Total": 0
}, //some more data
{
"year_decided": "2000",
"Total": "310"
}]; // default dataset that we can access and override
var margin = {
top: 30,
right: 20,
bottom: 20,
left: 35
};
var w = $("#section").width() - margin.left - margin.right;
var h = $("#section").height() - margin.top - margin.bottom;
///create the default scales
var xScale = d3.scale.linear()
.domain([0,dataset.length])
.range([0,w]);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset,function(d){ return +d.Total }) ])
.range([h,0]);
// create the axes
var xAxis = d3.svg.axis()
.scale(xScale)
.tickSize(6, 0)
.orient("bottom")
.tickFormat(function(d,i){
return d + 1982;
});
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("right")
.tickSize(w);
//define the svg and add it to the document
var svg = d3.select("#section").append("svg")
.attr("width",w + margin.left + margin.right)
.attr("height",h + margin.top + margin.bottom)
.attr("id", "main-chart");
svg.append("g")
.attr("transform","translate(" + margin.left + "," + margin.top + ")");
//add an axis group and add the y axis
var gy = svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.call(customAxis)
var gx = svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(" + margin.left + "," + h + ")")
.call(xAxis);
//create the line
var line = d3.svg.line()
.x(function(d, i){ return xScale(i) })
.y(function(d){ return yScale(+d.Total) })
.interpolate("linear");
svg.append('path')
.classed('data-line', true)
.attr('d', line(dataset))
.attr("transform", "translate(" + margin.left + ",0)");
//create the tooltip
var focus = svg.append("g")
.attr("class", "focus")
.style("display", "none");
focus.append("circle")
.attr("r", 4.5)
.attr("transform", "translate(" + margin.left + ",0)")
;
var tool_tip_year = focus.append("text")
.attr("x", 9)
.attr("dy", ".35em")
.attr("transform", "translate(" + margin.left + ",0)")
;
var tool_tip_total = focus.append("text")
.attr("x", 9)
.attr("dy", "1.8em")
.attr("transform", "translate(" + margin.left + ",0)")
;
svg.append("rect")
.attr("class", "overlay")
.attr("width", w)
.attr("height", h)
.attr("transform", "translate(" + margin.left + ",0)")
.on("mouseover", function() { focus.style("display", null); })
.on("mouseout", function() { focus.style("display", "none"); })
.on("mousemove", mousemove);
var bisectIndex = d3.bisector(function(d, i) { return i; }).left;
function mousemove() {
var x0 = xScale.invert(d3.mouse(this)[0]),
i = Math.round(x0),
d = dataset[i];
focus.attr("transform", "translate(" + xScale(i) + "," + yScale(+d.Total) + ")");
tool_tip_year.text(1982 + i);
tool_tip_total.text(d3.format(",")(+d.Total));
}
function customAxis(g){
g.selectAll("text")
.attr("x",4)
.attr("dy",-4);
}
//update the graph following http://bl.ocks.org/d3noob/7030f35b72de721622b8
$("#submission").submit(function(){
//define url to request
var submission = "php/data.php?word=" + $("#submission-text").val();
//request json and save as dataset
d3.json(submission, function(error, json) {
if (error) return console.warn(error);
dataset = json;
//rescale the graphs
xScale = d3.scale.linear()
.domain([0,dataset.length])
.range([0,w]);
yScale = d3.scale.linear()
.domain([0, d3.max(dataset,function(d){ return +d.Total }) ])
.range([h,0]);
gy.transition()
.duration(2500)
.call(yAxis);
gy.call(customAxis);
svg.select(".data-line")
.transition()
.duration(2000)
.attr("d",line(dataset));
})
});
I have some pretty simple code to plot a time series line graph. The x-scale is rendered correctly, however the line is not being rendered.
I am pretty sure that the issue we are facing here is with my function for calculating the x axis value, but I can't see what I might be doing wrong
My code for the graph is similar to this:
var data = getData();
var graph;
var line;
function getData() {
var theDate = new Date(2012, 01, 01, 0, 0, 0, 0);
var arr = [];
for (var x = 0; x < 30; x++) {
arr.push([theDate.getTime(), rand(100)]);
theDate.setDate(theDate.getDate() + 1);
}
return arr;
}
function rand(max) {
return Math.floor(Math.random() * (max + 1))
}
var m = [80, 80, 80, 80]; // margins
var w = 1000 - m[1] - m[3]; // width
var h = 400 - m[0] - m[2]; // height
// pretty sure the issue is which this line
var x = d3.time.scale().domain([new Date(data[0][0]), new Date(data[data.length - 1][0])]).range([0, w]);
var y = d3.scale.linear().domain([0, 100]).range([h, 0]);
line = d3.svg.line()
.x(function (d, i) { return x(new Date(d[0])); })
.y(function (d) { return y(d[1]); })
.interpolate("linear")
graph = d3.select("#graph").append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
var xAxis = d3.svg.axis().scale(x).ticks(d3.time.days, 1).tickFormat(d3.time.format("%d"));
graph.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
var yAxisLeft = d3.svg.axis().scale(y).ticks(10).orient("left");
graph.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(0,0)") //positon of the y axis
.call(yAxisLeft);
graph.append("svg:path")
.data([data])
.attr("class", "line")
.attr("transform", "translate(" + x(1) + ")")
.attr("d", line)
.transition()
.duration(1500)
.ease("linear")
.attr("transform", "translate(" + x(0) + ")");
I figured it out, changing
graph.append("svg:path")
.data([data])
.attr("class", "line")
.attr("transform", "translate(" + x(1) + ")")
.attr("d", line)
.transition()
.duration(1500)
.ease("linear")
.attr("transform", "translate(" + x(0) + ")");
to
graph.append("svg:path")
.data([data])
.attr("class", "line")
worked.
Obviously my transition for the x axis is incorrect