Related
I created this bars with a tooltip. I need to get them update after the $('.quarter-increase, .quarter-decrease').on('click', function() {
I don't get any errors but nothing gets updated...
$(document).ready(function() {
$('#prof-rendi').click(function() {
$('.graph-loading').show();
$('#svg-quarter').empty();
var tooltip = tooltipd3();
var svg = d3.select("svg#svg-quarter"),
margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
var g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var div = d3.select("#svg-quarter").append("div"). // declare the tooltip div
attr("class", "tooltip"). // apply the 'tooltip' class
style("opacity", 0);
d3.csv(base_url() + 'graph/getStatementsQuarterly/', function(d) {
$('.graph-loading').hide();
d.guadagno = +d.guadagno;
return d;
}, function(error, data) {
if (error)
throw error;
x.domain(data.map(function(d) {
return d.periodo;
}));
y.domain([
0,
d3.max(data, function(d) {
return d.guadagno;
})
]);
g.append("g").attr("class", "axis axis--x").attr("transform", "translate(0," + height + ")").call(d3.axisBottom(x));
g.append("g").attr("class", "axis axis--y").call(d3.axisLeft(y).ticks(10)).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", "0.71em").attr("text-anchor", "end").text("Guadagno")
g.selectAll(".bar").data(data).enter().append("rect").attr("class", "bar").attr("x", function(d) {
return x(d.periodo);
}).attr("y", function(d) {
return y(d.guadagno);
}).attr("width", x.bandwidth()).attr("height", function(d) {
return height - y(d.guadagno);
}).on('mouseover', function(d) {
var html = '<h5>' + d.guadagno + ' €</h5>';
tooltip.mouseover(html); // pass html content
}).on('mousemove', tooltip.mousemove).on('mouseout', tooltip.mouseout);
});
});
$('.quarter-increase, .quarter-decrease').on('click', function() {
$('.rendi-btn.left, .rendi-btn.right').attr('disabled', 'disabled');
var where_at = $('#scroll-statement-quarter').val();
$('.graph-loading').show();
$('#svg-quarter').css({'opacity': 0.4});
var tooltip = tooltipd3();
var svg = d3.select("svg#svg-quarter"),
margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
var g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var div = d3.select("#svg-quarter").append("div"). // declare the tooltip div
attr("class", "tooltip"). // apply the 'tooltip' class
style("opacity", 0);
var speed = 500;
d3.csv(base_url() + 'graph/getStatementsQuarterly/' + where_at, function(d) {
$('.graph-loading').hide();
d.guadagno = +d.guadagno;
return d;
}, function(error, data) {
if (error)
throw error;
x.domain(data.map(function(d) {
return d.periodo;
}));
y.domain([
0,
d3.max(data, function(d) {
return d.guadagno;
})
]);
g.append("g").attr("class", "axis axis--x").attr("transform", "translate(0," + height + ")").call(d3.axisBottom(x));
g.append("g").attr("class", "axis axis--y").call(d3.axisLeft(y).ticks(10)).append("text").attr("transform", "rotate(-90)").attr("y", 6).attr("dy", "0.71em").attr("text-anchor", "end").text("Guadagno")
g.selectAll(".bar").data(data).transition().duration(speed).attr("class", "bar").attr("x", function(d) {
return x(d.periodo);
}).attr("y", function(d) {
return y(d.guadagno);
}).attr("width", x.bandwidth()).attr("height", function(d) {
return height - y(d.guadagno);
}).on('mouseover', function(d) {
var html = '<h5>' + d.guadagno + ' €</h5>';
tooltip.mouseover(html); // pass html content
}).on('mousemove', tooltip.mousemove).on('mouseout', tooltip.mouseout);
});
})
});
This is a Plunker to test this:
https://plnkr.co/edit/72GCWqkllMFXZI6mecQE?p=preview
Press "show", then change the year to 2016 and you will see the result.
Your g variable inside the click event handler is a newly appended <group> element.
Therefore, this...
g.selectAll(".bar").data(data).etc...
... won't work, because there is nothing with a class .bar inside that group.
Solution: use the svg variable to select the rectangles:
svg.selectAll(".bar").data(data).etc...
Here is the updated plunker: https://plnkr.co/edit/eNa6Af0WcyrcLejadO2q?p=preview
PS: this code has several problems. I strongly advise you to not mix jQuery and D3, and also to not use d3.csv inside an event handler.
I'm having difficulty to plot the horizontal grid according the y-axis tick values. I'm able to plot the grid on y-axis but it's not coming according the Y-axis co-ordinates.
Bar chart
Here is my fiddle
var data = [["Since Mar 10, 2015",150], ["1 year",-17.1], ["3 year",6.9],["Since Mar 10, 2010",100]];
d3.select("#example")
.datum(data)
.call(columnChart()
.width(320)
.height(240)
.x(function(d, i) { return d[0]; })
.y(function(d, i) { return d[1]; }));
function columnChart() {
var margin = {top: 30, right: 10, bottom: 50, left: 50},
width = 20,
height = 20,
xRoundBands = 0.6,
xValue = function(d) { return d[0]; },
yValue = function(d) { return d[1]; },
xScale = d3.scale.ordinal(),
yScale = d3.scale.linear(),
yAxis = d3.svg.axis().scale(yScale).orient("left"),
xAxis = d3.svg.axis().scale(xScale);
var isNegative = false;
function chart(selection) {
selection.each(function(data) {
// Convert data to standard representation greedily;
// this is needed for nondeterministic accessors.
for(var i=0; i< data.length; i++){
if(data[i][1] < 0){
isNegative = true;
}
}
data = data.map(function(d, i) {
return [xValue.call(data, d, i), yValue.call(data, d, i)];
});
// Update the x-scale.
xScale
.domain(data.map(function(d) { return d[0];} ))
.rangeRoundBands([0, width - margin.left - margin.right], xRoundBands);
// Update the y-scale.
yScale
.domain(d3.extent(data.map(function(d) { return d[1];} )))
.range([height - margin.top - margin.bottom, 0])
.nice();
// Select the svg element, if it exists.
var svg = d3.select(this).selectAll("svg").data([data]);
// Otherwise, create the skeletal chart.
var gEnter = svg.enter().append("svg").append("g");
gEnter.append("g").attr("class", "bars");
gEnter.append("g").attr("class", "y axis");
gEnter.append("g").attr("class", "x axis");
gEnter.append("g").attr("class", "x axis zero");
// Update the outer dimensions.
svg .attr("width", width)
.attr("height", height);
// Update the inner dimensions.
var g = svg.select("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Update the bars.
var bar = svg.select(".bars").selectAll(".bar").data(data);
bar.enter().append("rect");
bar.exit().remove();
bar .attr("class", function(d, i) { return d[1] < 0 ? "bar negative" : "bar positive"; })
.attr("x", function(d) { return X(d); })
.attr("y", function(d, i) { return d[1] < 0 ? Y0() : Y(d); })
.attr("width", xScale.rangeBand())
.attr("height", function(d, i) { return Math.abs( Y(d) - Y0() ); });
// x axis at the bottom of the chart
if( isNegative === true ){
var xScaleHeight = height - margin.top - margin.bottom+12;
}else{
var xScaleHeight = height - margin.top - margin.bottom;
}
g.select(".x.axis")
.attr("transform", "translate(0," + ( xScaleHeight ) + ")")
.call(xAxis.orient("bottom"))
.selectAll("text")
.call(wrap, xScale.rangeBand());
// zero line
g.select(".x.axis.zero")
.attr("transform", "translate(0," + Y0() + ")")
.attr("class", "zero axis")
.call(xAxis.tickFormat("").tickSize(0));
// Update the text in bars.
var bar1 = svg.select(".bars").selectAll("text").data(data);
bar1 .data(data)
.enter()
.append("text")
.attr("class", "text")
.text(function(d) { return d[1]+"%"; })
.attr("x", function(d) { return X(d); })
.attr("y", function(d, i) { return d[1] < 0 ? Math.abs(Y(d)+10) : Y(d)-2; });
// Update the y-axis.
g.select(".y.axis")
//.call(yAxis)
.call(yAxis.tickSize(3).ticks(5))
.selectAll("g")
.selectAll("text")
.text(function(d){
return d+"%";
});
// Horizontal grid
g.insert("g", ".bars")
.attr("class", "grid horizontal")
.call(d3.svg.axis().scale(yScale)
.orient("left")
.tickSize(-(height), 0, 0)
.tickFormat("")
);
});
}
// Custom function for text wrap
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > 55) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
// The x-accessor for the path generator; xScale ∘ xValue.
function X(d) {
return xScale(d[0]);
}
function Y0() {
return yScale(0);
}
// The x-accessor for the path generator; yScale ∘ yValue.
function Y(d) {
return yScale(d[1]);
}
chart.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.x = function(_) {
if (!arguments.length) return xValue;
xValue = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return yValue;
yValue = _;
return chart;
};
return chart;
}
You can do something like this
Instead of your code to generate horizontal grid
// Horizontal grid
g.insert("g", ".bars")
.attr("class", "grid horizontal")
.call(d3.svg.axis().scale(yScale)
.orient("left")
.tickSize(-(height), 0, 0)
.tickFormat("")
);
});
Add this it will iterate through the ticks .data(yScale.ticks(5))
g.append("g").selectAll("line.line").data(yScale.ticks(5)).enter()
.append("line")
.attr(
{
"class":"line grid tick",
"x1" : margin.right,
"x2" : width,
"y1" : function(d){ return yScale(d);},
"y2" : function(d){ return yScale(d);},
});
});
Working code here
I am newbie to d3.js , I am working on a minimap for collapsible tree .
There is always a one click lag in collapsible tree minimap. When user clicks the first node followed by second node , minimap shows the image of first node when user clicks second node.
Could someone please help me with this ?
d3.demo = {};
/** CANVAS **/
d3.demo.canvas = function(width,height) {
"use strict";
var width = 500,
height = 500,
zoomEnabled = true,
dragEnabled = true,
scale = 1,
translation = [0,0],
base = null,
wrapperBorder = 2,
minimap = null,
minimapPadding = 20,
minimapScale = 0.25;
function canvas(selection) {
base = selection;
var xScale = d3.scale.linear()
.domain([-width / 2, width / 2])
.range([0, width]);
var yScale = d3.scale.linear()
.domain([-height / 2, height / 2])
.range([height, 0]);
var zoomHandler = function(newScale) {
if (!zoomEnabled) { return; }
if (d3.event) {
scale = d3.event.scale;
} else {
scale = newScale;
}
if (dragEnabled) {
var tbound = -height * scale,
bbound = height * scale,
lbound = -width * scale,
rbound = width * scale;
// limit translation to thresholds
translation = d3.event ? d3.event.translate : [0, 0];
translation = [
Math.max(Math.min(translation[0], rbound), lbound),
Math.max(Math.min(translation[1], bbound), tbound)
];
}
d3.select(".panCanvas, .panCanvas .bg")
.attr("transform", "translate(" + translation + ")" + " scale(" + scale + ")");
minimap.scale(scale).render();
}; // startoff zoomed in a bit to show pan/zoom rectangle
var zoom = d3.behavior.zoom()
.x(xScale)
.y(yScale)
.scaleExtent([0.5, 5])
.on("zoom.canvas", zoomHandler);
var svg = selection.append("svg")
.attr("class", "svg canvas")
.attr("width", width + (wrapperBorder*2) + minimapPadding*2 + (width*minimapScale))
.attr("height", height + (wrapperBorder*2) + minimapPadding*2)
.attr("shape-rendering", "auto");
var svgDefs = svg.append("defs");
svgDefs.append("clipPath")
.attr("id", "wrapperClipPath")
.attr("class", "wrapper clipPath")
.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height);
svgDefs.append("clipPath")
.attr("id", "minimapClipPath")
.attr("class", "minimap clipPath")
.attr("width", width)
.attr("height", height)
//.attr("transform", "translate(" + (width + minimapPadding) + "," + (minimapPadding/2) + ")")
.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height);
var filter = svgDefs.append("svg:filter")
.attr("id", "minimapDropShadow")
.attr("x", "-20%")
.attr("y", "-20%")
.attr("width", "150%")
.attr("height", "150%");
filter.append("svg:feOffset")
.attr("result", "offOut")
.attr("in", "SourceGraphic")
.attr("dx", "1")
.attr("dy", "1");
filter.append("svg:feColorMatrix")
.attr("result", "matrixOut")
.attr("in", "offOut")
.attr("type", "matrix")
.attr("values", "0.1 0 0 0 0 0 0.1 0 0 0 0 0 0.1 0 0 0 0 0 0.5 0");
filter.append("svg:feGaussianBlur")
.attr("result", "blurOut")
.attr("in", "matrixOut")
.attr("stdDeviation", "10");
filter.append("svg:feBlend")
.attr("in", "SourceGraphic")
.attr("in2", "blurOut")
.attr("mode", "normal");
var minimapRadialFill = svgDefs.append("radialGradient")
.attr({
id:"minimapGradient",
gradientUnits:"userSpaceOnUse",
cx:"500",
cy:"500",
r:"400",
fx:"500",
fy:"500"
});
minimapRadialFill.append("stop")
.attr("offset", "0%")
.attr("stop-color", "#FFFFFF");
minimapRadialFill.append("stop")
.attr("offset", "40%")
.attr("stop-color", "#EEEEEE");
minimapRadialFill.append("stop")
.attr("offset", "100%")
.attr("stop-color", "#E0E0E0");
var outerWrapper = svg.append("g")
.attr("class", "wrapper outer")
.attr("transform", "translate(0, " + minimapPadding + ")");
outerWrapper.append("rect")
.attr("class", "background")
.attr("width", width + wrapperBorder*2)
.attr("height", height + wrapperBorder*2);
var innerWrapper = outerWrapper.append("g")
.attr("class", "wrapper inner")
.attr("clip-path", "url(#wrapperClipPath)")
.attr("transform", "translate(" + (wrapperBorder) + "," + (wrapperBorder) + ")")
.call(zoom);
innerWrapper.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height);
var panCanvas = innerWrapper.append("g")
.attr("class", "panCanvas")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(0,0)");
panCanvas.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height);
minimap = d3.demo.minimap()
.zoom(zoom)
.target(panCanvas)
.minimapScale(minimapScale)
.x(width + minimapPadding)
.y(minimapPadding);
svg.call(minimap);
// startoff zoomed in a bit to show pan/zoom rectangle
zoom.scale(1.75);
zoomHandler(1.75);
/** ADD SHAPE **/
canvas.addItem = function(item) {
panCanvas.node().appendChild(item.node());
minimap.render();
};
canvas.loadTree = function (divID,treeData,height,width) {
var totalNodes = 0;
var maxLabelLength = 0;
// Misc. variables
var i = 0;
var duration = 750;
var root,
rootNode;
// size of the diagram
var viewerWidth = width;
var viewerHeight = height;
var tree = d3.layout.tree()
.size([viewerHeight, viewerWidth]);
// define a d3 diagonal projection for use by the node paths later on.
var diagonal = d3.svg.diagonal()
.projection(function (d) {
return [d.y, d.x];
});
// A recursive helper function for performing some setup by walking through all nodes
function visit(parent, visitFn, childrenFn) {
if (!parent)
return;
visitFn(parent);
var children = childrenFn(parent);
if (children) {
var count = children.length;
for (var i = 0; i < count; i++) {
visit(children[i], visitFn, childrenFn);
}
}
}
// Call visit function to establish maxLabelLength
visit(treeData, function (d) {
totalNodes++;
maxLabelLength = Math.max(d.name.length, maxLabelLength);
}, function (d) {
return d.children && d.children.length > 0 ? d.children : null;
});
// sort the tree according to the node names
function sortTree() {
tree.sort(function (a, b) {
return b.name.toLowerCase() < a.name.toLowerCase() ? 1 : -1;
});
}
// Sort the tree initially incase the JSON isn't in a sorted order.
sortTree();
// Define the zoom function for the zoomable tree
/*function zoom() {
svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}*/
// define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents
//var zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3]).on("zoom", zoom);
// define the baseSvg, attaching a class for styling and the zoomListener
var baseSvg =panCanvas.append("g");
// Helper functions for collapsing and expanding nodes.
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
function expand(d) {
if (d._children) {
d.children = d._children;
d.children.forEach(expand);
d._children = null;
}
}
// Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children.
// Toggle children function
function toggleChildren(d) {
if (d.children) {
d._children = d.children;
d.children = null;
update(d);
minimap.render();
//centerNode(d);
} else if (d._children) {
d.children = d._children;
d._children = null;
update(d);
minimap.render();
//centerNode(d);
} else {
d.children = null;
var json = {
"useCase" : d.useCase,
"chartType" : d.chartType,
"type" : d.type,
"assetId" : d.assetId,
"name" : d.name,
"childQueriesWithDelim" : d.childQueriesWithDelim,
"imgSrc" : d.imgSrc
};
window.parameterJsonData = JSON.stringify(json);
window.getDataMethod();
window.setChildData = function (childData) {
var childObj = getObjects(childData, 'name', d.name);
if (childObj != null) {
var newnodes = tree.nodes(childObj[0].children).reverse();
d.children = newnodes[0];
update(d);
minimap.render();
//centerNode(d);
}
}
}
}
// Toggle children on click.
function click(d) {
//if (d3.event.defaultPrevented)
//return; // click suppressed
$('#loading' + d.id).show();
toggleChildren(d);
}
function update(source) {
// Compute the new height, function counts total children of root node and sets tree height accordingly.
// This prevents the layout looking squashed when new nodes are made visible or looking sparse when nodes are removed
// This makes the layout more consistent.
$('#loading' + source.id).hide();
var levelWidth = [1];
var childCount = function (level, n) {
if (n.children && n.children.length > 0) {
if (levelWidth.length <= level + 1)
levelWidth.push(0);
levelWidth[level + 1] += n.children.length;
n.children.forEach(function (d) {
childCount(level + 1, d);
});
}
};
childCount(0, root);
var newHeight = d3.max(levelWidth) * 25; // 25 pixels per line
tree = tree.size([newHeight, viewerWidth]);
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Set widths between levels based on maxLabelLength.
nodes.forEach(function (d) {
//d.y = (d.depth * (maxLabelLength * 30)); //maxLabelLength * 10px
// alternatively to keep a fixed scale one can set a fixed depth per level
// Normalize for fixed-depth by commenting out below line
d.y = (d.depth * 150); //500px per level.
});
// Update the nodes…
var node = svgGroup.selectAll("g.node")
.data(nodes, function (d) {
return d.id || (d.id = ++i);
});
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on('click', click);
/*nodeEnter.append("circle")
.attr('class', 'nodeCircle')
.attr("r", 0)
.style("fill", function (d) {
return d.hasChild ? "lightsteelblue" : "#fff";
});*/
nodeEnter.append("svg:image")
.attr("class", "nodeCircle")
.attr("xlink:href", function (d) {
return d.imgSrc;
})
.attr("x", "-8px")
.attr("y", "-8px")
.attr("width", function (d) {
if (d.id == rootNode.id) {
return "40px";
} else {
return "16px";
}
})
.attr("height", function (d) {
if (d.id == rootNode.id) {
return "40px";
} else {
return "16px";
}
});
nodeEnter.append("foreignObject").attr("width", 100)
.attr("height", 100).attr("id", function (d) {
return "loading" + d.id;
}).style("display", "none")
.append("xhtml:div").html(
"<img src=\"d3/images/loading.gif\"/>");
nodeEnter.append("a")
.attr("xlink:href", function (d) {
return d.url;
})
.on("mousedown.zoom", function (d) {
if (d.url != null) {
disableDrag();
}
})
.append("text")
.attr("x", function (d) {
return d.hasChild ? -10 : 10;
})
.attr("dy", ".02em")
.attr('class', 'nodeText')
.attr("text-anchor", function (d) {
return d.hasChild ? "end" : "start";
})
.text(function (d) {
var name = d.name.substr(0, d.truncationLimit);
if (d.name != null && d.name.length > d.truncationLimit) {
name = name.concat("...");
}
return name;
})
.style("fill-opacity", 0)
.on("mouseover", function (d) {
var res = d.description ? d.description.split(",") : null;
var desc = "";
for (var i = 0; res != null && i < res.length; i++) {
desc = desc + '<div>' + res[i] + '</div>';
}
if (d.description == null) {
desc = '<div>Name : ' + d.name + '</div>';
}
tooltip.show([d3.event.clientX, d3.event.clientY], desc);
})
.on('mouseout', function () {
tooltip.cleanup()
});
/*nodeEnter.append("foreignObject")
.attr('x', 10)
.attr("width", 100)
.attr("height", 200)
.append("xhtml:p")
.attr('style', 'word-wrap: break-word; text-align:center;')
.append("xhtml:a")
.attr("xlink:href", function (d) {
return d.url;
})
.html(function (d) {
return d.name;
});*/
// Update the text to reflect whether node has children or not.
node.select('text')
.attr("x", function (d) {
return d.hasChild ? -10 : 10;
})
.attr("dy", ".02em")
.attr("text-anchor", function (d) {
return d.hasChild ? "end" : "start";
})
.text(function (d) {
var name = d.name.substr(0, d.truncationLimit);
if (d.name != null && d.name.length > d.truncationLimit) {
name = name.concat("...");
}
return name;
});
// Change the circle fill depending on whether it has children and is collapsed
/*node.select("circle.nodeCircle")
.attr("r", 4.5);*/
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + d.y + "," + d.x + ")";
});
// Fade the text in
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + source.y + "," + source.x + ")";
})
.remove();
/*nodeExit.select("circle")
.attr("r", 0);*/
nodeExit.select("text")
.style("fill-opacity", 0);
// Update the links…
var link = svgGroup.selectAll("path.link")
.data(links, function (d) {
return d.target.id;
});
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function (d) {
var o = {
x : source.x0,
y : source.y0
};
return diagonal({
source : o,
target : o
});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function (d) {
var o = {
x : source.x,
y : source.y
};
return diagonal({
source : o,
target : o
});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function (d) {
d.x0 = d.x;
d.y0 = d.y;
});
//canvas.addItem(svgGroup);
minimap.render();
}
// Append a group which holds all nodes and which the zoom Listener can act upon.
var svgGroup = baseSvg.append("g");
// Define the root
root = treeData;
rootNode = treeData;
root.x0 = viewerHeight / 2;
root.y0 = 0;
// Layout the tree initially and center on the root node.
update(root);
function disableDrag() {
baseSvg.on("mousedown.zoom", null);
}
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i))
continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
//d3.select(self.frameElement).style("height", _height + "px");
}
/** RENDER **/
canvas.render = function() {
svgDefs
.select(".clipPath .background")
.attr("width", width)
.attr("height", height);
svg
.attr("width", width + (wrapperBorder*2) + minimapPadding*2 + (width*minimapScale))
.attr("height", height + (wrapperBorder*2));
outerWrapper
.select(".background")
.attr("width", width + wrapperBorder*2)
.attr("height", height + wrapperBorder*2);
innerWrapper
.attr("transform", "translate(" + (wrapperBorder) + "," + (wrapperBorder) + ")")
.select(".background")
.attr("width", width)
.attr("height", height);
panCanvas
.attr("width", width)
.attr("height", height)
.select(".background")
.attr("width", width)
.attr("height", height);
minimap
.x(width + minimapPadding)
.y(minimapPadding)
.render();
};
canvas.zoomEnabled = function(isEnabled) {
if (!arguments.length) { return zoomEnabled }
zoomEnabled = isEnabled;
};
canvas.dragEnabled = function(isEnabled) {
if (!arguments.length) { return dragEnabled }
dragEnabled = isEnabled;
};
canvas.reset = function() {
d3.transition().duration(750).tween("zoom", function() {
var ix = d3.interpolate(xScale.domain(), [-width / 2, width / 2]),
iy = d3.interpolate(yScale.domain(), [-height / 2, height / 2]),
iz = d3.interpolate(scale, 1);
return function(t) {
zoom.scale(iz(t)).x(x.domain(ix(t))).y(y.domain(iy(t)));
zoomed(iz(t));
};
});
};
}
//============================================================
// Accessors
//============================================================
canvas.width = function(value) {
if (!arguments.length) return width;
width = parseInt(value, 10);
return this;
};
canvas.height = function(value) {
if (!arguments.length) return height;
height = parseInt(value, 10);
return this;
};
canvas.scale = function(value) {
if (!arguments.length) { return scale; }
scale = value;
return this;
};
return canvas;
};
/** MINIMAP **/
d3.demo.minimap = function() {
"use strict";
var minimapScale = 0.15,
scale = 1,
zoom = null,
base = null,
target = null,
width = 0,
height = 0,
x = 0,
y = 0,
frameX = 0,
frameY = 0;
function minimap(selection) {
base = selection;
var container = selection.append("g")
.attr("class", "minimap")
.call(zoom);
zoom.on("zoom.minimap", function() {
scale = d3.event.scale;
});
minimap.node = container.node();
var frame = container.append("g")
.attr("class", "frame")
frame.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.attr("filter", "url(#minimapDropShadow)");
var drag = d3.behavior.drag()
.on("dragstart.minimap", function() {
var frameTranslate = d3.demo.util.getXYFromTranslate(frame.attr("transform"));
frameX = frameTranslate[0];
frameY = frameTranslate[1];
})
.on("drag.minimap", function() {
d3.event.sourceEvent.stopImmediatePropagation();
frameX += d3.event.dx;
frameY += d3.event.dy;
frame.attr("transform", "translate(" + frameX + "," + frameY + ")");
var translate = [(-frameX*scale),(-frameY*scale)];
target.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
zoom.translate(translate);
});
frame.call(drag);
/** RENDER **/
minimap.render = function() {
scale = zoom.scale();
container.attr("transform", "translate(" + x + "," + y + ")scale(" + minimapScale + ")");
var node = target.node().cloneNode(true);
node.removeAttribute("id");
base.selectAll(".minimap .panCanvas").remove();
minimap.node.appendChild(node);
var targetTransform = d3.demo.util.getXYFromTranslate(target.attr("transform"));
frame.attr("transform", "translate(" + (-targetTransform[0]/scale) + "," + (-targetTransform[1]/scale) + ")")
.select(".background")
.attr("width", width/scale)
.attr("height", height/scale);
frame.node().parentNode.appendChild(frame.node());
d3.select(node).attr("transform", "translate(1,1)");
};
}
//============================================================
// Accessors
//============================================================
minimap.width = function(value) {
if (!arguments.length) return width;
width = parseInt(value, 10);
return this;
};
minimap.height = function(value) {
if (!arguments.length) return height;
height = parseInt(value, 10);
return this;
};
minimap.x = function(value) {
if (!arguments.length) return x;
x = parseInt(value, 10);
return this;
};
minimap.y = function(value) {
if (!arguments.length) return y;
y = parseInt(value, 10);
return this;
};
minimap.scale = function(value) {
if (!arguments.length) { return scale; }
scale = value;
return this;
};
minimap.minimapScale = function(value) {
if (!arguments.length) { return minimapScale; }
minimapScale = value;
return this;
};
minimap.zoom = function(value) {
if (!arguments.length) return zoom;
zoom = value;
return this;
};
minimap.target = function(value) {
if (!arguments.length) { return target; }
target = value;
width = parseInt(target.attr("width"), 10);
height = parseInt(target.attr("height"), 10);
return this;
};
return minimap;
};
/** UTILS **/
d3.demo.util = {};
d3.demo.util.getXYFromTranslate = function(translateString) {
var split = translateString.split(",");
var x = split[0] ? ~~split[0].split("(")[1] : 0;
var y = split[1] ? ~~split[1].split(")")[0] : 0;
return [x, y];
};
/** RUN SCRIPT **/
treeChart= (function (divID, treeData, height, width) {
var canvasWidth = width;
var shapes = [];
var lastXY = 1;
var zoomEnabled = true;
var dragEnabled = true;
var canvas = d3.demo.canvas(width,height).width(width/2).height(height/2);
d3.select(divID).call(canvas);
canvas.loadTree(divID,treeData,height,width);
});
I want to fill the height of the brush selection by default to the height of the rectangles on which it is drawn.
Here is my code:
var margin = {top: 10, right: 50, bottom: 20, left: 50},
width = 800 - margin.left - margin.right,
height = 120 - margin.top - margin.bottom;
var svgheight=40,svggraphheight=400;
var svg,svgcheckins,svgbuilds,svgoss,svgappsec;
var x,j = 0;
var x_axis = 1;
var y_axis = 45;
var xvar=0;
var yvar=40;
var rectangle,RectangleAttrb,rect,rectdata,selected,begindata,enddata;
function loaddata()
{
svg = d3.select("#timer").append("svg").attr("id","svgtimer")
.attr("width", 550)
.attr("height", svgheight)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svgcheckins= d3.select("#legend").append("svg").attr("id","svgcheckins")
.attr("width", 250)
.attr("height", 200)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("TimerData.json", function(data)
{
CreateLegend('#timer',svg,"rectangle",data,'Mar 1','Oct 4');
createbrush();
});
}
function createbrush()
{
var brush = d3.svg.brush()
.x(d3.scale.identity().domain([0, width]))
.y(d3.scale.identity().domain([0, height+30]))
//.on("brushstart", brushstart)
.on("brushend", brushed);
svg.append("g").call(brush);
function brushed()
{
//var e = brush.extent();
var e = d3.event.target.extent();
selected = svg.selectAll("rect").filter(function(d)
{
return d.x_axis <= e[1][0] && d.x_axis + d.width >= e[0][0] && d.y_axis <= e[1][1] && d.y_axis + d.height >= e[0][1];
})
//console.log("e[1][0] " + e[1][0] + " e[0][0] " + e[0][0] + "object " +e);
//createtinderboxes(selected);
}
function brushstart()
{
var e = brush.extent(0,5);
}
}
function CreateLegend(div,svg,svgid,data,header,trail)
{
var traillength=0;
var svgelem;
jsondata = data;
console.log(data);
rectangle= svg.selectAll("rect").data(data).enter().append("rect");
var RectangleAttrb = rectangle
.attr("id", function (d,i) { return svgid + "id" + i ; })
.attr("x", function (d) { return d.x_axis; })
.attr("y", function (d) { return d.y_axis; })
.attr("width",function(d) { return d.width; } )
.attr("height",function(d) { return d.height; })
.style("stroke", function (d) { return d.border;})
.style("fill", function(d) { return d.color; });
var textparam = svg.selectAll("text").data(data).enter().append("text");
var yearheader = d3.select("#header");
if(yearheader.empty())
{
var textheader = svg.append("text").attr("dx",20).attr("dy",5).text(header).attr("id",header).attr("style","margin-bottom:21px;border-bottom: solid 2px #ffd97f; font-size:12px;")
}
if (trail.length == 0)
{
d3.select(header).attr("style","font-size:15.1px;text-decoration:underline");
}
var text = textparam .attr("x", function (d) { traillength = d.x_axis + d.width +10; return d.x_axis + d.width +10; })
.attr("y", function (d) { return d.y_axis + d.height-5; })
.attr("width",30 )
.attr("height",20)
.attr("style", "text-decoration:none")
.text(function(d) { return d.text; });
var yearheader = d3.select("#trail");
if (trail.length > 0 && yearheader.empty() )
{
svg.append("text").attr("id","trail").attr("dx",traillength-10).attr("dy",5).text(trail).attr("style","margin-bottom:21px;border-bottom: solid 2px #ffd97f; font-size:12px;" )
}
}
the data is read from json file:
[
{ "x_axis":40, "y_axis": 10,"width":20,"height":15,"color" : "#ffffff","border":"#000000"},
{ "x_axis":60, "y_axis": 10,"width":20,"height":15,"color" : "#ffffff","border":"#000000"},
{ "x_axis":80, "y_axis":10,"width":20,"height":15,"color" : "#ffffff","border":"#000000"}
]
You can set the extent of the brush in code using brush.extent(), so in your case something like
brush.extent([[40, 80], [10, 25]]);
I'm populating a graph with multiple lines and trying to access the highest values, then incrementing them every few seconds. I'm not sure what syntax to use to access each line separately...
index.html:
function generateVisualization(data){
//className for first timeline
var className = "ch1Class";
data.forEach(function(d) {
d.date = parseDate(d.date);
d.price = +d.price; // + ensures its an integer
});
maxY = d3.max(data.map(function(d) { return d.price; }));
obj[className] = maxY;
maxX = d3.max(data.map(function(d) { return d.date; }));
objD[className] = maxX;
x.domain(d3.extent(data.map(function(d) { return Math.max(d.date); })));
y.domain([0, d3.max(data.map(function(d) { return Math.max(d.price); }))]);
x2.domain(x.domain());
y2.domain(y.domain());
focus.append("path")
.datum(data)
.attr("clip-path", "url(#clip)")
.attr("d", area)
.attr("class", className);
//make sure the first textbox is selected in the channel selection
$("#demo_box_1").attr("checked","checked");
focus.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
focus.append("g")
.attr("class", "y axis")
.call(yAxis);
context.append("path")
.datum(data)
.attr("class", className)
.attr("d", area2);
context.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "x brush")
.call(brush)
.selectAll("rect")
.attr("y", -6)
.attr("height", height2 + 7);
}
<!-- time series start -->
var margin = {top: 10, right: 10, bottom: 100, left: 40},
margin2 = {top: 430, right: 10, bottom: 20, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
height2 = 500 - margin2.top - margin2.bottom;
var parseDate = d3.time.format("%b %Y").parse;
//var parseDate = d3.time.format("%x %X.%L").parse;
var x = d3.time.scale().range([0, width]),
x2 = d3.time.scale().range([0, width]),
y = d3.scale.linear().range([height, 0]),
y2 = d3.scale.linear().range([height2, 0]);
var xAxis = d3.svg.axis().scale(x).orient("bottom"),
xAxis2 = d3.svg.axis().scale(x2).orient("bottom"),
yAxis = d3.svg.axis().scale(y).orient("left");
var brush = d3.svg.brush()
.x(x2)
.on("brush", brushed);
var area = d3.svg.area()
.interpolate("monotone")//smooths path corners
.x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.price); });
var area2 = d3.svg.area()
.interpolate("monotone")//smooths path corners
.x(function(d) { return x2(d.date); })
.y0(height2)
.y1(function(d) { return y2(d.price); });
var svg = d3.select("#maincontent1").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("class", "timeLine");
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var focus = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = svg.append("g")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
var dataset; //global variable
d3.csv("ch1.csv", function(error, data) {
dataset = data;
generateVisualization(data);
});
<!-- time series end -->
</script>
</div><!-- end #maincontent -->
included js file:
//create an object to track max y values
var obj = {};
var objD = {};
// if adding/removing paths check max values and rescale if necessary
function maxValue(maxY,maxX,addRemove,className){
//if adding and its not in the array yet, then add to array, then check to see if its got the highest yvalue, if so updateaxis
if(addRemove=="add"){
if((className in obj )!=true){
// add new class/max value to an object
obj[className] = maxY;
objD[className] = maxY;
//check to see if its the highest yvalue in the object and if so, rescale
var max = 0;
for(var i in obj){
if(obj[i] > max) {
max = obj[i];
}
}
if (max==obj[className]){
updateAxis("y");
//reScaleEverything();
}
// important, reset the y domain to the new max, if you don't do this then the brushing will use the last added paths y max
y.domain([0, max]);
}
} else if (addRemove=="remove"){
//if its being remove then it should already have a matching obj, remove it from the obj array and then test for the new max yVal, rescale to new max
if((className in obj )==true){
var max = 0;
for(var i in obj){
if(obj[i] > max) {
max = obj[i];
}
}
if (max==obj[className]){
delete obj[className];
delete objD[className];
var max = 0;
for(var i in obj){
if(obj[i] > max) {
max = obj[i];
}
}
//set the new y domain
y.domain([0, max]);
//y2.domain([0, max]);
//rescale y using the new max value
updateAxis("y");
}
}
}
}
// found in maxValue(), this is called after setting domains
function updateAxis(axisXY){
if (axisXY == 'x'){//Update x-axis
svg.select(".x.axis")
.transition()
.duration(1000)
.call(xAxis);
} else if (axisXY == 'y'){
//Update y-axis
svg.select(".y.axis")
.transition()
.duration(1000)
.call(yAxis);
}
// very important, rescales all existing paths to new y values
focus.selectAll("path").attr("d", area);
//focus.selectAll("path").attr("d", area2);
//focus.select(".x.axis").call(xAxis);
}
function rescaleEverything(){
}
function checkSetY(maxY){
var max = 0;
for(var i in obj){
if(obj[i] > max) {
max = obj[i];
}
}
if(maxY>max){
//if the new maxY is bigger then any other Y then set a new domain
return y.domain([0, maxY]);
}
}
function checkSetX(maxX){
console.log(maxX);
var max = 0;
for(var i in objD){
if(objD[i] > max) {
max = objD[i];
}
}
if(maxX>max){
//if the new maxX is bigger then any other Y then set a new domain
return x.domain([0, maxX]);
}
}
function addCSV(csvFileName, className){
d3.csv(csvFileName, function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.price = +d.price;
});
maxY = d3.max(data.map(function(d) { return d.price; }));
checkSetY(maxY);
maxX = d3.max(data.map(function(d) { return d.date; }));
checkSetX(maxX);
//x.domain(d3.extent(data.map(function(d) { return d.date; })));
//y.domain([0, d3.max(data.map(function(d) { return d.price; }))]);
x2.domain(x.domain());
y2.domain(y.domain());
focus.append("path")
.datum(data)
.attr("clip-path", "url(#clip)")
.attr("d", area)
.attr("class", className);
context.append("path")
.datum(data)
.attr("class", className)
.attr("d", area2);
// important, this fixes brushing issues, avoids multiple context brush areas
context.selectAll("g.x.brush").remove();
context.append("g")
.attr("class", "x brush")
.call(brush)
.selectAll("rect")
.attr("y", -6)
.attr("height", height2 + 7);
maxValue(maxY,maxX,"add",className);
//maxX = d3.max(data.map(function(d) { return Date.max(d.date); }));
//console.log(maxX);
});
}
function removeCSV(className){
var classRemoval = "." + className;
d3.selectAll(classRemoval).transition().remove();
maxValue(maxY,maxX,"remove",className);
}
function brushed() {
x.domain(brush.empty() ? x2.domain() : brush.extent());
//console.log(x2);
focus.selectAll("path").attr("d", area);
focus.select(".x.axis").call(xAxis);
}
function incrementDate(){
//pass in last date
}
$(document).ready(function() {
//addCSV("sp501.csv", "timeLine2");
//toggle the side panel sliding
$(".togglePanel").click(function(){
//$("#channels").animate({left:'-130px'},350);
var $lefty = $("#channels");
$lefty.animate({
left: parseInt($lefty.css('left'),10) == 0 ?
-$lefty.outerWidth() :
0
});
});
$("#maincontent2, #maincontent3").hide();
$(".gauge").hover(
function(){
var idName = $(this).attr('id');
var newName = "." + idName.substring(0,3) + "Class";
//alert(newName);
$(newName).css("fill","#c2c2c2");
$(newName).css("fill-opacity",".7");
//$(newName).css("stroke-width","3");
},
function(){
var idName = $(this).attr('id');
var newName = "." + idName.substring(0,3) + "Class";
$(newName).css("fill","none");
$(newName).css("stroke-width","1");
}
);
//hide all gauges
$(".gauge").hide();
//this one starts already open
$("#ch1GaugeContainer").slideDown();
$("#tabs li").click(function() {
$("#tabs li").removeClass("selected");
$(this).addClass("selected");
});
$('#channelSelect :checkbox').click(function() {
var $this = $(this);
var channelName = $this.attr("value") + ".csv";
var className = $this.attr("value") + "Class";
var guageName = "#" + $this.attr("value") + "GaugeContainer";
// $this will contain a reference to the checkbox
if ($this.is(':checked')) {
addCSV(channelName,className);
$(guageName).slideDown();
} else {
removeCSV(className);
$(guageName).slideUp();
}
});
});