123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787 |
- Shiny.addCustomMessageHandler("treemap_values", function (message) {
- var data = message[0];
- var data1 = message[1];
- var data2 = message[2];
- var scopes = ["pais", "regiao", "uf", "mesorregiao", "microrregiao", "municipio"];
- var nextScope = "regiao";
- //Parallel Coordinates code
- var traits = ["localidade", "cnae_secao", "ds_natureza_lesao", "cbo_grande_grupo",
- "agrupamento_parte_do_corpo", "ds_grupo_agcausadores",
- "ds_tipo_acidente", "ds_tipo_local_acidente",
- "ds_emitente_cat", "idade", "obito", "sexo", "turno"];
- // We have to specify which of the axis are categorical, instead of numerical
- var categoricalAxis = ["localidade", "ds_grupo_agcausadores", "cnae_secao",
- "ds_emitente_cat", "ds_natureza_lesao" ,"cbo_grande_grupo"
- ,"agrupamento_parte_do_corpo", "ds_tipo_acidente",
- "ds_tipo_local_acidente"];
- function toggleAxis(checkBox, trait, data, div_name) {
- if (checkBox.checked == true) {
- if (!traits.includes(trait))
- traits.push(trait);
- }
- if (checkBox.checked == false) {
- var i = traits.indexOf(trait);
- traits.splice(i, 1);
- }
- d3.select(div_name + " svg").remove();
- drawParallelCoords(data, div_name);
- }
- var checkboxes = d3.select("#parallelcoordinates_area")
- .append("div")
- .attr("id", "parallelcoordinates_switch");
- function reloadCheckBoxes(data, checkboxes, div_name) {
- traits.forEach(function (trait) {
- checkboxes.append("input")
- .attr("type", "checkbox")
- .attr("id", trait)
- .attr("value", trait)
- .attr("checked", true)
- .on("click", function () {
- toggleAxis(this, trait, data, div_name);
- });
- checkboxes.append("text")
- .text(trait);
- });
- }
- function drawParallelCoords(arrayData, div_name) {
- dragging = {};
- var background;
- var m = {top: 30, right: 15, bottom: 10, left:150},
- w = window.innerWidth *0.95 - m.left - m.right,
- h = window.innerHeight * 0.8 - m.top - m.bottom;
- var line = d3.line(),
- axis = d3.axisLeft(),
- foreground;
- var parcoords = d3.select(div_name).append("svg")
- .attr("width", w + m.left + m.right)
- .attr("height", h + m.top + m.bottom)
- .append("g")
- .attr("transform", "translate(" + m.left + "," + m.top + ")");
- // Create a scale and brush for each trait
- var x = d3.scalePoint().domain(traits).range([0, w]),
- y = {};
- traits.forEach(function (col) {
- var data = [];
- if (categoricalAxis.includes(col)) {
- arrayData.forEach(function (row) {
- if (!arrayData.includes(row[col])) {
- data.push(row[col]);
- }
- });
- y[col] = d3.scalePoint()
- .domain(data)
- .range([h, 0]);
- } else {
- arrayData.forEach(function (p) {
- p[col] = +p[col];
- });
- if (col == "sexo" || col == "obito" || col == "turno") {
- y[col] = d3.scaleLinear()
- .domain(
- [0, 1]
- )
- .range([h, 0]);
- } else if (col == "idade") { //TODO remove these magic numbers
- y[col] = d3.scaleLinear()
- .domain(
- [19, 67]
- )
- .range([h, 0]);
- } else {
- y[col] = d3.scaleLinear()
- .domain(d3.extent(arrayData, function (p) {
- return p[col];
- }))
- .range([h, 0]);
- }
- }
- //Create Brush
- y[col].brush = d3.brushY()
- .extent([
- [-7, y[col].range()[1]],
- [7, y[col].range()[0]]
- ])
- .on("start", brushstart)
- .on("brush", brushView)
- .on("end", brush);
- });
- //Append Background
- background = parcoords.append("g")
- .attr("class", "background")
- .selectAll("path")
- .data(arrayData)
- .enter().append("path")
- .attr("d", path);
- //Add Foreground Lines
- foreground = parcoords.append("g")
- .attr("class", "foreground")
- .selectAll("path")
- .data(arrayData)
- .enter().append("path")
- .attr("d", path);
- /*.style("stroke", function (d) {
- return colorMake(toColor.indexOf(d[nextScope]));
- });*/
- // Add a group element for each trait.
- var g = parcoords.selectAll(".trait")
- .data(traits)
- .enter()
- .append("svg:g")
- .attr("class", "trait")
- .attr("transform", function (d) {
- return "translate(" + x(d) + ")";
- })
- .call(d3.drag()
- .subject(function (d) {
- return {
- x: x(d)
- };
- })
- .on("start", function (d) {
- dragging[d] = x(d);
- background.attr("visibility", "hidden");
- })
- .on("drag", function (d) {
- //+10 e -10 para mudar com o primeiro e o ultimo
- dragging[d] = Math.min(w + 10, Math.max(-10, d3.event.x));
- foreground.attr("d", path);
- traits.sort(function (a, b) {
- return position(a) - position(b);
- });
- x.domain(traits);
- g.attr("transform", function (d) {
- return "translate(" + position(d) + ")";
- });
- })
- .on("end", function (d) {
- delete dragging[d];
- transition(d3.select(this)).attr("transform", "translate(" + x(d) + ")");
- transition(foreground).attr("d", path);
- background
- .attr("d", path)
- .transition()
- .delay(500)
- .duration(0)
- .attr("visibility", null);
- })
- );
- //Gradiente do eixo Sexo
- var defs = parcoords.append("defs");
- var gradient = defs.append("linearGradient")
- .attr("id", "svgGradient")
- .attr("x1", "50%")
- .attr("x2", "100%")
- .attr("y1", "50%")
- .attr("y2", "100%");
- gradient.append("stop")
- .attr('class', 'start')
- .attr("offset", "0%")
- .attr("stop-color", "blue")
- .attr("stop-opacity", 1);
- gradient.append("stop")
- .attr('class', 'end')
- .attr("offset", "100%")
- .attr("stop-color", "red")
- .attr("stop-opacity", 1);
- //Axis
- g.append("svg:g")
- .attr("class", "axis")
- .each(function (col) {
- if (col == "sexo") {
- d3.select(this)
- .attr("class", "eixoSexo")
- .call(d3.axisLeft(y[col]))
- .selectAll("text").remove();
- d3.select(this)
- .call(d3.axisLeft(y[col])
- .ticks(3));
- d3.select(this)
- .append("svg:text").text("M")
- .attr("x", -9)
- .attr("y", 10);
- d3.select(this)
- .append("svg:text").text("F")
- .attr("x", -9)
- .attr("y", h + 2);
- // Text category reduction
- } else if (col == "cnae_secao" || col == "ds_natureza_lesao" ||
- col == "cbo_grande_grupo" || col == "agrupamento_parte_do_corpo" ||
- col == "ds_grupo_agcausadores") {
- // ALT
- d3.select(this).call(d3.axisLeft(y[col])).selectAll("text")._groups[0].forEach(function (p) {
- p.innerHTML = p.innerHTML.slice(0,20).toLowerCase();
- });
- } else {
- d3.select(this).call(d3.axisLeft(y[col]));
- }
- })
- // Axis Titles
- .append("svg:text")
- .attr("text-anchor", "middle")
- .attr("y", -15)
- .text(function (col) {
- return col;
- });
- // Add a brush for each axis.
- g.append("svg:g")
- .attr("class", "brush")
- .each(function (d) {
- d3.select(this).call(y[d].brush);
- })
- .selectAll("rect")
- .attr("x", -8)
- .attr("width", 16);
- function position(d) {
- var v = dragging[d];
- return v == null ? x(d) : v;
- }
- function transition(g) {
- return g.transition().duration(500);
- }
- // Returns the path for a given data point.
- function path(d) {
- return line(traits.map(function (p) {
- return [position(p), y[p](d[p])];
- }));
- }
- // BRUSH FUNCTIONS
- function brushstart() {
- d3.event.sourceEvent.stopPropagation();
- }
- function brushView() {
- var actives = [];
- //filter brushed extents
- parcoords.selectAll(".brush")
- .filter(function (d) {
- return d3.brushSelection(this);
- })
- .each(function (d) {
- actives.push({
- dimension: d,
- extent: d3.brushSelection(this)
- });
- dim = actives[0].dimension;
- });
- //set un-brushed foreground line disappear
- foreground.classed("fade", function (d, i) {
- return !actives.every(function (active) {
- var dim = active.dimension;
- return active.extent[0] <= y[dim](d[dim]) && y[dim](d[dim]) <= active.extent[
- 1];
- });
- });
- }
- function brush() {
- var actives = [];
- //filter brushed extents
- parcoords.selectAll(".brush")
- .filter(function (d) {
- return d3.brushSelection(this);
- })
- .each(function (d) {
- actives.push({
- dimension: d,
- extent: d3.brushSelection(this)
- });
- var selected = arrayData.filter(function (d) {
- return actives.every(function (active) {
- var dim = active.dimension;
- return active.extent[0] <= y[dim](d[dim]) && y[dim](d[dim]) <= active.extent[1];
- });
- });
- });
- foreground.classed("fade", function (d, i) {
- return !actives.every(function (active) {
- var dim = active.dimension;
- return active.extent[0] <= y[dim](d[dim]) && y[dim](d[dim]) <= active.extent[1];
- });
- });
- }
- }
- var checkboxescities = d3.select("#parallelcoordinates_area_cities")
- .append("div")
- .attr("id", "parallelcoordinates_switch_cities");
- // TRANSPOSE DATA THAT COMES FROM R
- // true means to use municipio
- function transposeData(d, flag) {
- var values = Object.keys(d).slice(1);
- index = values.findIndex(x => x ==="cnae_secao");
- var len = d.idade.length; //We really only want to know how many lines there is in the file
- var datainsert = [];
- var dataTransposed = [];
- var i, j;
- for (i = 0; i < len; i++) {
- if(flag) {
- datainsert["localidade"] = d[values[index-1]][i];
- } else {
- datainsert["localidade"] = d[nextScope][i];
- }
- values.forEach(function (v) {
- datainsert[v] = d[v][i];
- });
- dataTransposed.push(datainsert);
- datainsert = [];
- }
- return dataTransposed;
- }
- /*var colorMake = color = d3.scaleOrdinal().range(d3.schemeCategory10);
- var toColorDup = data1[nextScope];
- toColor = toColorDup.filter(function (elem, index, self) {
- return index === self.indexOf(elem);
- });*/
- var colors_subtitle = [];
- /*for (var i = 0; i < toColor.length; i++) {
- colors_subtitle.push({
- name: toColor[i],
- color: colorMake(i)
- });
- }*/
- //Bottom graph
- dataTranspose = transposeData(data1, false);
- reloadCheckBoxes(dataTranspose, checkboxescities, "#parallelcoordinates_area_cities");
- drawParallelCoords(dataTranspose, "#parallelcoordinates_area_cities");
- //Top graph
- dataTranspose2 = transposeData(data2, false);
- reloadCheckBoxes(dataTranspose2, checkboxes, "#parallelcoordinates_area");
- drawParallelCoords(dataTranspose2, "#parallelcoordinates_area");
- var s1 = d3.select("#parallel_coordinates_subtitle").selectAll('div')
- .data(colors_subtitle)
- .enter()
- .append("div")
- .append("text");
- s1Attr = s1.text(function (d) {
- return d.name;
- })
- .style("color", function (d) {
- return d.color;
- })
- .style("font-weight", "bold");
- //Treemap code
- var margin = {
- top: 25,
- right: 0,
- bottom: 0,
- left: 0
- },
- width = window.innerWidth * 0.95,
- height = window.innerHeight * 0.6,
- formatNumber = d3.format(",d"),
- transitioning,
- hovering;
- var tooltip = d3.select("body")
- .append("div")
- .style("position", "absolute")
- .style("z-index", "10")
- .style("visibility", "hidden")
- .style("color", "white")
- .style("padding", "8px")
- .style("background-color", "rgba(0, 0, 0, 0.75)")
- .style("border-radius", "6px")
- .style("font", "12px sans-serif")
- .text("tooltip");
- var x = d3.scaleLinear()
- .domain([0, width])
- .range([0, width]);
- var y = d3.scaleLinear()
- .domain([0, height - margin.top - margin.bottom])
- .range([0, height - 3 * margin.top - margin.bottom]);
- var c = [];
- function q(d) {
- for (var i = 0; i < d.children.length; i++) {
- c[i] = d.children[i].value;
- }
- return c.sort(function (a, b) {
- return (a - b);
- });
- }
- q(data);
- var maxValue = c[c.length - 1];
- var minValue = maxValue / 9;
- var color = d3.scaleThreshold()
- .domain([minValue, minValue * 2, minValue * 3, minValue * 4, minValue * 5, minValue * 6, minValue * 7, minValue * 8])
- .range(d3.schemeBlues[9]);
- var format = d3.format(",d");
- var createTreemap;
- var treemap, grandparent;
- updateDrillDown();
- function updateDrillDown() {
- if (treemap) {
- treemap.selectAll("*").remove();
- } else {
- treemap = d3.select("#treemap2_area").append("svg")
- .attr("width", width + margin.left + margin.right)
- .attr("height", height + margin.bottom + margin.top)
- //.style("margin-left", -margin.left + "px")
- //.style("margin.right", -margin.right + "px")
- .append("g")
- .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
- .style("shape-rendering", "crispEdges");
- grandparent = treemap.append("g")
- .attr("class", "grandparent");
- grandparent.append("rect")
- .style("fill", "#ADEAEA")
- .style("padding", "1px")
- .attr("y", -margin.top)
- .attr("width", width)
- .attr("height", margin.top);
- grandparent.append("text")
- .attr("x", 6)
- .attr("y", 6 - margin.top)
- .attr("dy", ".75em");
- createTreemap = d3.treemap()
- .tile(d3.treemapBinary)
- .size([width, height - 10])
- .round(false)
- .paddingInner(0);
- }
- var root = d3.hierarchy(data)
- .eachBefore(function (d) {
- d.id = (d.parent ? d.parent.id + "." : "") + d.data.name;
- })
- .sum(function (d) {
- return d.value;
- })
- .sort(function (a, b) {
- return b.height - a.height || b.value - a.value;
- });
- initialize(root);
- accumulate(root);
- layout(root);
- createTreemap(root);
- display(root);
- };
- function initialize(root) {
- root.x = root.y = 0;
- root.x1 = width;
- root.y1 = height;
- root.depth = 0;
- }
- function accumulate(d) {
- return (d._children = d.children) ?
- d.value = d.children.reduce(function (p, v) {
- return p + accumulate(v);
- }, 0) : d.value;
- }
- function layout(d) {
- if (d._children) {
- d._children.forEach(function (c) {
- c.x0 = d.x0 + c.x0 * d.x1;
- c.y0 = d.y0 + c.y0 * d.y1;
- c.x1 *= (d.x1 - d.x0);
- c.y1 *= (d.y1 - d.y0);
- c.parent = d;
- layout(c);
- });
- }
- }
- function display(d) {
- grandparent
- .datum(d.parent)
- .on("click", transition)
- .select("text")
- .text(name(d));
- var g1 = treemap.insert("g", ".grandparent")
- .datum(d)
- .attr("class", "depth");
- var g = g1.selectAll("g")
- .data(d._children)
- .enter().append("g").style("opacity", 1);
- g.filter(function (d) {
- return d._children;
- })
- .classed("children", true)
- .on("click", transition);
- var children = g.selectAll(".child")
- .data(function (d) {
- return d._children || [d];
- })
- .enter().append("g") //SHOW CHILDREN FROM TREEMAP VIEW
- .style("opacity", 0.7); // DEFINES THE OPACITY OF THE INTERNAL NODES
- children.append("rect")
- .attr("class", "child")
- .call(rect)
- .append("title")
- .text(function (d) {
- return d.data.name + " (" + formatNumber(d.data.value) + ")";
- });
- children.append("text")
- .attr("class", "ctext").style("font-size", "14px")
- .text(function (d) {
- return d.data.name;
- })
- .call(text2);
- g.append("rect")
- .attr("class", "parent")
- .call(rect);
- //MOUSEOVER: SHOW CHILDREN OF THE NODES
- g.selectAll("rect").classed("parent", true).on("mouseover", function (d) {
- d3.select(this).style("opacity", 0.3); //.
- tooltip.html(d.data.name + "<br/>" + formatNumber(d.data.value));
- tooltip.transition();
- return tooltip.style("visibility", "visible").style("opacity", 1);
- //children.select("g").style("opacity", 1);
- });
- //MOUSEOUT: HIDE CHILDREN OF THE NODES
- g.selectAll("rect").classed("parent", false).on("mouseout", function () {
- d3.select(this).style("opacity", 1);
- return tooltip.style("visibility", "hidden");
- });
- g.selectAll("rect").classed("parent", false).on("mousemove", function () {
- d3.select(this).style("opacity", 0.3);
- tooltip.style("opacity", 1);
- return tooltip.style("top", (d3.event.pageY - 10) + "px").style("left", (d3.event.pageX + 10) + "px");
- });
- var t = g.append("text")
- .attr("class", "ptext").style("font-weight", "bold")
- .attr("dy", ".75em");
- t.append("tspan")
- .attr("font-weight", "bold")
- .text(function (d) {
- return d.data.name;
- });
- t.append("tspan")
- .attr("dy", "1.0em")
- .text(function (d) {
- return formatNumber(d.data.value);
- });
- t.call(text);
- g.selectAll("rect")
- .style("fill", function (d) {
- return color(d.data.value);
- });
- function transition(d) {
- // Handle Parcoords data
- Shiny.onInputChange("scope", scopes[d.depth]);
- Shiny.onInputChange("name", d.data.name);
- Shiny.addCustomMessageHandler("treemap2_values_change", function (message) {
- dataset1 = message[0];
- dataset2 = message[1];
- if (d.data.children[0]) {
- nextScope = scopes[d.depth +1];
- /*var toColorDup = dataset1[nextScope];
- toColor = toColorDup.filter(function (elem, index, self) {
- return index === self.indexOf(elem);
- });*/
- colors_subtitle = [];
- /*for (var i = 0; i < toColor.length; i++) {
- colors_subtitle.push({
- name: toColor[i],
- color: colorMake(i)
- });
- }*/
- d3.select("#parallel_coordinates_subtitle").selectAll('div').remove();
- s1 = d3.select("#parallel_coordinates_subtitle").selectAll('div')
- .data(colors_subtitle)
- .enter()
- .append("div")
- .append("text");
- s1Attr = s1.text(function (d) {
- return d.name;
- })
- .style("color", function (d) {
- return d.color;
- })
- .style("font-weight", "bold");
- } else {
- nextScope = "municipio";
- }
- dataset1 = transposeData(dataset1, false);
- //dataset2 = transposeData(dataset2);
- d3.select("#parallelcoordinates_switch_cities").selectAll("*").remove();
- reloadCheckBoxes(dataset1, checkboxescities, "#parallelcoordinates_area_cities");
- d3.select("#parallelcoordinates_area_cities svg").remove();
- drawParallelCoords(dataset1, "#parallelcoordinates_area_cities");
- dataset2 = transposeData(dataset2, false);
- d3.select("#parallelcoordinates_switch").selectAll("*").remove();
- reloadCheckBoxes(dataset2, checkboxes, "#parallelcoordinates_area");
- d3.select("#parallelcoordinates_area svg").remove();
- drawParallelCoords(dataset2, "#parallelcoordinates_area");
- });
- if (transitioning || !d) return;
- if (transitioning || !d) return;
- transitioning = true;
- var g2 = display(d),
- t1 = g1.transition().duration(750),
- t2 = g2.transition().duration(750);
- // Update the domain only after entering new elements.
- x.domain([d.x0, d.x0 + (d.x1 - d.x0)]);
- y.domain([d.y0, d.y0 + (d.y1 - d.y0)]);
- // Enable anti-aliasing during the transition.
- treemap.style("shape-rendering", null);
- // Draw child nodes on top of parent nodes.
- //treemap.selectAll(".depth").sort(function(a, b) {
- //console.log('.depth sort a ' + a.depth + ' b ' + b.depth);
- //return a.depth - b.depth; });
- // Fade-in entering text.
- g2.selectAll("text").style("fill-opacity", 0);
- // Transition to the new view.
- t1.selectAll(".ptext").call(text).style("fill-opacity", 0).style("font-weight", "bold"); //.style("font-size", "12px");
- t2.selectAll(".ptext").call(text).style("fill-opacity", 1).style("font-weight", "bold"); //.style("font-size", "12px");
- t1.selectAll(".ctext").call(text2).style("fill-opacity", 0);
- t2.selectAll(".ctext").call(text2).style("fill-opacity", 1);
- t1.selectAll("rect").call(rect);
- t2.selectAll("rect").call(rect);
- // Remove the old node when the transition is finished.
- t1.remove().on("end", function () {
- treemap.style("shape-rendering", "crispEdges");
- transitioning = false;
- });
- }
- return g;
- }
- function make_title(d) {
- return d ? d.data.name + " (" + formatNumber(d.data.value) + ")" : d.data.name + " (" + formatNumber(d.data.value) + ")";
- }
- function text(text) {
- text.selectAll("tspan")
- .attr("x", function (d) {
- return x(d.x0) + 5;
- });
- text.attr("x", function (d) {
- return x(d.x0) + 5;
- })
- .attr("y", function (d) {
- return y(d.y0) + 3;
- })
- .style("opacity", function (d) {
- var w = x(d.x1) - x(d.x0);
- return this.getComputedTextLength() <= w ? 1 : 0;
- })
- .style("font-size", "10px");
- }
- function text2(text) {
- text
- .attr("x", function (d) {
- return x(d.x1) - this.getComputedTextLength() - 2;
- })
- .attr("y", function (d) {
- return y(d.y1) - 2;
- })
- .style("opacity", function (d) {
- var w = x(d.x1) - x(d.x0);
- return this.getComputedTextLength() <= w ? 1 : 0;
- })
- .style("font-size", "14px");
- }
- function rect(rect) {
- rect.attr("x", function (d) {
- return x(d.x0);
- })
- .attr("y", function (d) {
- return y(d.y0);
- })
- .attr("width", function (d) {
- var w = x(d.x1) - x(d.x0) - 1;
- return w;
- })
- .attr("height", function (d) {
- var h = y(d.y1) - y(d.y0);
- return h;
- })
- .style("stroke", "darkblue")
- .style("stroke-width", 1);
- }
- function name(d) {
- return d.parent ? name(d.parent) + " -> " + d.data.name + " (" + formatNumber(d.data.value) + ")" : d.data.name + " (" + formatNumber(d.data.value) + ")";
- }
- });
|