I have a line chart and the full array of data is attached to the line. I want to change from using the value column to the pct (percent) column in the data. Is there a way of doing this in place, ie. using the values already in the DOM without passing it a new set of data?
as far as I've got - http://bl.ocks.org/3099307
var width = 700, // width of svg
height = 400, // height of svg
padding = 100; // space around the chart, not including labels
var data=[{"date":new Date(2012,0,1), "value": 3, 'pct': 55},
{"date":new Date(2012,0,3), "value": 2, "pct": 30 },
{"date":new Date(2012,0,12), "value": 33, "pct": 10},
{"date":new Date(2012,0,21), "value": 13, "pct": 29},
{"date":new Date(2012,0,30), "value": 23, "pct": 22}];
var x_domain = d3.extent(data, function(d) {
return d.date; }),
y_domain = d3.extent(data, function(d) { return d.value; });
// define the y scale (vertical)
var yScale = d3.scale.linear()
.domain(y_domain)
.range([height - padding, padding]); // map these top and bottom of the chart
var xScale = d3.time.scale()
.domain(x_domain)
.range([padding, width - padding]); // map these sides of the chart, in this case 100 and 600
// define the y axis
var yAxis = d3.svg.axis()
.orient("left")
.scale(yScale);
// define the x axis
var xAxis = d3.svg.axis()
.orient("bottom")
.scale(xScale);
// create the svg
var div = d3.select("body");
div.select("svg").remove();
var vis = div.append("svg")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + padding + "," + padding + ")");
// draw y axis with labels and move in from the size by the amount of padding
vis.append("g")
.attr("class", "axis yaxis")
.attr("transform", "translate("+padding+",0)")
.call(yAxis);
// draw x axis with labels and move to the bottom of the chart area
vis.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (height - padding) + ")")
.call(xAxis);
// DRAW LINES
var line = d3.svg.line()
.x(function(d) {
return xScale(d.date); })
.y(function(d) {
return yScale(d.value); })
.interpolate("basis");
vis.selectAll(".lines")
.data([data])
.enter()
.append("svg:path")
.attr("d", line)
.attr("class", "lines");
function rescale() {
// change the y axis to show percentage
yScale.domain([0,100]) // redraw as percentage outstanding
vis.select(".yaxis")
.transition().duration(1500).ease("sin-in-out") // https://github.com/mbostock/d3/wiki/Transitions#wiki-d3_ease
.call(yAxis);
What happens here?
// now redraw the line to use pct
line.y(function(d) {
return yScale(d.pct); });
vis.selectAll("lines")
.transition()
.duration(500)
.ease("linear");
}
Your data is already joined, so you just need to update your selection:
var yPctScale = d3.scale.linear()
.domain([0, 100])
.range([height - padding, padding]);
var pct_line = d3.svg.line()
.x(function(d) {
return xScale(d.date); })
.y(function(d) {
return yPctScale(d.pct); })
.interpolate("basis");
vis.selectAll(".lines")
.transition().duration(1500).ease("sin-in-out")
.attr("d", pct_line);
Related
I have a horizontal bar graph where the labels sometimes run off the end of the canvas. So for example if the Y axis is to the far left of the canvas, based on the distribution of the data values, instead of the label showing 'Chevrolet Corvette', only 'Chevro' will be visible. If I could keep the Y axis in the middle of the canvas (i.e. point 0,0 is in the middle) regardless of the data distribution, it would help solve my issue. Is it possible to keep the Y axis in the middle of the canvas and have the bars scale accordingly? fiddle:
https://jsfiddle.net/Kavitha_2817/2e1xLxLc/
var margin = {top: 30, right: 10, bottom: 50, left: 50},
width = 500,
height = 300;
var data = [{value: -10, dataset:"Corvette", year: "1975"},
{value: 40, dataset:"Lumina", year: "1975"},
{value: -10, dataset:"Gran Torino", year: "1971"},
{value: -50, dataset:"Pomtiac GTO", year: "1964"},
{value: 30, dataset:"Mustang", year: "19655"},
{value: -20, dataset:"Camaro", year: "1973"},
{value: -70, dataset:"Firebird", year: "1975"}];
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 + ')');
// set the ranges
var y = d3.scaleBand()
.range([height, 0])
.padding(0.1);
var x = d3.scaleLinear()
.range([0, width]);
// Scale the range of the data in the domains
x.domain(d3.extent(data, function (d) {
return d.value;
}));
y.domain(data.map(function (d) {
return d.dataset;
}));
// append the rectangles for the bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function (d) {
return "bar bar--" + (d.value < 0 ? "negative" : "positive");
})
.attr("x", function (d) {
return x(Math.min(0, d.value));
})
.attr("y", function (d) {
return y(d.dataset);
})
.attr("width", function (d) {
return Math.abs(x(d.value) - x(0));
})
.attr("height", y.bandwidth());
// add the x Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// add the y Axis
let yAxisGroup = svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + x(0) + ",0)")
I updated you jsfiddle to do what I understood you try to achieve. I did it by simply computing the domain manually to make it symetrical:
var min = d3.min(data, function(d){return d.value});
var max = d3.max(data, function(d){return d.value});
var absMax = Math.max(Math.abs(min), Math.abs(max));
x.domain([-absMax, absMax]);
This way, the min and max being equal but of opposite signs, the 0 will be at the center.
Here is my entire JS code, I'm really just getting started based on some example.
I would like to be able to catch a click event, wether on the whole drawing, wether on the chart line and get y value for it.
onMouseOver and onMouseOut work as intended for now.
Thank you.
//Example may be interesting: http://bl.ocks.org/byrongibson/5232838
var parseDate = d3.time.format("%d-%b-%y").parse;
var svg, d3, x, y, valueline, xAxis, yAxis, width, height;
function CreateSvg()
{
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50};
width = 600 - margin.left - margin.right;
height = 270 - margin.top - margin.bottom;
// Set the ranges
x = d3.time.scale().range([0, width]);
y = d3.scale.linear().range([height, 0]);
// Define the axes
xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
valueline = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
//var rect = d3.selectAll("rect");
// Adds the svg canvas
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 + ")").on("click", click)
;
}
function GetData(data)
{
data.forEach(function(d)
{
d.date = parseDate(d.date);
d.close = +d.close;
});
data.reverse();
data.push({date:parseDate('3-May-12'), close:Math.random() * 1200});
data.push({date:parseDate('4-May-12'), close:Math.random() * 1200});
data.reverse();
return data;
}
function Draw()
{
d3.csv("data.csv", function(error, data) {
data = GetData(data);
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);
svg.text("");
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data))
.on("mouseover", onMouseOver)
.on("mouseout", onMouseOut)
.on("click", click)
;
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
});
}
function click() {
alert("onclick");
}
function onMouseOver(){
alert("mouseOver");
};
function onMouseOut(){
alert("mouseOut");
};
CreateSvg();
Draw();
Draw();
I currently have a working scatter plot that I make using this
var data = (an array of arrays with two integers in each array)
var margin = {top: 20, right: 15, bottom: 60, left: 60}
, width = 300 - margin.left - margin.right
, height = 250 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[0]; })])
.range([ 0, width ]);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[1]; })])
.range([ height, 0 ]);
var chart = d3.select('.scatterGraph')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')
var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')
// draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom')
.ticks(5);
main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);
// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');
main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);
var g = main.append("svg:g");
g.selectAll("scatter-dots")
.data(data)
.enter().append("svg:circle")
.attr("cx", function (d,i) { return x(d[0]); } )
.attr("cy", function (d) { return y(d[1]); } )
.attr("r", 2);
I was wondering how I could add a line graph (or alternatively another scatter plot) to this graph. I'm very new to d3 so I'm currently lost on how to do it. For example I would just want to add a line described by a function y = 2t where t is the x axis of the scatterplot. Thanks!
If it is as simple as a line described by a function y=2t you can just append a line element to your chart in this case main like this, assuming that your width is at least greater than twice your height
main.append("line").attr("x1", 0).attr("x2", height/2)
.attr("y1", height).attr("y2", 0);
But if you have a line that connected through multiple points, you will need to add a path element to your svg, and use d3.svg.line() function to generate its d attribute. So something like this,
var lineFunction = d3.svg.line().x(function (d) { x(d[0])}; )
.y(function (d) { y(d[1])}; );
var gLine = main.append("g");
gLine.append("path").attr("d", lineFunction(data));
For another scatter plot, you can reuse
var g = main.append("svg:g");
g.selectAll("scatter-dots")
.data(data2)
.enter().append("svg:circle")
.attr("cx", function (d,i) { return x(d[0]); } )
.attr("cy", function (d) { return y(d[1]); } )
.attr("r", 2);
but with a different set of data, and different accessor functions or scales if needed.
I'm trying to build this trend component that is able to zoom and pan in data fetched with d3.json. First off, here's my code:
<script>
var margin = { top: 20, right: 80, bottom: 20, left: 50 },
width = $("#trendcontainer").width() - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var format = d3.time.format("%Y-%m-%d").parse;
var x = d3.time.scale()
.domain([-width / 2, width / 2])
.range([0, width]);
var y = d3.scale.linear()
.domain([-height / 2, height / 2])
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(-height);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickSize(-width);
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1, 10])
.on("zoom", zoomed);
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.value);
});
var 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);
d3.json('#Url.Action("DataBlob", "Trend", new {id = Model.Unit.UnitId, runId = 5})', function(error, json) {
$('#processing').hide();
color.domain(d3.keys(json[0]).filter(function(key) {
return key !== "Time" && key !== "Id";
}));
data.forEach(function(d) { var date = new Date(parseInt(d.Time.substr(6))); d.Time = date; });
var instruments = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {
date: d.Time,
value: +d[name]
};
})
};
});
x.domain(d3.extent(data, function(d) { return d.Time; }));
y.domain([
d3.min(instruments, function(c) {
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;
});
})
]);
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(yAxis);
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) + "," + y(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(yAxis);
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.select(".line")
.attr("class", "line")
.attr("d", line);
};
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(y)
.orient("left")
.ticks(5);
};
</script>
Problem here being that the zooming / panning does not interact with my lines. The just stay the same, 'below' the zoomable / pannable grid. Also, one of the lines disappear when trying to zoom / pan and my console says the following:
Error: Problem parsing d="" - referring to the following snippet, last line:
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
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.select(".line")
.attr("class", "line")
.attr("d", line);
};
Here's the content of my json result from the controller:
[{"Weight":0.0,"Speed":59.9,"Depth":362.24000,"Time":"2014-04-09T10:01:23","Id":0},{"Weight":10.0,"Speed":59.9,"Depth":394.07000,"Time":"2014-04-09T10:01:56","Id":1},{"Weight":971.0,"Speed":70.1,"Depth":425.84650,"Time":"2014-04-09T10:02:28","Id":2},{"Weight":0.0,"Speed":-29.9,"Depth":422.07465,"Time":"2014-04-09T10:03:00","Id":3},{"Weight":1321.0,"Speed":-21.6,"Depth":406.32840,"Time":"2014-04-09T10:03:32","Id":4},{"Weight":-6.0,"Speed":-30.0,"Depth":390.57880,"Time":"2014-04-09T10:04:04","Id":5},{"Weight":3.0,"Speed":59.9,"Depth":404.50380,"Time":"2014-04-09T10:04:36","Id":6},{"Weight":609.0,"Speed":59.9,"Depth":435.79380,"Time":"2014-04-09T10:05:08","Id":7},{"Weight":1.0,"Speed":59.9,"Depth":467.95280,"Time":"2014-04-09T10:05:40","Id":8},{"Weight":-2149.0,"Speed":34.6,"Depth":498.61060,"Time":"2014-04-09T10:06:12","Id":9},{"Weight":2.0,"Speed":59.9,"Depth":529.83060,"Time":"2014-04-09T10:06:44","Id":10}]
Trend looks like this in my view now, but the actual lines don't zoom or pan. Only the overlaying grid (black lines) does;
For simplicitys sake, I've considered just starting over, following the original example found here, but I really struggle with placing json-loaded data into this.
Hopefully, someone can help me figure this out :)
Thanks to Lars, I was finally able to solve this. Ultimately, I had to do some changes to my controller in addition to using this fiddle which assigns the scales to the zoom behaviour after setting the domains, so it returns a json string to my view like this:
string json = JsonConvert.SerializeObject(Model.Trend.ToArray());
return Json(json, JsonRequestBehavior.AllowGet);
This was due to the fact that some errors appeared when zooming / panning on the array returned without being serialized before returned to the view.
Also had to do the following for it to work:
d3.json('#Url.Action("DataBlob", "Trend", new {id = Model.Unit.UnitId, runId = 5})', function(error, tmparray) {
var json = JSON.parse(tmparray);
...
)};
If this step is skipped, my data will not be displayed properly for some reason, being squeezed to the left side of my graph.
I am new to d3.js and am trying to graph three lines on the same plot. I'm reading from a tsv file with four columns: time, x, y, and z. This is accelerometer data. I want to plot the x,y,z columns vs time but can't seem to get it. Any suggestions?
function graph(){
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.time); })
.y(function(d) { return y(d.x); });
var valueline2 = d3.svg.line()
.x(function(d) { return x(d.time); })
.y(function(d) { return y(d.y); })
var valueline3 = d3.svg.line()
.x(function(d) { return x(d.time); })
.y(function(d) { return y(d.z); });
// Adds the svg canvas
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 + ")");
// Get the data
d3.tsv("data/data2.tsv", function(error, data) {
data.forEach(function(d) {
d.time = +d.time;
d.x = +d.x;
d.y = +d.y;
d.z = +d.z;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.time; }));
y.domain([0, d3.max(data, function(d) { return Math.max(d.x, d.y, d.z); })]);
// Add the valueline path.
svg.append("path") // Add the valueline path.
.attr("class", "line")
.attr("d", valueline(data));
svg.append("path") // Add the valueline path.
.attr("class", "line")
.style("stroke", "red")
.attr("d", valueline2(data));
svg.append("path") // Add the valueline path.
.attr("class", "line")
.style("stroke", "green")
.attr("d", valueline3(data));
// Add the X Axis
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
});}
You can add each line one at a time to the canvas but it's not very d3 or efficient. It's much better to organise your data in the appropriate way. So the the main issue is the way that the data's been prepared. In the example that Lar's pointed to the data is nested using this block of code:
var series = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {
time: d.time,
score: +d[name]
};
})
};
});
And what this does is to create an array of 3 objects. Each object has a key value pair: name and
an array. In each array is another object which contains the time and score information for plotting. It is this last array of object that is passed to the line generator.
I've created a fiddle, here, that's heavily based on the example that Lar's has pointed to and it's commented throughout. The trick at this stage is to inspect the elements and use console.log
Best of luck.