Related
I'm having issues trying to make mouseover works on my D3 graph (I'm not an D3 expert). I managed to make line and points sincronized with zoom but unable to show toolptip on point over, not sure if I'm missing something, as you can see in the image below everything is working fine.
You can my code using the button below. Thanks for the help.
var data = JSON.parse('{"success":true,"response":[{"product_date":"2019-09-01","value":{"temperature":"30.6029968261719"}},{"product_date":"2019-09-02","value":{"temperature":"30.1170043945312"}},{"product_date":"2019-09-03","value":{"temperature":"30.0830078125"}},{"product_date":"2019-09-04","value":{"temperature":"30.2479858398438"}},{"product_date":"2019-09-05","value":{"temperature":"30.9110107421875"}},{"product_date":"2019-09-06","value":{"temperature":"31.3150024414062"}},{"product_date":"2019-09-07","value":{"temperature":"31.2909851074219"}},{"product_date":"2019-09-08","value":{"temperature":"30.7149963378906"}},{"product_date":"2019-09-09","value":{"temperature":"30.010009765625"}},{"product_date":"2019-09-10","value":{"temperature":"29.7990112304688"}},{"product_date":"2019-09-11","value":{"temperature":"29.6549987792969"}},{"product_date":"2019-09-12","value":{"temperature":"30.0769958496094"}},{"product_date":"2019-09-13","value":{"temperature":"30.0830078125"}},{"product_date":"2019-09-14","value":{"temperature":"29.8619995117188"}},{"product_date":"2019-09-15","value":{"temperature":"30.0029907226562"}},{"product_date":"2019-09-16","value":{"temperature":"30.1080017089844"}},{"product_date":"2019-09-17","value":{"temperature":"30.6979980469"}},{"product_date":"2019-09-18","value":{"temperature":"30.3139953613"}},{"product_date":"2019-09-19","value":{"temperature":"30.5180053710938"}},{"product_date":"2019-09-20","value":{"temperature":"30.3720092773"}},{"product_date":"2019-09-21","value":{"temperature":"29.8710021973"}},{"product_date":"2019-09-22","value":{"temperature":"29.7460021972656"}},{"product_date":"2019-09-23","value":{"temperature":"29.5769958496"}},{"product_date":"2019-09-24","value":{"temperature":"29.1159973145"}},{"product_date":"2019-09-25","value":{"temperature":"28.908996582"}}]}');
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 110, left: 40},
margin2 = {top: 430, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
height2 = +svg.attr("height") - margin2.top - margin2.bottom;
var parseDate = d3.timeParse("%b %Y");
var x = d3.scaleTime().range([0, width]),
x2 = d3.scaleTime().range([0, width]),
y = d3.scaleLinear().range([height, 0]),
y2 = d3.scaleLinear().range([height2, 0]);
var xAxis = d3.axisBottom(x),
xAxis2 = d3.axisBottom(x2),
yAxis = d3.axisLeft(y);
var brush = d3.brushX()
.extent([[0, 0], [width, height2]])
.on("brush end", brushed);
var zoom = d3.zoom()
.scaleExtent([1, Infinity])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", zoomed);
var line1 = d3.line()
.curve(d3.curveMonotoneX)
.x(function(d) { return x(d.date) })
.y(function(d) { return y(d.value) });
var line2 = d3.line()
.curve(d3.curveMonotoneX)
.x(function(d) { return x2(d.date) })
.y(function(d) { return y2(d.value) });
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var focus = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var points = svg.append('g')
.attr("clip-path", "url(#clip)")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
var context = svg.append("g")
.attr("class", "context")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
let vdata = data.response;
// format the data
vdata.forEach((d) => {
d.date = d3.timeParse("%Y-%m-%d")(d.product_date);
d.value = +d.value.temperature;
});
x.domain(d3.extent(vdata, function(d) { return d.date; }));
y.domain([0, d3.max(vdata, function(d) { return d.value; })]);
x2.domain(x.domain());
y2.domain(y.domain());
focus.append("path")
.datum(vdata)
.attr("clip-path", "url(#clip)")
.attr("class", "line")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", line1);
focus.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
focus.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
points.selectAll(".dot")
.data(vdata)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function(d, i) { return x(d.date) })
.attr("cy", function(d) { return y(d.value) })
.attr("r", 3)
.attr("pointer-events", "all")
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div .html(parseDate(d.date) + "<br/>" + f(d.value))
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
points.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
context.append("path")
.datum(vdata)
.attr("class", "line")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", line2);
context.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.move, x.range());
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
function brushed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
var s = d3.event.selection || x2.range();
x.domain(s.map(x2.invert, x2));
focus.select(".line").attr("d", d3.line()
.x(function(d) { return x(d.date) })
.y(function(d) { return y(d.value) })
.curve(d3.curveMonotoneX)
);
focus.select(".axis--x").call(xAxis);
points.selectAll('circle')
.attr("cx", function(d, i) { return x(d.date) })
.attr("cy", function(d) { return y(d.value) });
points.select(".axis--x").call(xAxis);
svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
.scale(width / (s[1] - s[0]))
.translate(-s[0], 0));
}
function zoomed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
var t = d3.event.transform;
x.domain(t.rescaleX(x2).domain());
focus.select(".line").attr("d", d3.line()
.x(function(d) { return x(d.date) })
.y(function(d) { return y(d.value) })
.curve(d3.curveMonotoneX)
);
points.selectAll('circle')
.attr("cx", function(d, i) { return x(d.date) })
.attr("cy", function(d) { return y(d.value) });
points.select(".axis--x").call(xAxis);
focus.select(".axis--x").call(xAxis);
context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
}
function type(d) {
d.date = parseDate(d.date);
d.value = +d.value;
return d;
}
.area {
fill: steelblue;
clip-path: url(#clip);
}
.zoom {
cursor: move;
fill: none;
pointer-events: all;
}
.dot {
fill: steelblue;
stroke: #fff;
}
div.tooltip {
position: absolute;
text-align: left;
width: 70px;
height: 28px;
padding: 3px;
font: 11px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 3px;
pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<svg width="960" height="500"></svg>
In order to do zoom interaction you have placed an invisible rectangle over your plot area:
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
You do this after you append the g that holds the plot, so the rectangle is over the points.
The pointer events are intercepted by this rectangle before they can interact with the points.
What you can do instead is append the rectangle to the g that is selected as focus and lower it with selection.lower() (this just moves it so it is the first child of the g, which has the effect of drawing it first or under the plot):
focus.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.lower();
.call(zoom);
However now we have the opposite problem (though it is slight): the plot intercepts mouse events meaning that one cannot zoom if the mouse is over the plot, so we could modify this slightly:
focus.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.lower();
focus.call(zoom);
However, as focus is not a selection of the g that holds the points, when the mouse is over a point, the graph won't zoom (when the mouse is over the line, it will though). Likewise, as the axes are part of the g selected in focus, one can zoom when the mouse is over the axes.
This may be a problem, perhaps, not, but to address it, we can rejig the DOM structure a bit to ensure everything in the plot area (above the bottom axis and to the right of the vertical axis) interacts with the zoom, but nothing else.
To do so we add the points as children of the focus g, and call the axes on a different g (I've added a new one for you):
var axes = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
var points = focus.append('g') // no need to add a transform, focus already has one.
.attr("clip-path", "url(#clip)")
Of course we'll need to update all the places where we call an axis to call it on the new g. Altogether we get:
var data = JSON.parse('{"success":true,"response":[{"product_date":"2019-09-01","value":{"temperature":"30.6029968261719"}},{"product_date":"2019-09-02","value":{"temperature":"30.1170043945312"}},{"product_date":"2019-09-03","value":{"temperature":"30.0830078125"}},{"product_date":"2019-09-04","value":{"temperature":"30.2479858398438"}},{"product_date":"2019-09-05","value":{"temperature":"30.9110107421875"}},{"product_date":"2019-09-06","value":{"temperature":"31.3150024414062"}},{"product_date":"2019-09-07","value":{"temperature":"31.2909851074219"}},{"product_date":"2019-09-08","value":{"temperature":"30.7149963378906"}},{"product_date":"2019-09-09","value":{"temperature":"30.010009765625"}},{"product_date":"2019-09-10","value":{"temperature":"29.7990112304688"}},{"product_date":"2019-09-11","value":{"temperature":"29.6549987792969"}},{"product_date":"2019-09-12","value":{"temperature":"30.0769958496094"}},{"product_date":"2019-09-13","value":{"temperature":"30.0830078125"}},{"product_date":"2019-09-14","value":{"temperature":"29.8619995117188"}},{"product_date":"2019-09-15","value":{"temperature":"30.0029907226562"}},{"product_date":"2019-09-16","value":{"temperature":"30.1080017089844"}},{"product_date":"2019-09-17","value":{"temperature":"30.6979980469"}},{"product_date":"2019-09-18","value":{"temperature":"30.3139953613"}},{"product_date":"2019-09-19","value":{"temperature":"30.5180053710938"}},{"product_date":"2019-09-20","value":{"temperature":"30.3720092773"}},{"product_date":"2019-09-21","value":{"temperature":"29.8710021973"}},{"product_date":"2019-09-22","value":{"temperature":"29.7460021972656"}},{"product_date":"2019-09-23","value":{"temperature":"29.5769958496"}},{"product_date":"2019-09-24","value":{"temperature":"29.1159973145"}},{"product_date":"2019-09-25","value":{"temperature":"28.908996582"}}]}');
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 110, left: 40},
margin2 = {top: 430, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
height2 = +svg.attr("height") - margin2.top - margin2.bottom;
var parseDate = d3.timeParse("%b %Y");
var x = d3.scaleTime().range([0, width]),
x2 = d3.scaleTime().range([0, width]),
y = d3.scaleLinear().range([height, 0]),
y2 = d3.scaleLinear().range([height2, 0]);
var xAxis = d3.axisBottom(x),
xAxis2 = d3.axisBottom(x2),
yAxis = d3.axisLeft(y);
var brush = d3.brushX()
.extent([[0, 0], [width, height2]])
.on("brush end", brushed);
var zoom = d3.zoom()
.scaleExtent([1, Infinity])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", zoomed);
var line1 = d3.line()
.curve(d3.curveMonotoneX)
.x(function(d) { return x(d.date) })
.y(function(d) { return y(d.value) });
var line2 = d3.line()
.curve(d3.curveMonotoneX)
.x(function(d) { return x2(d.date) })
.y(function(d) { return y2(d.value) });
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var focus = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var axes = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
var points = focus.append('g')
.attr("clip-path", "url(#clip)")
var context = svg.append("g")
.attr("class", "context")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
let vdata = data.response;
// format the data
vdata.forEach((d) => {
d.date = d3.timeParse("%Y-%m-%d")(d.product_date);
d.value = +d.value.temperature;
});
x.domain(d3.extent(vdata, function(d) { return d.date; }));
y.domain([0, d3.max(vdata, function(d) { return d.value; })]);
x2.domain(x.domain());
y2.domain(y.domain());
focus.append("path")
.datum(vdata)
.attr("clip-path", "url(#clip)")
.attr("class", "line")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", line1);
axes.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
axes.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
points.selectAll(".dot")
.data(vdata)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function(d, i) { return x(d.date) })
.attr("cy", function(d) { return y(d.value) })
.attr("r", 3)
.attr("pointer-events", "all")
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div .html(parseDate(d.date) + "<br/>" + (d.value))
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
points.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
context.append("path")
.datum(vdata)
.attr("class", "line")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 1.5)
.attr("d", line2);
context.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.move, x.range());
focus.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.lower();
focus.call(zoom);
function brushed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
var s = d3.event.selection || x2.range();
x.domain(s.map(x2.invert, x2));
focus.select(".line").attr("d", d3.line()
.x(function(d) { return x(d.date) })
.y(function(d) { return y(d.value) })
.curve(d3.curveMonotoneX)
);
axes.select(".axis--x").call(xAxis);
points.selectAll('circle')
.attr("cx", function(d, i) { return x(d.date) })
.attr("cy", function(d) { return y(d.value) });
points.select(".axis--x").call(xAxis);
svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
.scale(width / (s[1] - s[0]))
.translate(-s[0], 0));
}
function zoomed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
var t = d3.event.transform;
x.domain(t.rescaleX(x2).domain());
focus.select(".line").attr("d", d3.line()
.x(function(d) { return x(d.date) })
.y(function(d) { return y(d.value) })
.curve(d3.curveMonotoneX)
);
points.selectAll('circle')
.attr("cx", function(d, i) { return x(d.date) })
.attr("cy", function(d) { return y(d.value) });
points.select(".axis--x").call(xAxis);
axes.select(".axis--x").call(xAxis);
context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
}
function type(d) {
d.date = parseDate(d.date);
d.value = +d.value;
return d;
}
.area {
fill: steelblue;
clip-path: url(#clip);
}
.zoom {
cursor: move;
fill: none;
pointer-events: all;
}
.dot {
fill: steelblue;
stroke: #fff;
}
div.tooltip {
position: absolute;
text-align: left;
width: 70px;
height: 28px;
padding: 3px;
font: 11px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 3px;
pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<svg width="960" height="500"></svg>
first i have created a multi-line chart with brush and zoom and now i am trying to add tool-tip for it. Such that when i mouse over the multi-line chart i get the variable : value of that particular line. Since i have just started i have referred few sites but i found this and altered my code. But i am just getting dots at various positions and nothings seems to work. If there is any link i can refer to and alter my code or any corrections to my code would be very much helpful.
morley.csv
Expt date Speed extra
1 2016-01-07 850 200
1 2016-01-08 740 300
1 2016-01-09 900 568
1 2016-01-10 1070 100
1 2016-01-01 930 789
1 2016-01-02 850 312
1 2016-01-03 950 864
1 2016-01-04 980 159
1 2016-01-05 980 345
1 2016-01-06 880 690
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
.zoom {
cursor: move;
fill: none;
pointer-events: all;
}
div.tooltip {
position: absolute;
text-align: center;
width: 60px;
height: 28px;
padding: 2px;
font: 12px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 110, left: 40},
margin2 = {top: 430, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
height2 = +svg.attr("height") - margin2.top - margin2.bottom;
var parseDate = d3.timeParse("%Y-%m-%d");
var x = d3.scaleTime().range([0, width]),
y = d3.scaleLinear().range([height, 0]),
//brush
x2 = d3.scaleTime().range([0, width]),
y2 = d3.scaleLinear().range([height2, 0]);
var xAxis = d3.axisBottom(x),
yAxis = d3.axisLeft(y),
//brush
xAxis2 = d3.axisBottom(x2);
//slider that grey selection one
var brush = d3.brushX()
.extent([[0, 0], [width, height2]])
.on("brush end", brushed);
var zoom = d3.zoom()
.scaleExtent([1, Infinity])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", zoomed);
var line = d3.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.extra); });
var line1 = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.Speed); });
//slider line
var line2 = d3.line()
.x(function (d) { return x2(d.date); })
.y(function (d) { return y2(d.Speed); });
var clip = svg.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("width", width)
.attr("height", height)
.attr("x", 0)
.attr("y", 0);
var Line_chart = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr("clip-path", "url(#clip)");
var focus = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = svg.append("g")
.attr("class", "context")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
//tooltip
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
d3.csv("data/morley.csv", type, function (error, data) {
if (error) throw error;
data.sort(function(a,b){
return a.date-b.date
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) {
return Math.max(d.Speed, d.extra); })]);
//slider
x2.domain(x.domain());
y2.domain(y.domain());
focus.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
focus.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
Line_chart.append("path")
.datum(data)
.attr("class", "line line-extra")
.style("stroke", "green")
.attr("d", line);
Line_chart.append("path")
.datum(data)
.attr("class", "line line-speed")
.style("stroke", "blue")
.attr("d", line1);
//slider line
context.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line2);
context.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
//slider
context.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.move, x.range());
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
// console.log(data);
//tooltip
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) { return x(d.date); })
.attr("cy", function(d) { return y(d.Speed); })
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div.html(formatTime(d.date) + "<br/>" + d.Speed)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) { return x(d.date); })
.attr("cy", function(d) { return y(d.extra); })
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div.html(formatTime(d.date) + "<br/>" + d.extra)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
});
function updateLines() {
Line_chart.select(".line-extra").attr("d", line);
Line_chart.select(".line-speed").attr("d", line1);
}
//selection in slider
function brushed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return;
var s = d3.event.selection || x2.range();
x.domain(s.map(x2.invert, x2));
Line_chart.select(".line").attr("d", line);
focus.select(".axis--x").call(xAxis);
svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
.scale(width / (s[1] - s[0]))
.translate(-s[0], 0));
updateLines();
}
function zoomed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return;
var t = d3.event.transform;
x.domain(t.rescaleX(x2).domain());
Line_chart.select(".line").attr("d", line);
focus.select(".axis--x").call(xAxis);
context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
updateLines();
}
function type(d) {
d.date = parseDate(d.date);
d.extra = +d.extra;
d.Speed=+d.Speed
return d;
}
</script>
Having trouble using an external file data.json for use on a bar chart with a brush. This seems to be a scope issue.
I am using,
d3.json("data.json", function(error, data) {...});
to read in the json file. Inside this main chart and brush chart are drawn. And there is a call to the variable 'brush', which is outside of d3.json() and in that var there is a call to the brush function which is also outside of d3.json(). The 'data' cannot be read inside the brush function. I tried passing data as a parameter, brush(data) but that doesn't work.
The error I get is,
Uncaught ReferenceError: data is not defined
This error refers to line 226 which is in the brush function and looks like this,
.data(data.filter(function(d) {....
and is the first use of 'data' in the brush function.
This is set up the same as Bostock's example Brush & Zoom
<!DOCTYPE html>
<meta charset="utf-8">
<style type="text/css">
body {
font-family: avenir next, sans-serif;
font-size: 12px;
}
.zoom {
cursor: move;
fill: none;
pointer-events: all;
}
.axis {
stroke-width: 0.5px;
stroke: #888;
font: 10px avenir next, sans-serif;
}
.axis>path {
stroke: #888;
}
</style>
<body>
</body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var margin = {
top: 20,
right: 20,
bottom: 90,
left: 50
},
margin2 = {
top: 230,
right: 20,
bottom: 30,
left: 50
},
width = 960 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom,
height2 = 300 - margin2.top - margin2.bottom;
var x = d3.scaleBand().range([0, width]).padding(0.1),
x2 = d3.scaleBand().range([0, width]).padding(0.1),
y = d3.scaleLinear().range([height, 0]),
y2 = d3.scaleLinear().range([height2, 0]);
var xAxis = d3.axisBottom(x).tickSize(0),
xAxis2 = d3.axisBottom(x2).tickSize(0),
yAxis = d3.axisLeft(y).tickSize(0);
var brush = d3.brushX()
.extent([
[0, 0],
[width, height2]
])
// .on("start brush end", brushed);
.on("brush", brushed);
var zoom = d3.zoom()
.scaleExtent([1, 2])
.translateExtent([
[0, 0],
[width, height]
])
.extent([
[0, 0],
[width, height]
])
.on("zoom", zoomed);
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var focus = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = svg.append("g")
.attr("class", "context")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
focus.append("text") // yAxis label
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x", 0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Distance in meters");
svg.append("text") // xAxis label
.attr("transform",
"translate(" + ((width + margin.right + margin.left) / 2) + " ," +
(height + margin.top + margin.bottom) + ")")
.style("text-anchor", "middle")
.text("Date");
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom); //see var zoom above
focus.append("g") //append xAxis to main chart
.attr("class", "axis x-axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
d3.json("data.json", function(error, data) {
if (error) throw error;
focus.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.distance;
})])
.range([height, 0])).tickSize(0));
data.forEach(function(d) {
d.distance = +d.distance;
return d;
},
function(error, data) {
if (error) throw error;
});
x.domain(data.map(function(d) {
return d.date;
}));
y.domain([0, d3.max(data, function(d) {
return d.distance;
})]);
x2.domain(x.domain());
y2.domain(y.domain());
//********* Main ar Chart ****************
var rects = focus.append("g");
rects.attr("clip-path", "url(#clip)");
rects.selectAll("rects")
.data(data)
.enter().append("rect")
.style("fill", function(d) {
return "lightblue";
})
.style('stroke', 'gray')
.attr("class", "rects")
.attr("x", function(d) {
return x(d.date);
})
.attr("y", function(d) {
return y(d.distance);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height - y(d.distance);
});
// //********* Brush Bar Chart ****************
var rects = context.append("g"); //draw bar chart in brush
rects.attr("clip-path", "url(#clip)");
rects.selectAll("rect")
.data(data)
.enter().append("rect")
.style("fill", function(d) {
return "lightblue";
})
.style('stroke', 'gray')
.attr("class", "rectss")
.attr("x", function(d) {
return x2(d.date);
})
.attr("y", function(d) {
return y2(d.distance);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height2 - y2(d.distance);
});
context.append("g")
.attr("class", "axis x-axis")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.move, x.range());
}); //closes d3.json()
function brushed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
// get bounds of selection
var s = d3.event.selection,
nD = [];
x2.domain().forEach((d) => { //not as smooth as I'd like it
var pos = x2(d) + x2.bandwidth() / 2;
if (pos > s[0] && pos < s[1]) {
nD.push(d);
}
});
x.domain(nD);
focus.selectAll(".rects")
.remove().exit()
.data(data.filter(function(d) {
return nD.indexOf(d.date) > -1
}))
.enter().append("rect")
.style("fill", function(d) {
return "lightblue";
})
.style('stroke', 'gray')
.attr("class", "rects")
.attr("x", function(d) {
return x(d.date);
})
.attr("y", function(d) {
return y(d.distance);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height - y(d.distance);
});
focus.select(".x-axis").call(xAxis);
svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
.scale(width / (s[1] - s[0]))
.translate(-s[0], 0));
};
function zoomed() {};
</script>
A small part of the data.json
[{
"date": "A",
"distance": "1100"
},
{
"date": "B",
"distance": "1500"
},
{
"date": "C",
"distance": "2000"
},
{
"date": "D",
"distance": "2500"
},
{
"date": "E",
"distance": "1975"
},
{
"date": "F",
"distance": "3000"
},
{
"date": "G",
"distance": "2100"
},
{
"date": "H",
"distance": "2100"
},
{
"date": "I",
"distance": "3300"
},
{
"date": "J",
"distance": "2000"
}
]
Any help would be greatly appreciated.
Thanks,
Addendum:
Why does this not work?
var data = null;
d3.json("data.json", function(error, data) {
if (error) throw error;
.....
)}
and this does work,
var data = null;
d3.json("data.json", function(error, newdata) {
if (error) throw error;
data = newdata;
.....});
Indeed you have an issue with your scope. The variable data is defined inside a function, so it can't be available out of this function. Here is the code to make it works :
<!DOCTYPE html>
<meta charset="utf-8">
<style type="text/css">
body {
font-family: avenir next, sans-serif;
font-size: 12px;
}
.zoom {
cursor: move;
fill: none;
pointer-events: all;
}
.axis {
stroke-width: 0.5px;
stroke: #888;
font: 10px avenir next, sans-serif;
}
.axis>path {
stroke: #888;
}
</style>
<body>
</body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var margin = {
top: 20,
right: 20,
bottom: 90,
left: 50
},
margin2 = {
top: 230,
right: 20,
bottom: 30,
left: 50
},
width = 960 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom,
height2 = 300 - margin2.top - margin2.bottom;
var x = d3.scaleBand().range([0, width]).padding(0.1),
x2 = d3.scaleBand().range([0, width]).padding(0.1),
y = d3.scaleLinear().range([height, 0]),
y2 = d3.scaleLinear().range([height2, 0]);
var xAxis = d3.axisBottom(x).tickSize(0),
xAxis2 = d3.axisBottom(x2).tickSize(0),
yAxis = d3.axisLeft(y).tickSize(0);
var brush = d3.brushX()
.extent([
[0, 0],
[width, height2]
])
// .on("start brush end", brushed);
.on("brush", brushed);
var zoom = d3.zoom()
.scaleExtent([1, 2])
.translateExtent([
[0, 0],
[width, height]
])
.extent([
[0, 0],
[width, height]
])
.on("zoom", zoomed);
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var focus = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = svg.append("g")
.attr("class", "context")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
focus.append("text") // yAxis label
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x", 0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Distance in meters");
svg.append("text") // xAxis label
.attr("transform",
"translate(" + ((width + margin.right + margin.left) / 2) + " ," +
(height + margin.top + margin.bottom) + ")")
.style("text-anchor", "middle")
.text("Date");
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom); //see var zoom above
focus.append("g") //append xAxis to main chart
.attr("class", "axis x-axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var data_global=null;
d3.json("data.json", function(error, data) {
if (error) throw error;
data_global=data;
focus.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d.distance;
})])
.range([height, 0])).tickSize(0));
data.forEach(function(d) {
d.distance = +d.distance;
return d;
},
function(error, data) {
if (error) throw error;
});
x.domain(data.map(function(d) {
return d.date;
}));
y.domain([0, d3.max(data, function(d) {
return d.distance;
})]);
x2.domain(x.domain());
y2.domain(y.domain());
//********* Main ar Chart ****************
var rects = focus.append("g");
rects.attr("clip-path", "url(#clip)");
rects.selectAll("rects")
.data(data)
.enter().append("rect")
.style("fill", function(d) {
return "lightblue";
})
.style('stroke', 'gray')
.attr("class", "rects")
.attr("x", function(d) {
return x(d.date);
})
.attr("y", function(d) {
return y(d.distance);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height - y(d.distance);
});
// //********* Brush Bar Chart ****************
var rects = context.append("g"); //draw bar chart in brush
rects.attr("clip-path", "url(#clip)");
rects.selectAll("rect")
.data(data)
.enter().append("rect")
.style("fill", function(d) {
return "lightblue";
})
.style('stroke', 'gray')
.attr("class", "rectss")
.attr("x", function(d) {
return x2(d.date);
})
.attr("y", function(d) {
return y2(d.distance);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height2 - y2(d.distance);
});
context.append("g")
.attr("class", "axis x-axis")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.move, x.range());
}); //closes d3.json()
function brushed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
// get bounds of selection
var s = d3.event.selection,
nD = [];
x2.domain().forEach((d) => { //not as smooth as I'd like it
var pos = x2(d) + x2.bandwidth() / 2;
if (pos > s[0] && pos < s[1]) {
nD.push(d);
}
});
x.domain(nD);
focus.selectAll(".rects")
.remove().exit()
.data(data_global.filter(function(d) {
return nD.indexOf(d.date) > -1
}))
.enter().append("rect")
.style("fill", function(d) {
return "lightblue";
})
.style('stroke', 'gray')
.attr("class", "rects")
.attr("x", function(d) {
return x(d.date);
})
.attr("y", function(d) {
return y(d.distance);
})
.attr("width", x.bandwidth())
.attr("height", function(d) {
return height - y(d.distance);
});
focus.select(".x-axis").call(xAxis);
svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
.scale(width / (s[1] - s[0]))
.translate(-s[0], 0));
};
function zoomed() {};
</script>
I tried to use the following code to show a d3.js tool-tip effect but I can't get it to work, why is the number not showing up:
<style>
svg {
width: 100%;
height: 100%;
position: center;
}
#hist_sexage {
background-color: lightgrey;
}
.rect:hover {
fill: yellow;
}
.tooltip {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
position: absolute;
display: none;
width: auto;
height: auto;
background: none repeat scroll 0 0 red;
border: 0 none;
border-radius: 8px 8px 8px 8px;
box-shadow: -3px 3px 15px #888888;
color: blue;
font: 12px sans-serif;
padding: 5px;
text-align: center;
}
</style>
<svg id="hist_sexage" width="950" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var margin = {top: 30, right: 30, bottom: 40, left: 30};
var width = document.getElementById("hist_sexage").getBoundingClientRect().width-50;
var height = 400;
var g = d3.select("#hist_sexage")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x0 = d3.scaleBand()
.rangeRound([0, width])
.paddingInner(0.2);
var x1 = d3.scaleBand()
.padding(0.1);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var z = d3.scaleOrdinal()
.range(["cornflowerblue", "orangered"]);
d3.csv("/blog/data/age_by_gender.csv",function(d, i, columns) {
for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = +d[columns[i]];
return d;
},
function(error, data) {
if (error) throw error;
var keys = data.columns.slice(1);
x0.domain(data.map(function(d) { return d.Age_Group; }));
x1.domain(keys).rangeRound([0, x0.bandwidth()]);
y.domain([0, d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); })]).nice();
g.append("g")
.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d) { return "translate(" + x0(d.Age_Group) + ",0)"; })
.selectAll("rect")
.data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })
.enter().append("rect").attr("class", "rect")
.attr("x", function(d) { return x1(d.key); })
.attr("y", function(d) { return y(d.value); })
.attr("width", x1.bandwidth())
.attr("height", function(d) { return height - y(d.value); })
.attr("fill", function(d) { return z(d.key); })
.on("mouseover", function() { tooltip.style("display", null); })
.on("mousemove", function(d) {
var xPosition = d3.mouse(this)[0] - 5;
var yPosition = d3.mouse(this)[1] - 5;
tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d.value);
console.log(d.value)
})
.on("mouseout", function() { tooltip.style("display", "none"); });
g.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x0))
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.1em")
.attr("transform", "rotate(-45)" );;
g.append("g")
.attr("class", "axis")
.call(d3.axisLeft(y).ticks(null, ".0%"))
.append("text")
.attr("x", 2)
.attr("y", y(y.ticks().pop()) + 0.5)
.attr("dy", "0.32em")
.attr("fill", "#000")
.attr("font-weight", "bold")
.attr("text-anchor", "start")
.text("Percentage");
var legend = g.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("text-anchor", "end")
.selectAll("g")
.data(keys.slice().reverse())
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 19)
.attr("width", 19)
.attr("height", 19)
.attr("fill", z);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9.5)
.attr("dy", "0.32em")
.text(function(d) { return d; });
});
// Prep the tooltip bits, initial display is hidden
var tooltip = d3.select("#hist_sexage").append("g")
.attr("class", "tooltip")
.style("display", "none");
tooltip.append("g:rect")
.attr("width", 60)
.attr("height", 20)
.attr("fill", "red")
.style("opacity", 0.5);
tooltip.append("g:text")
.attr("x", 30)
.attr("y", "1.2em")
.style("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold");
</script>
I am expecting to see it, if I move over the bar, it should show the number alongside with my cursor but it does not. Can you please help me troubleshoot this issue?
Thanks,
Well, you can't see the tooltip for a simple reason. You set its display to none...
.style("display", "none");
... but you forgot to change its style on mousemove. Therefore, its children will never be rendered.
Here is a working demo with fake data, changing the style in the mousemove:
var svg = d3.select("#hist_sexage");
var data = [30, 250, 120, 150, 90];
var rects = svg.selectAll("jamesWatson")
.data(data)
.enter()
.append("rect")
.attr("x", 0)
.attr("y", function(d, i) {
return i * 20
})
.attr("height", 15)
.attr("width", function(d) {
return d
})
.attr("fill", "teal")
.on("mousemove", function(d) {
var xPosition = d3.mouse(this)[0] + 10;
var yPosition = d3.mouse(this)[1] - 5;
tooltip.style("display", "inline")
.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d);
})
.on("mouseout", function() {
tooltip.style("display", "none");
});
var tooltip = d3.select("#hist_sexage").append("g")
.attr("class", "tooltip")
.style("display", "none");
tooltip.append("g:rect")
.attr("width", 60)
.attr("height", 20)
.attr("fill", "red")
.style("opacity", 0.5);
tooltip.append("g:text")
.attr("x", 30)
.attr("y", "1.2em")
.style("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold");
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg id="hist_sexage"></svg>
How would I need to modify the following code, which uses d3, to allow dragging of the graph along the x-axis:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
.axis path, .axis line {
fill: none;
stroke: #ddd;
stroke-width: 1px;
shape-rendering: crispEdges;
}
.axis path
{
stroke: #999;
stroke-width: 2px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://d3js.org/d3.v2.min.js?2.9.4"></script>
</head>
<body>
<div id="chart" class="background">
</div>
</body>
<script type="text/javascript">
var data = [{
Id: "1",
Year: 1950,
Relevance: 55,
Category: "Cat1",
SpecFreq: 5,
GenFreq: 10
}, {
Id: "2",
Year: 1975,
Relevance: 25,
Category: "Cat1",
SpecFreq: 2,
GenFreq: 31
}, {
Id: "1",
Year: 1990,
Relevance: 75,
Category: "Cat1",
SpecFreq: 8,
GenFreq: 23
}];
$(function () {
DrawFocus(data);
});
function DrawFocus(data) {
//dimensions
var margin = {
top: 5.5,
right: 19.5,
bottom: 39.5,
left: 39.5
},
width = 800 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
//data domain extents
var extentX = d3.extent(data, function (d) {
return d.Year;
});
var extentY = d3.extent(data, function (d) {
return d.Relevance;
});
//pad extents to provide some extra "blank" areas around edge of graph
extentX[0] = extentX[0] - 5;
extentX[1] = extentX[1] + 5;
extentY[0] = extentY[0] - 5;
extentY[1] = extentY[1] + 5;
//scales
var x = d3.scale.linear().domain(extentX).range([0, width]);
var y = d3.scale.linear().domain(extentY).range([height, 0]);
var radiusMax = .025 * width;
var radius = d3.scale.sqrt().domain([0, 100]).range([0, radiusMax]);
var color = d3.scale.ordinal().domain(["Cat1", "Cat2", "Cat3"]).range(["#b7b8a0", "#898a72", "#878772"]);
//axes
var xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(d3.format("d")).tickSize(-height);
var yAxis = d3.svg.axis().scale(y).orient("left").tickSize(-width);
//create and size svg element, add zoom behavior
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Add the x-axis.
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("font-size", "10px")
.attr("dy", "1.5em");
// Add the y-axis.
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
// Add the x-axis label.
svg.append("text")
.attr("class", "x label")
.attr("text-anchor", "end")
.attr("x", width / 2)
.attr("y", height + 35)
.text(" Year");
// Add the y-axis label.
svg.append("text")
.attr("class", "y label")
.attr("text-anchor", "end")
.attr("x", -1 * height / 2)
.attr("y", -40)
.attr("dy", ".75em")
.attr("transform", "rotate(-90)")
.text("Relevance");
//plot genFreq
var gGenerally = svg.append("g").selectAll("circle")
.data(data)
.enter().append("circle")
.style("fill", function (d) {
return color(d.Category);
})
.attr("cx", function (d) {
return x(d.Year);
})
.attr("cy", function (d) {
return y(d.Relevance);
})
.attr("r", function (d) {
return radius(d.GenFreq);
})
.append("title")
.text(function (d) {
return "(" + d.Year + ", " + d.Relevance + ", " + d.GenFreq + ", " + d.SpecFreq + ")";
});
//plot specFreq
var gWithin = svg.append("g").selectAll("circle")
.data(data)
.enter().append("circle")
.style("fill", function (d) {
return "#d6d487";
})
.attr("cx", function (d) {
return x(d.Year);
})
.attr("cy", function (d) {
return y(d.Relevance);
})
.attr("r", function (d) {
return radius(d.SpecFreq);
})
.append("title")
.text(function (d) {
return "(" + d.Year + ", " + d.Relevance + ", " + d.GenFreq + ", " + d.SpecFreq + ")";
});
return svg;
}
</script>
</html>
I've found several examples online and realize that I need to use the zoom behavior, but haven't been able to figure out precisely how to do it. There is a fiddle of the above code available.
Applying the zoom function as shown below, together with some additional code to restrict the zooming domain, was all I needed to do to get it to work. I do seem some odd "stickiness" going on once the graph has been scrolled to the far edge in any direction. It sometimes hesitates for a moment before scrolling back. I'm not sure what causes that. Also, this example is a bit unrealistic because I'm trimming my domain to match the min and max values in my data and then adding a +- 5 buffer. So, you can really only scroll that buffered area. However, I think it would behave just the same if you had a larger domain applied.
<html>
<head>
<style type="text/css">
.axis path, .axis line {
fill: none;
stroke: #ddd;
stroke-width: 1px;
shape-rendering: crispEdges;
}
.axis path
{
stroke: #999;
stroke-width: 2px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://d3js.org/d3.v2.min.js?2.9.4"></script>
</head>
<body>
<div id="chart" class="background">
</div>
</body>
<script type="text/javascript">
var data = [{
Id: "1",
Year: 1950,
Relevance: 55,
Category: "Cat1",
SpecFreq: 5,
GenFreq: 10
}, {
Id: "2",
Year: 1975,
Relevance: 25,
Category: "Cat1",
SpecFreq: 2,
GenFreq: 31
}, {
Id: "1",
Year: 1990,
Relevance: 75,
Category: "Cat1",
SpecFreq: 8,
GenFreq: 23
}];
$(function () {
DrawFocus(data);
});
function DrawFocus(data) {
//dimensions
var margin = {
top: 5.5,
right: 19.5,
bottom: 39.5,
left: 39.5
},
width = 800 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
//data domain extents
var extentX = d3.extent(data, function (d) {
return d.Year;
});
var extentY = d3.extent(data, function (d) {
return d.Relevance;
});
//pad extents to provide some extra "blank" areas around edge of graph
extentX[0] = extentX[0] - 5;
extentX[1] = extentX[1] + 5;
extentY[0] = extentY[0] - 5;
extentY[1] = extentY[1] + 5;
//scales
var x = d3.scale.linear().domain(extentX).range([0, width]);
var y = d3.scale.linear().domain(extentY).range([height, 0]);
var radiusMax = .025 * width;
var radius = d3.scale.sqrt().domain([0, 100]).range([0, radiusMax]);
var color = d3.scale.ordinal().domain(["Cat1", "Cat2", "Cat3"]).range(["#b7b8a0", "#898a72", "#878772"]);
//axes
var xAxis = d3.svg.axis().scale(x).orient("bottom").tickFormat(d3.format("d")).tickSize(-height).ticks(10);
var yAxis = d3.svg.axis().scale(y).orient("left").tickSize(-width).ticks(10);
//create and size svg element, add zoom behavior
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.call(d3.behavior.zoom().x(x).y(y).scaleExtent([1, 8]).on("zoom", zoom))
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Add the x-axis.
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("font-size", "10px")
.attr("dy", "1.5em");
// Add the y-axis.
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.selectAll("text")
.style("font-size", "10px")
.attr("dx", "-1em");
// Add the x-axis label.
svg.append("text")
.attr("class", "x label")
.attr("text-anchor", "end")
.attr("x", width / 2)
.attr("y", height + 35)
.text(" Year");
// Add the y-axis label.
svg.append("text")
.attr("class", "y label")
.attr("text-anchor", "end")
.attr("x", -1 * height / 2)
.attr("y", -40)
.attr("dy", ".75em")
.attr("transform", "rotate(-90)")
.text("Relevance");
//plot genFreq
var gGenerally = svg.append("g").selectAll("circle")
.data(data)
.enter().append("circle")
.style("fill", function (d) {
return color(d.Category);
})
.attr("cx", function (d) {
return x(d.Year);
})
.attr("cy", function (d) {
return y(d.Relevance);
})
.attr("r", function (d) {
return radius(d.GenFreq);
})
.append("title")
.text(function (d) {
return "(" + d.Year + ", " + d.Relevance + ", " + d.GenFreq + ", " + d.SpecFreq + ")";
});
//plot specFreq
var gWithin = svg.append("g").selectAll("circle")
.data(data)
.enter().append("circle")
.style("fill", function (d) {
return "#d6d487";
})
.attr("cx", function (d) {
return x(d.Year);
})
.attr("cy", function (d) {
return y(d.Relevance);
})
.attr("r", function (d) {
return radius(d.SpecFreq);
})
.append("title")
.text(function (d) {
return "(" + d.Year + ", " + d.Relevance + ", " + d.GenFreq + ", " + d.SpecFreq + ")";
});
function zoom() {
if (x.domain()[0] >= extentX[0] -5 && x.domain()[1] <= extentX[1] +5 && y.domain()[0] >= extentY[0] -5 && y.domain()[1] <= extentY[1] +5) {
svg.select(".x.axis").call(xAxis).selectAll("text")
.style("font-size", "10px")
.attr("dy", "1.5em");
svg.select(".y.axis").call(yAxis).selectAll("text")
.style("font-size", "10px")
.attr("dx", "-1em");
svg.selectAll("circle").attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
}
}
return svg;
}
</script>
</html>