d3.js Bar Chart - Y Axis NaN - javascript

Getting NaN on the Y axis for a d3.js bar chart.
Question relates to this one .
The answer in that question has static data, which is identical to the Ajax JSON. See commented line for const data But the Ajax data is not working.
The data is loaded but the column with data has no height as there is no Y scale data.
Console log:
Error: <rect> attribute y: Expected length, "NaN".
Error: <rect> attribute height: Expected length, "NaN".
Error: <text> attribute y: Expected length, "NaN".
Chart with Ajax loaded data:
var margin = {top: 50, right: 135, bottom: 70, left: 80},
width = 1050 - margin.left - margin.right,
height = 540 - margin.top - margin.bottom;
var svg = d3.select("#domains")
.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 + ")");
//const data = [{"Domain":"Knowledge","Knowledge":0},{"Domain":"Problem Solving","problem_solving":0},{"Domain":"Skill","skill":0},{"Domain":"Transferable","transferable":100}];
d3.json("json/domains.json", function(error, data) {
const normalized = data.map(item => {
const name = item['Domain'];
const attr = name.toLowerCase().replace(' ', '_');
const value = item[attr];
return {name, value};
});
console.log('N: ', normalized);
/*
// Transpose the data into layers
var dataset = d3.layout.stack()(["Knowledge", "Problem Solving, Skill, Transferable"].map(function(lvl) {
return data.map(function(d) {
return {
x: d.Domain,
y: d[lvl]
};
});
}));
var disciplines = d3.nest()
.key(function(d){return d.Domain})
.rollup(function(leaves){
return d3.sum(leaves, function(d) {return d3.sum(d3.values(d))});
})
.entries(data);
*/
// Set x, y and colors
var x = d3.scale.ordinal()
.domain(normalized.map(item => item.name))
.rangeRoundBands([10, width-10], 0.35, 0);
const maxValue = normalized.reduce((max, item) => Math.max(max, item.value), 0);
var y = d3.scale.linear()
.domain([0, maxValue])
.range([height, 0]);
var colors = ["#83d1c4", "#f17950", "#838BD1", "#F150BE"];
// Define and draw axes
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickSize(-width, 0, 0)
.tickFormat(function(d) {
return d;
});
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.outerTickSize(0)
d3.select('.y axis .tick:first-child').remove();
/*
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-0, 0])
.html(function(d) {
return d.y + '%';
})
svg.call(tip);
*/
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(0,0)")
.call(yAxis);
svg.append("g")
.call(xAxis)
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("text")
.attr("x", 390 )
.attr("y", 480 )
.style("text-anchor", "middle")
.text("Domains");
svg.append("text")
.attr("x", -200 )
.attr("y", -40 )
.attr("transform", "rotate(-90)" )
.attr('style', 'font-size:12px')
.style("text-anchor", "middle")
.text("Percentage of Learning Events");
// Create groups for each series, rects for each segment
var groups = svg.selectAll("g.group")
.data(normalized)
.enter().append("g")
.attr("class", "group")
.style("fill", function(d, i) { return colors[i]; });
groups.append("rect")
.attr("y", function(d) { return y(d.value); })
.attr("x", d => x(d.name))
.attr("height", function(d) { return y(0) - y(d.value); })
.attr('class', 'segment')
.attr("width", x.rangeBand())
// .on('mouseover', tip.show)
// .on('mouseout', tip.hide);
columns = svg.append("g")
.selectAll("text")
.data(normalized)
.enter().append("text")
.attr("x", function(d){
return x(d.name) + x.rangeBand()/2
})
.attr("y", function (d) {
return y(d.value);
})
.attr("dy", "-0.7em")
.attr('style', 'font-size:11px')
.text( function (d){
return d3.format(".2f")(d.value) + '%';
})
.style({fill: 'black', "text-anchor": "middle"});
});
Chart with static data:

Although your dataset had an typo, which can break your current setup if you had the same in the json output. We can not be that sure if there is no data provided in example from actual json response, which can be different than what's in your const data example
const data = [{"Domain":"Knowledge","Knowledge":0},{"Domain":"Problem Solving","problem_solving":0},{"Domain":"Skill","skill":0},{"Domain":"Transferable","transferable":100}];
Try with lowercase "knowledge":0 which was printing the chart correctly on my screen
https://jsfiddle.net/978ync63/

Related

Plot multiple lines and scatter points on the same chart using d3, and use the mouseover function to calculate distance

I want to plot multiple lines and scatter plot on the same d3 chart.And I also define a mouse over function to calculate the distance between the scatter points and the line. Here is my js code:
import measurement from '../datasets/measurement';
// Parse the date / time
var parseDate = d3.time.format("%e/%_m/%Y %H");
// Get the data
d3.csv("../datasets/Book1.csv", function(error, data) {
data.forEach(function (d) {
d.date = parseDate.parse(d.dateHour);
d.estPressure = +d.x_inf;
d.lowPressure = +d.m1std;
d.upPressure = +d.p1std;
});
console.log(data);
// Set the dimensions of the canvas / graph
var margin = {top: 20, right: 50, bottom: 30, left: 66},
body_width = parseInt(d3.select('body').style('width').replace('px','')),
width = body_width - margin.left - margin.right,
height = 1000 - margin.top - margin.bottom;
// 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 + ")");
// Set the ranges
var x = d3.time.scale()
.domain([parseDate.parse("1/5/2016 00"), parseDate.parse("14/5/2016 23")])
// .domain(data.date])
.nice(d3.time.week)
/*.domain(data.map(function (d) {
return d.date;
}))*/
.range([0, width]);
//.rangeRoundBands([0, width], 0.1);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.time.format('%B %e %H:00'));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("text")
.attr("x", 1780)
.attr("y", 940)// text label for the x axis
.style("text-anchor", "end")
.text("Time");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("pressure");
y.domain([0, d3.max(data, function (d) {
return d.upPressure;
})]);
var line = d3.svg.line()
.x(function (d) {
return x(d.date);
})
.y(function (d) {
return y(d.estPressure);
});
// Draw line.
var linegraph = svg.selectAll("path.line").data([data], function (d) {
return d.date;
});
linegraph.attr('d', line).style("opacity", 1.0);
linegraph.enter().append("path")
.attr("class", "line")
.attr("d", line);
});
var data1 = measurement.map(function (d) {
Object.keys(d).forEach(function (key) {
d[key] = +d[key];
});
return d;
});
console.log(data1);
// Add the scatterplot
svg.selectAll(".dot")
.data(data1)
.enter().append("circle")
.attr("r", 4)
.attr("cx", function (d) {
return x(d.t);
})
.attr("cy", function (d) {
return y(d.est);
})
.on("mouseover", function (d) { //hover event
tooltip.transition()
.duration(100)
.style("opacity", .9)
.style("left", (d3.event.pageX + 20) + "px")
.style("top", (d3.event.pageY - 30) + "px");
var dist = 0, lowerbound;
data.forEach(function (n) {
if (n.t === d.t) {
dist = d.est - n.pressure ;
if (dist < 0) dist = dist * -1;
}
else if (n.time < d.t) { // linear interpolation for the t
lowerbound = n;
}
});
tooltip.html("<h1>" + "X: " + d.t + " Y: " + d.x + " distance:" + dist.toFixed(3) + "</h1>");
})
.on("mouseout", function (d) {
tooltip.transition()
.duration(200)
.style("opacity", 0);
});
And my csv data for the line chart is like this:
tHour,x_inf,p1std,m1std,dateHour
1,10,10.3,9.2,1/5/2016 00
2,12,16.8,7.2,1/5/2016 01
3,14,21.2,6.8,1/5/2016 02
4,15,19.8,10.2,1/5/2016 03
5,14.5,16.9,12.1,1/5/2016 04
6,18,22.96,13.04,1/5/2016 05
My jason data for the scatter points are like(measurement):
{
"t": 1,
"est": 1
},
{
"t": 3,
"est": 12
},
{
"t": 5,
"est": 14
},
{
Could anyone help me about the code? I am new to d3...And I just can plot only one line here using the dateHour as x and x_inf as y in the csv data. I want to use dateHour data as x and plot three lines using x_inf,p1std,m1std values. It would be so nice if you could also help me with the scatter points.

D3 - Having trouble updating stacked bar chart

I have a real simple horizontally stacked bar chart with 3 bars that are all on the same scale (i.e. each 0 to 100 with the stacked bars consisting of numbers that make up 100).
When trying to update my data nothing appears to happen. I've not been able to figure out how to update the data and it's been driving me crazy.
Relevant Code:
<body>
<div id='updateTest'>
Update Data
</div>
<div id='chart'></div>
<script>
$( document ).ready(function() {
$( "#updateTest" ).click(function() {
updateData();
console.log(allData[count]);
});
});
var institution;
// Set up the SVG data
var allData = ["data.csv","data2.csv","data3.csv"];
var count = 0;
var margin = {top: 20, right: 20, bottom: 145, left: 115},
width = 960 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var y = d3.scale.ordinal()
.rangeRoundBands([height, 0], .1);
var x = d3.scale.linear()
.rangeRound([0, width]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888"]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.format(".2s"));
var svg = d3.select("#chart").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 + ")");
// Bind initial shown data to the SVG
d3.csv(allData[count], function(error, data) {
if (error) throw error;
color.domain(d3.keys(data[0]).filter(function(key) {
return key !== "Institution";
}));
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) {
return {name: name, y0: y0, y1: y0 += +d[name]};
});
d.total = d.ages[d.ages.length - 1].y1;
});
data.sort(function(a, b) { return b.total - a.total; });
y.domain(data.map(function(d) { return d.Institution; }));
x.domain([0, d3.max(data, function(d) { return d.total; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("x", -32)
.attr("y", -112)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Institution");
institution = svg.selectAll(".institution")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) {
return "translate(0," + y(d.Institution) + ")"; });
institution.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("height", y.rangeBand())
.attr("x", function(d) { return x(d.y0); })
.attr("width", function(d) { return x(d.y1) - x(d.y0); })
.style("fill", function(d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(0," + i * 28 + ")"; });
legend.append("rect")
.attr("x", -20)
.attr("y", 190)
.attr("width", 25)
.attr("height", 25)
.style("fill", color);
legend.append("text")
.attr("x", 10)
.attr("y", 203)
.attr("dy", ".35em")
.style("text-anchor", "left")
.text(function(d) { return d; });
});
/* updateData()
* Rebinds the SVG to a new dataset
*/
function updateData() {
// Iterate through the data
var newData;
if (count === allData.length - 1)
count = 0;
else
count++;
newData = allData[count];
// Get the data again
d3.csv(allData[count], function(error, data) {
data.forEach(function(d) {
d.close = +d.close;
});
// Make the changes
institution.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("height", y.rangeBand())
.attr("x", function(d) { return x(d.y0); })
.attr("width", function(d) { return x(d.y1) - x(d.y0); })
.style("fill", function(d) { return color(d.name); });
});
}
</script>
</body>
My CSV files:
data.csv
Institution,CurrentlyOweBehind,CurrentlyOweNotBehind,Paid
For-profit,15,35,50
Nonprofit,11,48,41
Public,26,16,58
data2.csv
Institution,CurrentlyOweBehind,CurrentlyOweNotBehind,Paid
For-profit,23,33,44
Nonprofit,28,12,60
Public,12,8,80
data3.csv
Institution,CurrentlyOweBehind,CurrentlyOweNotBehind,Paid
For-profit,61,22,17
Nonprofit,7,43,50
Public,41,19,40
The main bit is in the updateData() function. I am able to create the chart and display data but I do not understand transitioning the data...
I'm getting no errors in the console and it's properly cycling the data.
The problems is with d.ages in the update function. You basically need the same setup that you have for the initial plot. So I added the following in the d3.csv block of your update function:
data.forEach(function(d) {
var y0 = 0;
d.ages = color.domain().map(function(name) {
return {name: name, y0: y0, y1: y0 += +d[name]};
});
d.total = d.ages[d.ages.length - 1].y1;
});
institution = svg.selectAll(".institution")
.data(data);
The class name for institution was set to g for some reason, and I changed that to institution. Also, you do not need .enter().append("rect") at this point. Finally I added a transition and duration.
I have created a plunk, with all your csv files included: http://plnkr.co/edit/CYFNWZKuiLo9gFps49e9?p=preview
Hope this helps.

d3.js bar chart sorting: can't figure out how to sort x-axis labels along with bars

I'm making a sortable d3 bar chart based on Scott Murray's tutorial, but he doesn't explain how to sort the x-axis labels along with the bars, and I haven't been able to figure it out despite various attempts. Here's my code; the relevant function is "sortBars" near the bottom, but I've included the rest for context.
(Here's a fiddle, but I can't seem to translate the data correctly from my JSON.)
The bar heights are data.days (which are numbers, i.e. number of days); the labels are data.names. How do I sort the labels?
function retirements(presidents){
var data = presidents;
var margin = {top: 20, right: 20, bottom: 180, left: 80},
width = 1100 - margin.left - margin.right,
height = 650 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(data.names)
.rangeBands([0, width], .1);
var y = d3.scale.linear()
.domain([0, Math.ceil(d3.max(data.days)/1000)*1000])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return d + " days";
})
var svg = d3.select(".container")
.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.call(tip);
var barWidth = width / data.days.length;
svg.selectAll("rect")
.data(data.days)
.enter().append("rect")
// this might be affected:
.attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; })
.attr("y", function(d) { return y(d); })
.attr("height", function(d) { return height - y(d) + 1; })
.attr("width", barWidth - 1)
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.9em")
.attr("dy", ".25em")
.attr("transform", "rotate(-50)" );
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "-6em")
.attr("dx","-15em")
.style("text-anchor", "end")
.text("Days");
var sortOrder = false;
var sortBars = function() {
svg.selectAll("rect")
.sort(function(a, b) {
if (sortOrder) {
return d3.descending(a, b);
} else {
return d3;
}
})
.transition()
.duration(1000)
.attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; })
$("#descending").on("click", function(){
sortOrder = true;
sortBars();
});
$("#chronological").on("click", function(){
sortOrder = false;
sortBars();
});
};
First of all rather than having 2 different arrays of presidents and its data.
Lets make it into single object so tat sorting is easy.
var newData = [];
data.names.forEach(function(d, i) {
newData.push({
name: d,//now object will have a name
days: data.days[i],//days will hold the president data
id: i //id of the record for chronology sorting
})
});
Now for sorting do this:
var sortBars = function() {
if (sortOrder){
//sort on basis of date
var sorted = newData.sort(function(a, b) {
return d3.descending(a.days, b.days);
});
} else {
//sort on basis of id
var sorted = newData.sort(function(a, b) {
return d3.ascending(a.id, b.id);
});
}
//set the domain post sorting
x.domain(sorted.map(function(d) {
return d.name;
}))
//sort the bars
svg.selectAll("rect")
.sort(function(a, b) {
if (sortOrder) {
return d3.descending(a.days, b.days);
} else {
return d3.ascending(a.id, b.id);
}
});
//make transition
var transition = svg.transition().duration(750),
delay = function(d, i) {
return i * 50;
};
//transition dor xa axis labels
transition.select(".x.axis")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.9em")
.attr("dy", ".25em")
.attr("transform", "rotate(-50)")
.delay(delay);
//transition for bars.
transition.selectAll("rect")
.attr("transform", function(d, i) {
return "translate(" + i * barWidth + ",0)";
});
}
Working code here
Hope this helps!

D3.js grouped bar chart plotting data multiple times

I am trying to create a grouped bar chart using D3.js. I have followed the examples provided in the D3 wiki at GitHub and have a semi working graph. However, it seems like all datapoints for a certain value get plotted at the same spot.
my data looks is a JSON array, which looks like this
[{"experiment":30385,"c":1,"ratio":0.022,"stdev":0.363,"median":0.032,"zscore":6.359},
{"experiment":30385,"c":2,"ratio":-0.02,"stdev":0.351,"median":-0.005,"zscore":-4.786},
{"experiment":30385,"c":3,"ratio":0.074,"stdev":0.339,"median":0.089,"zscore":29.036},
{"experiment":30385,"c":4,"ratio":-0.077,"stdev":0.361,"median":-0.065,"zscore":-25.704},
{"experiment":30385,"c":5,"ratio":-0.354,"stdev":0.569,"median":-0.223,"zscore":-145.625},
{"experiment":30385,"c":6,"ratio":-0.02,"stdev":0.352,"median":-0.007,"zscore":-2.545},
{"experiment":30385,"c":7,"ratio":0.018,"stdev":0.346,"median":0.036,"zscore":7.412},
{"experiment":30385,"c":8,"ratio":-0.11,"stdev":0.348,"median":-0.096,"zscore":-37.69},
{"experiment":30385,"c":9,"ratio":-0.012,"stdev":0.357,"median":0.008,"zscore":-4.394},
{"experiment":30385,"c":10,"ratio":-0.054,"stdev":0.366,"median":-0.036,"zscore":-14.158},
{"experiment":30385,"c":11,"ratio":-0.071,"stdev":0.344,"median":-0.044,"zscore":-21.4},
{"experiment":30385,"c":12,"ratio":-0.01,"stdev":0.352,"median":0.002,"zscore":-1.467},
{"experiment":30385,"c":13,"ratio":-0.03,"stdev":0.366,"median":-0.014,"zscore":-2.375},
{"experiment":30385,"c":14,"ratio":-0.039,"stdev":0.339,"median":-0.025,"zscore":-8.816},
{"experiment":30385,"c":15,"ratio":-0.02,"stdev":0.357,"median":0.0065,"zscore":-4.2},
{"experiment":30385,"c":16,"ratio":0.449,"stdev":0.439,"median":0.4215,"zscore":69.859},
{"experiment":30385,"c":17,"ratio":-0.028,"stdev":0.367,"median":-0.007,"zscore":-4.9},
{"experiment":30385,"c":18,"ratio":-0.071,"stdev":0.357,"median":-0.061,"zscore":-17.268},
{"experiment":30385,"c":19,"ratio":0.143,"stdev":0.356,"median":0.1415,"zscore":13.961},
{"experiment":30385,"c":20,"ratio":0.022,"stdev":0.349,"median":0.0405,"zscore":3.462},
{"experiment":30385,"c":21,"ratio":-0.076,"stdev":0.335,"median":-0.086,"zscore":-11.368},
{"experiment":30385,"c":22,"ratio":0.038,"stdev":0.355,"median":0.07,"zscore":3.152},
{"experiment":30385,"c":23,"ratio":0,"stdev":0,"median":0,"zscore":3.152},
{"experiment":30385,"c":24,"ratio":0,"stdev":0,"median":0,"zscore":3.152},
{"experiment":30384,"c":1,"ratio":-0.058,"stdev":0.403,"median":-0.042,"zscore":-14.154},
{"experiment":30384,"c":2,"ratio":-1.017,"stdev":0.418,"median":-0.982,"zscore":-360.857},
{"experiment":30384,"c":3,"ratio":-0.094,"stdev":0.417,"median":-0.074,"zscore":-30.964},
{"experiment":30384,"c":4,"ratio":-0.155,"stdev":0.397,"median":-0.157,"zscore":-54.593},
{"experiment":30384,"c":5,"ratio":-0.024,"stdev":0.381,"median":-0.001,"zscore":-8.125},
{"experiment":30384,"c":6,"ratio":0.013,"stdev":0.37,"median":0.0245,"zscore":7.455},
{"experiment":30384,"c":7,"ratio":-0.2,"stdev":0.434,"median":-0.171,"zscore":-56.706},
{"experiment":30384,"c":8,"ratio":-0.017,"stdev":0.367,"median":0.003,"zscore":-5.621},
{"experiment":30384,"c":9,"ratio":0.025,"stdev":0.365,"median":0.044,"zscore":6.818},
{"experiment":30384,"c":10,"ratio":-0.168,"stdev":0.422,"median":-0.121,"zscore":-44.158},
{"experiment":30384,"c":11,"ratio":-0.073,"stdev":0.382,"median":-0.056,"zscore":-22.067},
{"experiment":30384,"c":12,"ratio":0.002,"stdev":0.379,"median":0.019,"zscore":2.533},
{"experiment":30384,"c":13,"ratio":-0.054,"stdev":0.39,"median":-0.0295,"zscore":-8.375},
{"experiment":30384,"c":14,"ratio":0.019,"stdev":0.376,"median":0.025,"zscore":6.447},
{"experiment":30384,"c":15,"ratio":-0.054,"stdev":0.421,"median":-0.0265,"zscore":-11},
{"experiment":30384,"c":16,"ratio":0.055,"stdev":0.375,"median":0.0695,"zscore":8.297},
{"experiment":30384,"c":17,"ratio":0.024,"stdev":0.394,"median":0.054,"zscore":3.767},
{"experiment":30384,"c":18,"ratio":-0.049,"stdev":0.36,"median":-0.018,"zscore":-11.902},
{"experiment":30384,"c":19,"ratio":0.095,"stdev":0.37,"median":0.1135,"zscore":10.24},
{"experiment":30384,"c":20,"ratio":0.157,"stdev":0.343,"median":0.174,"zscore":29.423},
{"experiment":30384,"c":21,"ratio":-0.091,"stdev":0.407,"median":-0.067,"zscore":-14},
{"experiment":30384,"c":22,"ratio":0.071,"stdev":0.381,"median":0.104,"zscore":7.329},
{"experiment":30384,"c":23,"ratio":0,"stdev":0,"median":0,"zscore":7.329},
{"experiment":30384,"c":24,"ratio":0,"stdev":0,"median":0,"zscore":7.329}]
The data contains an experiment id, chromosome number, ratio and some satistics. The array can contain data from various experiments, which all have a different id.
my js code currently looks like this:
<script>
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
var margin = {top: 50, right: 50, bottom: 50, left: 50};
var width = 1000 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var threshold={upper:0.1,lower:-0.1};
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svg = d3.select("#svg").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 + ")");
d3.json("{{settings.Base_url}}/templates/addons/data.json", function(error, data) {
if (error) throw error;
var expNames =unique(data.map(function(d) { return d.experiment; }));
x0.domain(data.map(function(d) { return d.c; }));
x1.domain(expNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([-1.5,1.5]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -50)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Average Ratio/Chromosome");
var chr = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x0(d.c) + ",0)"; });
chr.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", function(d) {return x1(d.experiment);})
.attr("y", function(d) { return y(Math.max(0, d.ratio)); })
.attr("height", function(d) { return Math.abs(y(d.ratio)-y(0)); })
.attr("width", x1.rangeBand())
.style("fill", function(d) { return color(d.experiment); })
.style({"opacity":0.6,"stroke-width":"2"})
.text("test");
var legend = svg.selectAll(".legend")
.data(expNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
</script>
which results in a graph like this:
any ideas? I have a general idea where the error is, but cant seem to find a solution.
Note sure if I understand the question properly, but here's what I get:
You bind the data to the groups which you transform in x direction.
Afterwards you want to display two bars (for each experiment) in each group (c value)
If that's the case, you don't need to bind the data again for the bars, so it's just:
var chr = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function (d) {
return "translate(" + x0(d.c) + ",0)";
});
chr.append("rect")
.attr("x", function (d) {
return x1(d.experiment);
})
...etc
See fiddle
Does that help?

zoomable d3 line chart has disappearing data

I'm trying to add a zoom ability to a historical line chart I've built using a custom data object. I've been using http://codepen.io/brantwills/pen/igsoc/ as a template. The chart is rendered but when I try zooming there are two errors:
Error: Invalid value for path attribute d=""
Uncaught TypeError: undefined is not a function (in the last transform, translate of the last part of the zoomed function)
JSFiddle: http://jsfiddle.net/dshamis317/sFp6Q/
This is what my code looks like:
function renderHistoricalData(data) {
var parseDate = d3.time.format("%Y%m%d").parse;
data.forEach(function(d) { d.date = parseDate(d.date); });
// data.sort(function(a,b) { return a.date - b.date; });
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 1200 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1, 10])
.on("zoom", zoomed);
var line = d3.svg.line()
.interpolate("basis")
// .defined(function(d) { return d.y!=0; })
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.sentiment); });
var svg = d3.select("#historical_chart").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 + ")");
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
var sites = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, sentiment: +d[name]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(sites, function(c) { return d3.min(c.values, function(v) { return v.sentiment; }); }),
d3.max(sites, function(c) { return d3.max(c.values, function(v) { return v.sentiment; }); })
]);
var site = svg.selectAll(".site")
.data(sites)
.enter().append("g")
.attr("class", "site");
site.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
site.append("text")
.attr("transform", function(d) {
var val = d.values[d.values.length-1];
return "translate(" + x(val.date) + "," + y(val.sentiment) + ")";
})
.attr("x", 3)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d) { return d.name; });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Sentiment (%)");
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
svg.selectAll('path.line').attr('d', line);
sites.selectAll('.site').attr("transform", function(d) {
return "translate(" + x(d.date) + "," + y(d.sentiment) + ")"; }
);
}
}
Thank you!
Alright, let's walk through each thing.
To start with, in zoomed, the last transform doesn't need to be there. In the original, it's there to move the circles, which you don't have.
Also important, your edit on path.line sets d to the wrong function. If you look at what you're setting d to when you first make it, it should be the same, as a general rule of thumb, so it should be function(d) { return line(d.values); }, not just line.
Now, for the actual reason it's disappearing.
Your scale extent is calculated based off the original domain. However, you don't set the domain until AFTER you call scaleExtent, which means your scaling is all based on the default. It's not actually disappearing, it's being compressed to the left hand side of the graph. If you remove your x axis, you'll see the colored smear of all your data flattened against the side.
Move all your domain calculations to above where you build your scale, and it'll be fine.
To make things a bit more concrete:
function renderHistoricalData(data) {
var parseDate = d3.time.format("%Y%m%d").parse;
data.forEach(function(d) { d.date = parseDate(d.date); });
// data.sort(function(a,b) { return a.date - b.date; });
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 1200 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
var sites = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, sentiment: +d[name]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(sites, function(c) { return d3.min(c.values, function(v) { return v.sentiment; }); }),
d3.max(sites, function(c) { return d3.max(c.values, function(v) { return v.sentiment; }); })
]);
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1, 10])
.on("zoom", zoomed);
var line = d3.svg.line()
.interpolate("basis")
// .defined(function(d) { return d.y!=0; })
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.sentiment); });
var svg = d3.select("#historical_chart").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 + ")");
var site = svg.selectAll(".site")
.data(sites)
.enter().append("g")
.attr("class", "site");
site.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
site.append("text")
.attr("transform", function(d) {
var val = d.values[d.values.length-1];
return "translate(" + x(val.date) + "," + y(val.sentiment) + ")";
})
.attr("x", 3)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d) { return d.name; });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Sentiment (%)");
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
svg.selectAll('path.line').attr('d', function(d) { return line(d.values); });
}
}
If you want to text to move, you can give it an easily identifiable class, and then update it in zoomed.
Giving it a class:
site.append("text")
.attr("class", "lineLabel")
Updating it in zoomed:
svg.selectAll(".lineLabel")
.attr("transform", function(d) {
var val = d.values[d.values.length-1];
return "translate(" + x(val.date) + "," + y(val.sentiment) + ")";
});
This will just make it follow the ends of the lines, but you can modify whatever attributes you like to get the wanted effects.

Categories

Resources