d3.js can not update the chart - using json data - d3.js

I've been trying to get the update chart function to work... what am I doing wrong?
I've created a function to build the chart.
Then an update function once input boxes are changed - so if a user changes the data and then hits update.
I am unable to try and access the existing pie chart and update it/animate it with the correct data.
$.Core.doughnutCommon ={
init: function(){
var that = this;
var colourtheme = {
"spectrum" : ["#e87424", "#ebb700", "#007c92"]
};
$('[data-doughnut-pie-common="true"]').each(function(index) {
that.bindInputEvents($(this));
var holder = $(this)[0];
var data = that.generateData(holder);
console.log("data", data);
var theme = $(this).data("theme");
var colours = colourtheme[theme];
var radius = 64;
that.buildchart(holder, index, data, colours, radius);
});
},
bindInputEvents: function(holder){
var that = this;
holder.find('.updatechart').click(function(e) {
e.preventDefault();
that.updatechart(holder);
});
holder.find('.dataset li input').keyup(function() {
$(this).parent().parent().find('.value').text($(this).val());
});
},
generateData: function(holder){
var that = this;
var json = new Array();
var keysObj = {};
var legendsarray = new Array();
$(holder).find('.dataset li').each(function(index) {
var key = $(this).find('.key').text();
var value = $(this).find('.value').text();
//__key obj
var localKeyObj = {};
localKeyObj[key] = "";
//__legend array build
var stream = {
"name" : key,
"population" : value
}
jQuery.extend(keysObj, localKeyObj);
legendsarray.push(stream);
});
var obj ={
"legends": legendsarray
};
jQuery.extend(obj, keysObj);
json.push(obj);
return json;
},
updatechart: function(holder){
var that = this;
console.log("holder", holder);
var data = that.generateData(holder);
console.log("data hold", data);
var pieId = holder.find(".pie").attr("id");
//draw arc paths
//var svg = d3.select('#'+pieId);
var arc_group = d3.select('#'+pieId+' .sliceholder');
var color = d3.scale.ordinal();
var arc = d3.svg.arc()
.outerRadius(64)
.innerRadius(64 - 20);
paths = arc_group.selectAll("path").data(data[0].legends);
paths.enter().append("svg:path")
.attr("class", "arc")
.attr("d", arc)
.style("fill", function(d) {
console.log("d", d);
return color(d.name);
})
.transition()
.duration(500);
//.attrTween("d", arcTween);
paths
.transition()
.duration(500);
//.attrTween("d", arcTween);
paths.exit()
.transition()
.duration(500)
//.attrTween("d", arcTween);
.remove();
function arcTween(d) {
var i = d3.interpolate(this._current, d);
this._current = i(0);
return function(t) { return arc(i(t)); };
}
},
buildchart: function(holder, index, data, colours, radius){
var padding = 10;
var color = d3.scale.ordinal()
.range(colours);
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - 20);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
color.domain(
d3.keys(data[0]).filter(function(key) {
return key !== "legends";
})
);
var svg = d3.select(holder).selectAll(".pie")
.data(data)
.enter().append("svg")
.attr("class", "pie")
.attr("id", "pie"+index)
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("class", "sliceholder")
.attr("transform", "translate(" + radius + "," + radius + ")");
svg.selectAll(".arc")
.data(function(d) { return pie(d.legends); })
.enter().append("path")
.attr("class", "arc")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.name); });
var legend = d3.select(holder).append("svg")
.attr("class", "legend")
.attr("width", radius * 1.7)
.attr("height", radius * 2)
.selectAll("g")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 25 + ")"; });
legend.append("rect")
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", 24)
.attr("y", 9)
.attr("dy", ".35em")
.text(function(d) { return d; });
var totalUnits = svg.append("svg:text")
.attr("class", "units")
.attr("dy", 5)
.attr("text-anchor", "middle") // text-align: right
.text("Chart title");
}
};
The html is as follows
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="d3.v3.min.js"></script>
<script>
$.Core ={
init: function(){
console.log("test");
$.Core.doughnutCommon.init();//iniate doughnut read only
}
};
</script>
<script type="text/javascript" src="doughnut.common.js"></script>
<script>
$(document).ready(function() {
$.Core.init();
});
</script>
<div class="doughnut_pie common" data-doughnut-pie-common="true" data-theme="spectrum">
<form>
<ul class="dataset">
<li>
<span class="key">Equities</span>
<span class="value">50</span>
<span class="varbox"><input type="text" value="50"></span>
</li>
<li>
<span class="key">Bonds</span>
<span class="value">30</span>
<span class="varbox"><input type="text" value="30"></span>
</li>
<li>
<span class="key">Gilts</span>
<span class="value">20</span>
<span class="varbox"><input type="text" value="20"></span>
</li>
</ul>
<button class="updatechart">UPDATE</button>
</form>
</div>

There are a couple of problems with your code. First, the selector
var arc_group = d3.select('#'+pieId+' .sliceholder');
doesn't work because the g element with class sliceholder is a subelement of the SVG. You need
var arc_group = d3.select('#'+pieId+' > .sliceholder');
Second, you can't pass in the raw data when updating, you need to process it with a pie layout first. That is,
paths = arc_group.selectAll("path").data(data[0].legends);
won't work, you need
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
paths = arc_group.selectAll("path").data(pie(data[0].legends));
Third, you've missed some initialisation when copying the arcTween code. You need to set the initial values for ._current:
svg.selectAll(".arc")
.data(function(d) { return pie(d.legends); })
.enter().append("path")
...
.each(function(d) { this._current = d; });
Working jsfiddle here.

Related

How to display county tooltip in d3 map?

I am trying to create a tooltip in a D3 map. (also using DC.js). The problem is that it seems that the DC chart (mexicoChart) which holds the map is above everything or it is not compatible with the following code
(Nothing happens after adding it):
var width = 960
var height = 500
var projection = d3.geo.mercator()
.scale(1200)
.center([-102.34034978813841, 24.012062015793]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("svg")
.append("g")
.attr("width", width)
.attr("height", height);
var tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0)
.style("width", 600);
var g = svg.append("g");
d3.json("static/geojson/mx_tj.json", function(error, mx) {
svg.selectAll("path")
.data(topojson.feature(mx, mx.objects.municipalities))
.enter().append("path")
.attr("d", d3.geo.path().projection(projection))
.attr("fill", "transparent")
.style("stroke", "#333")
.style("stroke-width", ".2px")
.attr("class", "muns");
g.selectAll("path")
.data(topojson.feature(mx, mx.objects.states))
.enter().append("path")
.attr("d", d3.geo.path().projection(projection))
.attr("fill", "transparent")
.style("stroke", "#333");
svg.append("g")
.attr("class", "muns")
.selectAll("path")
.data(topojson.feature(mx, mx.objects.municipalities))
.enter().append("path")
.attr("d", path)
.on("mouseover", function (d) {var tip = "<h3>" + d.properties.name + "</h3>";
tooltip.html(tip)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY) + "px");
tooltip.transition()
.duration(500)
.style("opacity", .7); })
.on("mouseout", function (d) { tooltip.transition()
.duration(500)
.style("opacity", 0);
});
});
This is the second part of the code where the DC Charts are:
queue()
.defer(d3.json, "/homicidios/projects")
.defer(d3.json, "static/geojson/municipios.json")
.await(makeGraphs);
function makeGraphs(error, projectsJson, mx) {
//Clean projectsJson data
var homicidiosProjects = projectsJson;
var dateFormat = d3.time.format("%Y-%m-%d %H:%M:%S");
homicidiosProjects.forEach(function(d) {
d["fecha"] = dateFormat.parse(d["fecha"]);
d["fecha"].setMinutes(0);
d["fecha"].setSeconds(0);
// d["no_muertos"] = +d["no_muertos"];
});
//Create a Crossfilter instance
var ndx = crossfilter(homicidiosProjects);
//Define Dimensions
var FechaDim = ndx.dimension(function(d) {
return d["fecha"];
});
var zonaDim = ndx.dimension(function(d) {
return d["entidad_federativa"];
});
var pobrezaDim = ndx.dimension(function(d) {
return d["marginacion"];
});
var MunDim = ndx.dimension(function(d) {
return d["CVE_MUN"];
});
var noMuertosDim = ndx.dimension(function(d) {
return d["no_muertos"];
});
//Calculate metrics
var numProjectsPorFecha = FechaDim.group();
var numProjectsPorZona = zonaDim.group();
var numProjectsPorPobreza = pobrezaDim.group();
var noMuertosPorMun = MunDim.group().reduceSum(function(d) {
return d["no_muertos"];
});
var all = ndx.groupAll();
var noMuertos = ndx.groupAll().reduceSum(function(d) {
return d["no_muertos"];
});
var max_mun = noMuertosPorMun.top(1)[0].value;
//Define values (to be used in charts)
var minDate = FechaDim.bottom(1)[0]["fecha"];
var maxDate = FechaDim.top(1)[0]["fecha"];
//Charts
var timeChart = dc.barChart("#time-chart");
var zonaChart = dc.rowChart("#zona-row-chart");
var pobrezaChart = dc.rowChart("#pobreza-row-chart");
var mexicoChart = dc.geoChoroplethChart("#mexico-Chart");
var numberProjectsND = dc.numberDisplay("#number-projects-nd");
var noMuertosND = dc.numberDisplay("#no-muertos-nd");
numberProjectsND
.formatNumber(d3.format("d"))
.valueAccessor(function(d) {
return d;
})
.group(all);
noMuertosND
.formatNumber(d3.format("d"))
.valueAccessor(function(d) {
return d;
})
.group(noMuertos)
.formatNumber(d3.format(".3s"));
timeChart
.width(1000)
.height(180)
.margins({
top: 10,
right: 50,
bottom: 20,
left: 50
})
.dimension(FechaDim)
.group(numProjectsPorFecha)
.transitionDuration(500)
.x(d3.time.scale().domain([minDate, maxDate]))
.elasticY(true)
.xAxisLabel("Dia")
.yAxis().ticks(10);
zonaChart
.width(300)
.height(350)
.dimension(zonaDim)
.group(numProjectsPorZona)
.xAxis().ticks(4);
pobrezaChart
.width(300)
.height(250)
.dimension(pobrezaDim)
.group(numProjectsPorPobreza)
.xAxis().ticks(4);
d3.json("static/geojson/municipios.json", function (error, mx) {
mexicoChart.width(1000)
.height(630)
.dimension(MunDim)
.group(noMuertosPorMun)
.colors(["#FFE5EC", "#FFCCD9", "#FFB2C6", "#FF99B3", "#FF7FA0", "#FF668D", "#FF4C7A", "#FF3367", "#FF1954", "#FF0041"])
.colorDomain([0, max_mun])
.overlayGeoJson(mx.features, "municipio", function(d) {
return d.properties.CVE_MUN;
})
.projection(d3.geo.mercator()
.center([-101.45, 19.28])
.scale(1600)
.translate([490, 490]))
.title(function(p) {
return "State: " + p["key"] +
"\n" +
"Total Muertos: " + Math.round(p["value"]) + " $";
})
dc.renderAll();
});
}

Get bounding box of individual countries from topojson

I want to get bounding boxes for each country from a topojson, but when I add them as svg rectangles they are bundled together towards 0,0.
Ive re-read the API and played around with the order of the bound coordinates, but that didn't change anything! Also, I tried to use the SVG method getBBox() on the country paths but that produced the same result.
Any ideas?
var width = 700,
height = 400,
bboxes = [];
d3.queue()
.defer(d3.json, "data/world.topojson")
.await(ready);
//Map projection
var proj = d3.geoMercator()
.scale(100)
.center([-0.0018057527730242487, 11.258678472759552]) //projection center
.translate([width / 2, height / 2]) //translate to center the map in view
//Generate paths based on projection
var myPath = d3.geoPath().projection(proj);
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
//Group for the map features
var map = svg.append("g")
.attr("class", "map");
function ready(error, geodata) {
if (error) return console.log(error); //unknown error, check the console
//Create a path for each map feature in the data
map.selectAll("path")
.data(topojson.feature(geodata, geodata.objects.subunits).features) //generate features from TopoJSON
.enter()
.append("path")
.attr("class", "country")
.attr("id", function(d) {
return d.id;
})
.attr("d", myPath);
bboxes = boundingExtent(topojson.feature(geodata, geodata.objects.subunits).features);
svg.selectAll("rect")
.data(bboxes)
.enter()
.append("rect")
.attr("id", function(d){
return d.id;
})
.attr("class", "bb")
.attr("x1", function(d) {
return d.x;
})
.attr("y1", function(d) {
return d.y;
})
.attr("width", function(d) {
return d.width;
})
.attr("height", function(d) {
return d.height;
})
}
function boundingExtent(features) {
var bounds= [];
for (var x in features) {
var boundObj = {};
thisBounds = myPath.bounds(features[x]);
boundObj.id = features[x].id;
boundObj.x = thisBounds[0][0];
boundObj.y = thisBounds[0][1];
boundObj.width = thisBounds[1][0] - thisBounds[0][0];
boundObj.height = thisBounds[1][1] - thisBounds[0][1];
boundObj.path = thisBounds;
bounds.push(boundObj)
}
return bounds;
}
function boundExtentBySvg(){
var countries = svg.selectAll(".country")
countries.each(function(d){
var box = d3.select(this).node().getBBox();
bboxes.push({id: d.id, x: box.x, y : box.y, width: box.width, height : box.height})
})
}
In these lines:
.attr("x1", function(d) {
return d.x;
})
.attr("y1", function(d) {
return d.y;
})
rect does not have an attribute of x1 or y1, I think you meant just x and y.
Here's your code running (note, I switched out the topojson file which caused slight code changes):
<!DOCTYPE html>
<html>
<head>
<script data-require="d3#4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
<script data-require="topojson.min.js#3.0.0" data-semver="3.0.0" src="https://unpkg.com/topojson#3.0.0"></script>
</head>
<body>
<svg width="700" height="400"></svg>
<script>
var width = 700,
height = 400,
bboxes = [];
d3.queue()
.defer(d3.json, "https://unpkg.com/world-atlas#1/world/110m.json")
.await(ready);
//Map projection
var proj = d3.geoMercator()
.scale(100)
.center([-0.0018057527730242487, 11.258678472759552]) //projection center
.translate([width / 2, height / 2]) //translate to center the map in view
//Generate paths based on projection
var myPath = d3.geoPath().projection(proj);
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
//Group for the map features
var map = svg.append("g")
.attr("class", "map");
function ready(error, geodata) {
if (error) return console.log(error); //unknown error, check the console
//Create a path for each map feature in the data
map.selectAll("path")
.data(topojson.feature(geodata, geodata.objects.countries).features) //generate features from TopoJSON
.enter()
.append("path")
.attr("class", "country")
.attr("id", function(d) {
return d.id;
})
.attr("d", myPath);
bboxes = boundingExtent(topojson.feature(geodata, geodata.objects.countries).features);
svg.selectAll("rect")
.data(bboxes)
.enter()
.append("rect")
.attr("id", function(d) {
return d.id;
})
.attr("class", "bb")
.attr("x", function(d) {
return d.x;
})
.attr("y", function(d) {
return d.y;
})
.attr("width", function(d) {
return d.width;
})
.attr("height", function(d) {
return d.height;
})
.style("fill", "none")
.style("stroke", "steelblue");
}
function boundingExtent(features) {
var bounds = [];
for (var x in features) {
var boundObj = {};
thisBounds = myPath.bounds(features[x]);
boundObj.id = features[x].id;
boundObj.x = thisBounds[0][0];
boundObj.y = thisBounds[0][1];
boundObj.width = thisBounds[1][0] - thisBounds[0][0];
boundObj.height = thisBounds[1][1] - thisBounds[0][1];
boundObj.path = thisBounds;
bounds.push(boundObj)
}
console.log(bounds)
return bounds;
}
function boundExtentBySvg() {
var countries = svg.selectAll(".country")
countries.each(function(d) {
var box = d3.select(this).node().getBBox();
bboxes.push({
id: d.id,
x: box.x,
y: box.y,
width: box.width,
height: box.height
})
})
}
</script>
</body>
</html>

D3.js How to hide/show line when click select options?

I tried to use D3.js to draw lines when you click on different checkbox. It will get data of that option. Here is an example I used D3 multi-series line chart with tooltips and legend. I have got the specific data object that is corresponding the checkbox I choose. Howevery, I don't know how to draw it on svg. Please help me and I will appreciate you so much.
I also find a website "www.cotrino.com/starpaths/" that shows the final effect I want to implement.
My D3 effect
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis--x path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
<script src="http://d3js.org/d3.v4.js"></script>
<body>
<svg width="1000" height="500"></svg>
<div id="disease_list"></div>
</body>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 80, bottom: 30, left: 50},
width = svg.attr("width") - margin.left - margin.right,
height = svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//make a clip path for the graph
var clip = svg.append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height);
var parseTime = d3.timeParse("%Y-%m");
var x = d3.scaleTime().range([0, width]),
y = d3.scaleLinear().range([height, 0]);
var line = d3.line()
.curve(d3.curveBasis)
.x(function(d) { console.log(d.date); return x(d.date); })
.y(function(d) { console.log(d.date); return y(d.count); });
var color = d3.scaleOrdinal(d3.schemeCategory20);
d3.csv("./top10highestNormalize.csv", type, function(error, data) {
if (error) throw error;
var diseases = data.columns.slice(1).map(function(id) {
return {
id: id,
values: data.map(function(d) {
return {date: d.date, count: d[id]};
})
};
});
console.log(diseases);
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(diseases, function(c) { return d3.min(c.values, function(d) { return d.count; }); }),
d3.max(diseases, function(c) { return d3.max(c.values, function(d) { return d.count; }); })
]);
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))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("fill", "#000")
.text("Count");
/*
var disease = g.selectAll(".disease")
.data(diseases)
.enter().append("g")
.attr("class", "disease");
*/
// Create the shape selectors
var selector = d3.select("#disease_list").append("select");
labels = selector.selectAll("option")
.data(diseases)
.enter()
.append("option")
.attr("value",function(d,i) {return i;})
.text(function(d) {return d.id;});
var menu = d3.select("#disease_list select")
.on("change", redraw);
// var series = menu.property("value");
//console.log(series);
// all the meat goes in the redraw function
function redraw() {
console.log("redraw start");
// get value from menu selection
// the option values are set in HTML and correspond
//to the [type] value we used to nest the data
var series = menu.property("value");
console.log(series);
// only retrieve data from the selected series, using the nest we just created
var adata = diseases[series];
console.log(adata);
}
});
function type(d, _, columns) {
d.date = parseTime(d.date);
for (var i = 1, n = columns.length, c; i < n; ++i) d[c = columns[i]] = +d[c];
return d;
}
</script>
top10highestNormalize.csv
date,disseminated sclerosis,sclerosis,gestural tics,venereal disease,bite,cot death,venereal disease,cardiovascular disease,diseases vascular,pruritis,pus,cystic fibrosis,fibroses
2010-04,0,0,0,0,0,0,0,0,0,0,0,0,0
2010-05,0,0,0.06898023,0.068783069,0.085790885,0.065761258,0.068783069,0,0,0.001204094,0.023051592,0,0
2010-06,0.076923077,0.076923077,0.190584554,0.199972867,0.201072386,0.171789373,0.199972867,0.071428571,0.071428571,0.004816376,0.031284303,0.2,0.2
2010-07,0.230769231,0.230769231,0.221590101,0.224664225,0.225201072,0.235167977,0.224664225,0.214285714,0.285714286,0.00602047,0.038419319,0,0
2010-08,0.538461538,0.538461538,0.174797326,0.182471849,0.174262735,0.192041935,0.182471849,0.071428571,0.071428571,0.003612282,0.023051592,0,0
2010-09,0.230769231,0.230769231,0.287725786,0.277845611,0.252010724,0.259471051,0.277845611,0,0,0.004214329,0.046652031,0,0
2010-10,0.076923077,0.076923077,0.295406059,0.299416633,0.285969616,0.265665952,0.299416633,0,0.071428571,0.007224564,0.03402854,0.066666667,0.066666667
2010-11,0.153846154,0.153846154,0.284027877,0.279337946,0.261840929,0.276149631,0.279337946,0,0,0.006622517,0.050493963,0,0
2010-12,0.153846154,0.153846154,0.271511876,0.237552571,0.213583557,0.237312366,0.237552571,0.142857143,0.142857143,0.004214329,0.035126235,0,0
2011-01,0.076923077,0.076923077,0.306642014,0.312440646,0.28150134,0.305694544,0.312440646,0.142857143,0.142857143,0.006622517,0.046103183,0,0.066666667
2011-02,0.076923077,0.076923077,0.288721377,0.262243929,0.219839142,0.25899452,0.262243929,0.142857143,0.142857143,0.007224564,0.038968167,0,0.066666667
2011-03,0.076923077,0.076923077,0.271654103,0.255324922,0.253798034,0.266857279,0.255324922,0.071428571,0.071428571,0.007224564,0.051591658,0,0
2011-04,0.461538462,0.461538462,0.291423695,0.252068919,0.235031278,0.284250655,0.252068919,0,0,0.009030704,0.045005488,0,0
2011-05,0.153846154,0.153846154,0.448158157,0.380681047,0.351206434,0.439123183,0.380681047,0,0,0.011438892,0.079582876,0.333333333,0.4
2011-06,0.153846154,0.153846154,0.498079932,0.437661104,0.391420912,0.424827258,0.437661104,0.142857143,0.142857143,0.009632751,0.063117453,0,0.066666667
2011-07,0,0,0.410467928,0.424094424,0.419124218,0.379080295,0.424094424,0,0.071428571,0.009030704,0.061470911,1,1
2011-08,0.076923077,0.076923077,0.268382876,0.262922263,0.238605898,0.267810341,0.262922263,0.214285714,0.214285714,0.002408188,0.038968167,0,0
2011-09,0.230769231,0.230769231,0.510027023,0.469949803,0.470956211,0.444841553,0.469949803,0,0,0.014449127,0.075740944,0.133333333,0.2
2011-10,0.076923077,0.076923077,0.462380885,0.434540768,0.431635389,0.417679295,0.434540768,0.142857143,0.142857143,0.006622517,0.073545554,0,0.066666667
2011-11,0.153846154,0.153846154,0.519698478,0.457061457,0.415549598,0.443888492,0.457061457,0.142857143,0.142857143,0.01384708,0.06805708,0.2,0.2
2011-12,1,1,0.382449154,0.35002035,0.319928508,0.315701692,0.35002035,0,0,0.002408188,0.060373216,0,0
2012-01,0.461538462,0.461538462,0.492390841,0.45312712,0.409294013,0.45389564,0.45312712,0.571428571,0.571428571,0.007224564,0.060373216,0,0
2012-02,0.076923077,0.076923077,0.382875836,0.375932709,0.350312779,0.369073147,0.375932709,0.071428571,0.071428571,0.003612282,0.049945115,0.066666667,0.066666667
2012-03,0.923076923,1,1,0.922127255,1,0.871098404,0.922127255,0.5,0.5,0.01384708,0.171789243,0,0.066666667
2012-04,0.230769231,0.307692308,0.699331532,0.676977344,0.63360143,0.645699309,0.676977344,0.142857143,0.142857143,0.012040939,0.092206367,0.133333333,0.133333333
2012-05,0.846153846,0.846153846,0.801735173,0.752408086,0.776586238,0.7436264,0.752408086,0.785714286,0.785714286,0.016857315,0.131723381,0.466666667,0.466666667
2012-06,0.384615385,0.461538462,0.730479306,0.732193732,0.625558534,0.657850846,0.732193732,0,0,0.011438892,0.118002195,0.6,0.666666667
2012-07,0.384615385,0.384615385,0.751386716,0.738434405,0.71849866,0.714081487,0.738434405,0.285714286,0.285714286,0.009030704,0.126783754,0.2,0.2
2012-08,0.384615385,0.461538462,0.700327123,0.643467643,0.619302949,0.646890636,0.643467643,0.285714286,0.285714286,0.012642986,0.150933041,0.2,0.266666667
2012-09,0.076923077,0.230769231,0.72137676,0.701804368,0.63538874,0.70455087,0.701804368,0.214285714,0.214285714,0.011438892,0.130076839,0.066666667,0.066666667
2012-10,0.230769231,0.230769231,0.846252311,0.863112196,0.796246649,0.825827972,0.863112196,0.071428571,0.071428571,0.036724865,0.127881449,0.333333333,0.333333333
2012-11,0.692307692,0.692307692,0.895605177,1,0.798927614,0.909935668,1,0.214285714,0.357142857,0.012642986,0.143798024,0,0.133333333
2012-12,0.923076923,1,0.795903854,0.803283137,0.683646113,0.827257565,0.803283137,0.142857143,0.142857143,0.008428657,0.104829857,0.6,0.6
2013-01,0.230769231,0.384615385,0.92106386,0.964862298,0.848078642,0.944007624,0.964862298,0.285714286,0.357142857,0.015653221,0.146542261,0.533333333,0.733333333
2013-02,0.153846154,0.307692308,0.830322856,0.872880206,0.798927614,0.755777937,0.872880206,0.142857143,0.142857143,0.010234798,0.110318332,0,0.066666667
2013-03,0.230769231,0.230769231,0.927037406,0.944105277,0.885612154,0.953061711,0.944105277,0.142857143,0.142857143,0.009632751,0.131174533,0,0.133333333
2013-04,0.384615385,0.384615385,0.796046082,0.775471442,0.671134942,0.715749345,0.775471442,0,0,0.012040939,0.12349067,0.133333333,0.133333333
2013-05,0.923076923,1,0.824633765,0.844254511,0.742627346,0.843697879,0.844254511,0.142857143,0.142857143,0.015653221,0.149286498,0,0
2013-06,0.307692308,0.307692308,0.884369222,0.949667616,0.865951743,1,0.949667616,0.071428571,0.071428571,0.020469597,0.135016465,0.466666667,0.466666667
2013-07,0.461538462,0.461538462,0.864172948,0.935829602,0.843610366,0.939480581,0.935829602,0.071428571,0.071428571,0.015051174,0.128979144,0.066666667,0.2
2013-08,0.153846154,0.153846154,0.670886076,0.738163071,0.753351206,0.821300929,0.738163071,0.071428571,0.214285714,0.012642986,0.098243688,0,0
2013-09,0.230769231,0.230769231,0.876262267,0.861484195,0.744414656,0.996426019,0.861484195,0,0,0.024081878,0.144895719,0.066666667,0.066666667
2013-10,0.615384615,0.615384615,0.917508178,0.885361552,0.806970509,0.841315225,0.885361552,0.642857143,0.642857143,0.030704395,0.115806806,0.2,0.4
2013-11,0,0.076923077,0.857061584,0.903540904,0.791778374,0.845127472,0.903540904,0.5,0.5,0.012642986,0.093852909,0,0
2013-12,0.230769231,0.230769231,0.704878396,0.719169719,0.584450402,0.81915654,0.719169719,0.285714286,0.5,0.015653221,0.108122942,0,0
2014-01,0.461538462,0.461538462,0.900014223,0.856328856,0.717605004,0.98903979,0.856328856,0.357142857,0.5,0.030102348,0.137211855,0,0.066666667
2014-02,0,0,0.707865169,0.703296703,0.63717605,0.796997856,0.703296703,1,1,0.012642986,0.097145993,0,0
2014-03,0.230769231,0.230769231,0.815531219,0.800434134,0.7256479,0.786275911,0.800434134,0.714285714,0.714285714,0.009632751,0.099341383,0.533333333,0.6
2014-04,0.153846154,0.153846154,0.756506898,0.790259124,0.615728329,0.778174887,0.790259124,0,0,0.011438892,0.12349067,0,0
2014-05,0.461538462,0.461538462,0.85990613,0.767331434,0.705987489,0.78008101,0.767331434,0.142857143,0.285714286,0.014449127,0.13611416,0.066666667,0.133333333
2014-06,0.076923077,0.153846154,0.670886076,0.713064713,0.615728329,0.735763641,0.713064713,0.285714286,0.285714286,0.010836845,0.102634468,0,0
2014-07,0.076923077,0.076923077,0.672592803,0.801655135,0.621090259,0.680009531,0.801655135,0.071428571,0.071428571,0.007224564,0.103183315,0,0
2014-08,0.384615385,0.461538462,0.487270659,0.58377425,0.486148347,0.575887539,0.58377425,0.071428571,0.071428571,0.005418423,0.079582876,0,0.133333333
2014-09,0,0.076923077,0.715545442,0.678062678,0.669347632,0.705980462,0.678062678,0,0,0.01384708,0.103183315,0,0.066666667
2014-10,0.230769231,0.307692308,0.742995306,0.723511057,0.630920465,0.679294734,0.723511057,0,0,0.016857315,0.1064764,0,0
2014-11,0,0,0.672735031,0.623388957,0.583556747,0.64927329,0.623388957,0,0,0.004816376,0.115806806,0.066666667,0.066666667
2014-12,0.307692308,0.384615385,0.591096572,0.55704789,0.478999106,0.491303312,0.55704789,0.285714286,0.428571429,0.003010235,0.074643249,0,0
2015-01,0.076923077,0.153846154,0.659223439,0.561117894,0.531724754,0.605432452,0.561117894,0.071428571,0.071428571,0.007224564,0.094401756,0.133333333,0.133333333
2015-02,0.230769231,0.307692308,0.61840421,0.564780898,0.512064343,0.585656421,0.564780898,0.071428571,0.071428571,0.007224564,0.096597146,0,0
2015-03,0,0,0.770302944,0.677927011,0.599642538,0.675482487,0.677927011,0.071428571,0.071428571,0.009632751,0.111964874,0.066666667,0.2
2015-04,0.076923077,0.076923077,0.706016214,0.61687695,0.731903485,0.563497736,0.61687695,0.071428571,0.071428571,0.008428657,0.097145993,0,0
2015-05,0,0.076923077,0.655383303,0.614027947,0.55406613,0.6154396,0.614027947,0.071428571,0.071428571,0.012642986,0.099341383,0,0
2015-06,0,0.076923077,0.564357844,0.540632207,0.527256479,0.598284489,0.540632207,0.142857143,0.142857143,0.00602047,0.091657519,0,0
2015-07,0.076923077,0.076923077,0.486417295,0.525301859,0.511170688,0.566356922,0.525301859,0,0,0.015653221,0.08726674,0.066666667,0.066666667
2015-08,0.230769231,0.230769231,0.408476746,0.386379053,0.320822163,0.465094115,0.386379053,0,0,0.003010235,0.056531284,0,0
2015-09,0.538461538,0.538461538,0.870999858,0.792701126,0.747095621,0.883964737,0.792701126,0,0,0.013245033,0.156421515,0,0
2015-10,0.153846154,0.153846154,0.469492249,0.435490435,0.320822163,0.51227067,0.435490435,0,0,0.174593618,0.221734358,0,0
2015-11,0.153846154,0.153846154,0.322998151,0.309455976,0.273458445,0.346676197,0.309455976,0,0,0.462974112,0.481888035,0.133333333,0.133333333
2015-12,0.076923077,0.076923077,0.342767743,0.309320309,0.27971403,0.384798666,0.309320309,0,0,0.464780253,0.482436883,0.066666667,0.066666667
2016-01,0.307692308,0.384615385,0.415872564,0.349477683,0.358355675,0.442458899,0.349477683,0,0,0.559903672,0.581229418,0.066666667,0.066666667
2016-02,0,0,0.445455838,0.403744404,0.316353887,0.457469621,0.403744404,0,0,0.54846478,0.568605928,0.066666667,0.066666667
2016-03,0,0,0.471198976,0.400352734,0.317247542,0.508220157,0.400352734,0.142857143,0.142857143,0.604455148,0.628430296,0,0
2016-04,0,0,0.582989617,0.570343237,0.575513852,0.603764594,0.570343237,0.214285714,0.214285714,1,1,0,0
You need to create your line variable:
var myLine = svg.append("path");
And then, inside redraw(), changing it according to the option selected:
myLine.datum(adata.values)
.attr("d", line);
Here is a demo plunker: https://plnkr.co/edit/YjGO9TLDBXj13JQuO5bm?p=preview
PS: I changed your x-scale range:
var x = d3.scaleTime().range([margin.left, width]);
And also added a call to redraw() when the code runs for the first time.

D3.js Multiple lines on a chart

The lines of my chart are drawing off my chart. I've tried to replace this code:
yE.domain(d3.extent(data, function(E) { return E.close;}));
With this:
yE.domain([0,d3.max(data, function(E) {
return Math.max(E.close, E.Map1, EMap2, E.MapII);
})]);
Based on the answer from Bill: d3.js: dataset array w/ multiple y-axis values
Mine doesn't work.
My entire code:
var marginE = {top: 30, right: 20, bottom: 30, left: 50},
widthE = 400 - marginE.left - marginE.right,
heightE = 270 - marginE.top - marginE.bottom;
// Parse the date / time
var parseDateTimeE = d3.time.format("%Y-%m-%d%H:%M").parse;
// Set the ranges
var xE = d3.time.scale().range([0, widthE]);
var yE = d3.scale.linear().range([heightE, 0]);
// Define the axEs
var xAxisE = d3.svg.axis().scale(xE)
.orient("bottom").ticks(6);
var yAxisE = d3.svg.axis().scale(yE)
.orient("left").ticks(6);
var areaE = d3.svg.area()
.interpolate("bundle")
.x(function(e) { return xE(e.date); })
.y0(heightE)
.y1(function(e) { return yE(e.close); });
// Adds the svg canvas
var svgE = d3.select(".eur")
.append("svg")
.attr("width", widthE + marginE.left + marginE.right)
.attr("height", heightE + marginE.top + marginE.bottom)
.attr('id', 'charteur')
.attr('viewBox', '0 0 400 270')
.attr('perserveAspectRatio', 'xMinYMid')
.append("g")
.attr("transform",'translate(' + marginE.left + ',' + marginE.top + ')')
.attr('width', widthE)
.attr('height', heightE)
.style("font-size","12px");
// Get the data
d3.json("php/downl_EUR.php", function(error, data) {
data.forEach(function(E) {
E.date = parseDateTimeE(E.date +E.time);
E.close = +E.close;
E.MaP1 = +E.MaP1;
E.MaP2 = +E.MaP2;
E.MaPII = +E.MaPII; });
// Define the line
var valuelineE = d3.svg.line()
.interpolate("bundle")
.x(function(E) { return xE(E.date); })
.y(function(E) { return yE(E.close); });
var valuelineE2 = d3.svg.line()
.interpolate("bundle")
.x(function(E) { return xE(E.date); })
.y(function(E) { return yE(E.MaP1); });
var valuelineE3 = d3.svg.line()
.interpolate("bundle")
.x(function(E) { return xE(E.date); })
.y(function(E) { return yE(E.MaP2); });
var valuelineE4 = d3.svg.line()
.interpolate("bundle")
.x(function(E) { return xE(E.date); })
.y(function(E) { return yE(E.MaPII); });
// Scale the range of the data
xE.domain(d3.extent(data, function(E) { return E.date; }));
yE.domain(d3.extent(data, function(E) { return E.close;})); //****
//yE.domain([0,d3.max(data, function(E) {return Math.max(E.close, E.MapII);})]); ****
svgE.append("path")
.datum(data)
.attr("class", "area")
.attr("d", areaE);
// Add the valueline path.
svgE.append("path")
.attr("class", "lineE")
.style("stroke", "steelblue")
.attr("d", valuelineE(data));
svgE.append("path")
.attr("class", "lineE")
.style("stroke", "red")
.attr("d", valuelineE2(data));
svgE.append("path")
.attr("class", "lineE")
.style("stroke", "green")
.attr("d", valuelineE3(data));
svgE.append("path")
.attr("class", "lineE")
.style("stroke-dasharray", ("3, 3"))
.attr("d", valuelineE4(data));
// Add the X Axis
svgE.append("g")
.attr("class", "XaxisE")
.attr("transform", "translate(0," + heightE + ")")
.call(xAxisE);
// Add the Y Axis
svgE.append("g")
.attr("class", "YaxisE")
.call(yAxisE); });
I found the solution myself. Instead of MaP1, Map2 & MaPII, use map1, map2 and mapii -> no capital letters !! (also in the php-file)
Everything works fine now...

Change class of one element when hover over another element d3

I have a list of images and a list of image titles. I want to be able to show a hover state (change css) for the title when I mouse over its corresponding image, but I cannot figure out how to connect the two pieces of data. My code is below. I have it so that when you click on the top number the information appears beneath.
<!DOCTYPE html>
<html>
<head>
<script src="d3.v2.js"></script>
<title>Untitled</title>
</head>
<body>
<script type="text/javascript" >
function barStack(d) {
var l = d[0].length
while (l--) {
var posBase = 0, negBase = 0;
d.forEach(function(d) {
d=d[l]
d.size = Math.abs(d.y)
if (d.y<0) {
d.y0 = negBase
negBase-=d.size
} else
{
d.y0 = posBase = posBase + d.size
}
})
}
d.extent= d3.extent(d3.merge(d3.merge(d.map(function(e) { return e.map(function(f) { return [f.y0,f.y0-f.size]})}))))
return d
}
var ratiodata = [[{y:3.3}],[{y:-1.5}]]
var imageList = [
[3.3, 28, -1.5, 13, 857, 3, 4, 7, [{paintingfile:"676496.jpg", title:"Dessert1"}, {paintingfile:"676528.jpg", title: "Dessert2"}]
]]
var h=400
var w=1350
var margin=25
var color = d3.scale.category10()
var div = d3.select("body").append("div")
.attr("class", "imgtooltip")
.style("opacity", 0);
var x = d3.scale.ordinal()
.domain(['255'])
.rangeRoundBands([margin,w-margin], .1)
var y = d3.scale.linear()
.range([h-margin,0+margin])
var xAxis = d3.svg.axis().scale(x).orient("bottom").tickSize(6, 0)
var yAxis = d3.svg.axis().scale(y).orient("left")
barStack(ratiodata)
y.domain(ratiodata.extent)
var svg = d3.select("body")
.append("svg")
.attr("height",h)
.attr("width",w)
svg.selectAll(".series")
.data(ratiodata)
.enter()
.append("g")
.classed("series",true)
.style("fill","orange")
.selectAll("rect").data(Object)
.enter()
.append("rect")
.attr("x",function(d,i) { return x(x.domain()[i])})
.attr("y",function(d) { return y(d.y0)})
.attr("height",function(d) { return y(0)-y(d.size)})
.attr("width",x.rangeBand());
svg.selectAll("text")
.data(imageList)
.enter()
.append("text")
.text(function(d) {
return d[0];
})
.attr("x", function(d, i) {
return x(x.domain()[i]) + x.rangeBand() / 2;
})
.attr("y", function(d) {
return h - (32.1100917431*d[0] +150);
})
.attr("font-size", "16px")
.attr("fill", "#000")
.attr("text-anchor", "middle")
//.on("click", function(d) {console.log(d[1]);})
.on("click", function(d) {
//Update the tooltip position and value
d3.selectAll("ul")
.remove();
d3.selectAll("li")
.remove();
d3.select("#PaintingDetails")
.append("ul")
.selectAll("li")
.data(d[8])
.enter()
.append("li")
.text(function(d){
return (d.title);
});
d3.select("#imageBox")
.append("ul")
.selectAll("li")
.data(d[8])
.enter()
.append("li")
.classed("Myimageslist",true)
.append("img")
.classed("Myimages",true)
.attr("src", function(d){
return ("http://images.tastespotting.com/thumbnails/" + d.paintingfile);
})
.attr("align", "top");
d3.select(".Myimages")
.on("mouseover", function(){
d3.select("#PaintingDetails")
.selectAll("li")
.classed("selected", true)
});
});
svg.append("g").attr("class","axis x").attr("transform","translate (0 "+y(0)+")").call(xAxis);
// svg.append("g").attr("class","axis y").attr("transform","translate ("+x(margin)+" 0)").call(yAxis);
</script>
<div id="PaintingDetails"></div>
<div id="imageBox"></div>
</body>
</html>
The quick and dirty solution would be to simply use the index of the data element to figure out which title matches which image:
d3.selectAll(".Myimages")
.on("mouseover", function(d, i) {
d3.select("#PaintingDetails")
.selectAll("li")
.classed("selected", function(e, j) { return j == i; })
});

Resources