This line chart is constructed from a TSV file storing the daily average temperatures of New York, San Francisco and Austin over the last year. The chart employs conventional margins and a number of D3 features:
forked from mbostock's block: Lab 7 - Interactivity
forked from ngchwanlii's block: Lab 7 - Interactivity
forked from Thanaporn-sk's block: Lab 7 - Interactivity
xxxxxxxxxx
<meta charset="utf-8">
<style>
.axis--x path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
.focus text {
text-anchor: middle;
text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
}
.voronoi path {
fill: none;
pointer-events: all;
}
.voronoi--show path {
stroke: red;
stroke-opacity: 0.2;
}
.city--hover {
stroke: #000;
}
#form {
position: absolute;
top: 20px;
right: 30px;
}
</style>
<svg width="960" height="500"></svg>
<label id="form" for="show-voronoi">
Show Voronoi
<input type="checkbox" id="show-voronoi" disabled>
</label>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 80, bottom: 30, left: 50},
width = svg.attr("width") - margin.left - 2 * margin.right, // set the line plot area slightly compacted to the left, so that the hover/click effect of text won't overlapped
height = svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", translate(margin.left, margin.top));
// voronoi global variable, focus for hovering + zooming
var voronoiGroup, focus;
// setup clip path (for limiting zoom)
g.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var parseTime = d3.timeParse("%Y%m%d");
// use for general linking in between click event and mouse-over event
var clickedStates = d3.map();
var x = d3.scaleTime().range([0, width]),
y = d3.scaleLinear().range([height, 0]),
z = d3.scaleOrdinal(d3.schemeCategory10),
xz = x; // used for scaling x position when zoom, initially set as x, if zoomed, the d3.event.rescaleX will be set as this
// voronoi: data binded by d.values from cities -> each city's d.values
var voronoi = d3.voronoi()
.x(function(d) {return xz(d.date); })
.y(function(d) {return y(d.temperature); })
// set voronoi area EXACTLY fit with the line point max min boundary
.extent([[xz(x.domain()[0]) , y(y.domain()[1])], [xz(x.domain()[1]), y(y.domain()[0])]]);
var line = d3.line()
.curve(d3.curveBasis)
.x(function(d) { return xz(d.date); })
.y(function(d) { return y(d.temperature); });
// for hovering effect -> circle in voronoi
focus = g.append("g")
.attr("class", "focus")
// .attr("clip-path","url(#clip)")
.attr("transform", translate(-100,-100));
focus.append("circle")
.attr("r", 3.5)
.attr("fill", "red")
.attr("stroke", "black")
.attr("stroke-width", 3);
focus.append("text")
.attr("y", -10);
// zoom effect
var zoom = d3.zoom()
.scaleExtent([1 / 4, 15000])
// change with the scaledX position - use xz!!!
.translateExtent([[xz(xz.domain()[0]), -Infinity], [xz(xz.domain()[1])+200, Infinity]])
.on("zoom", zoomed);
d3.tsv("data.tsv", type, function(error, data) {
if (error) throw error;
// zoom effect setup
cities = data.columns.slice(1).map(function(id) {
return {
id: id,
values: data.map(function(d) {
return {date: d.date, temperature: d[id]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(cities, function(c) { return d3.min(c.values, function(d) { return d.temperature; }); }),
d3.max(cities, function(c) { return d3.max(c.values, function(d) { return d.temperature; }); })
]);
z.domain(cities.map(function(c) { return c.id; }));
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", translate(0, height))
.call(d3.axisBottom(x));
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.61em")
.attr("dx", "1.8em")
.attr("fill", "#000")
.text("Temperature, ºF");
var city = g.selectAll(".city")
.data(cities)
.enter()
.append("g")
// add id on each cities (easier in selecting)
.attr("id", function(d){return formatLetter(d.id)}) // use formatLetter (consider edge case like San Francisco, San Bruno, San Jose etc.)
.attr("class", "city");
// use a easier draw path function
drawPath(city);
// setup voronoi data
cities.map(function(c1){
c1.values.forEach(function(c2){
// set line associate with each values
c2.city = {line: c1.line, values: c1.values, name: c1.id};
})
})
city.append("text")
.datum(function(d) { return {id: d.id, value: d.values[d.values.length - 1]}; })
// add text offset // zxc
.attr("transform", function(d) { return translate(xz(d.value.date)+30, y(d.value.temperature))})
.attr("x", 3)
.attr("dy", "0.35em")
.style("font", "10px sans-serif")
.style("cursor", "pointer")
.text(function(d) { return d.id; })
.on("click", function(d){
var onClick = d3.select(this).classed("onClick");
if(!onClick){
clickedStates.set(this.parentNode.id, true);
g.select("#"+this.parentNode.id).select("path").remove();
}
else {
clickedStates.remove(this.parentNode.id);
// update path line
drawPath(g.select("#"+ this.parentNode.id));
}
// toogle on/off flag
d3.select(this).classed("onClick", !onClick);
})
.on("mouseover", function(d){
// if this path is not disabled, bring this line to front, color other line to gray
var onClick = d3.select(this).classed("onClick");
if(!onClick){
g.select("#"+ this.parentNode.id).raise();
g.selectAll(".city").filter(function(c){
// return city that is not hover
return d.id != c.id;
})
.select("path")
.style("stroke", "lightgray");
}
})
.on("mouseout", function(d){
// resume all cities line color
g.selectAll(".city")
.select("path")
.style("stroke", function(city){
return z(city.id);
})
})
// create voronoi group
voronoiGroup = g.append("g")
.attr("class", "voronoi")
// clip the zoom area
.attr("clip-path","url(#clip)")
.style("pointer-events", "all");
// for setting up voronoi group
drawVoronoi();
// show voronoi option - check the voronoi area
// Debug Issues: (adjust voronoi width to enabled text hovering/click effect). Previously the voronoi area overlapped text
d3.select("#show-voronoi")
.property("disabled", false)
.on("change", function() { voronoiGroup.classed("voronoi--show", this.checked); });
});
function drawVoronoi(){
// merge all lines' points' values
all = d3.merge(cities.map(function(d) {return d.values;}));
voronoiGroup.selectAll("path")
.data(voronoi.polygons(all))
.enter()
.append("path")
.attr("class", function(d) {
try {
return formatLetter(d.data.city.name);
}catch (e) {}
})
// .attr("id", function(d){return formatLetter(d.id)})
.attr("d", function(d) {return d ? "M" + d.join("L") + "Z" : null;})
.on("mouseover", function(d) {
try {
// get class name of this path
if(!clickedStates.has(this.className.baseVal)){
// if scaled x mouseover out of plot boundaries, don't show the hover effect
if(!(xz(d.data.date) < x.range()[0]) && !(xz(d.data.date) > x.range()[1])){
// transform the focus (label for city and temperature)
focus.attr("transform", translate(xz(d.data.date), y(d.data.temperature)));
// draw city name and temperature
focus.select("text")
.style("font-size", 9)
.style("font-weight", "bolder")
.attr("dy", -5)
// "\u00A0" = add spacebar
.text(d.data.city.name + "\u00A0" + "\u00A0" + d.data.temperature + "ºF");
// use hover class
d3.select(d.data.city.line).classed("city--hover", true);
// add as the last child
d.data.city.line.parentNode.appendChild(d.data.city.line);
// raise the text above all the line!
focus.raise();
}
}
}catch (e){}
})
.on("mouseout", function(d) {
d3.select(d.data.city.line).classed("city--hover", false);
focus.attr("transform", translate(-100, -100));
})
.call(zoom);
}
// zoom function
function zoomed() {
// rescale x position
xz = d3.event.transform.rescaleX(x);
// x axis change when zoom
g.select(".axis--x")
.call(d3.axisBottom(x).scale(xz));
// redraw new path when zooming
g.selectAll(".city").selectAll("path.line")
.attr("d", function(d){return line(d.values)});
}
// easier for drawing path, based on pass in elem
function drawPath(elem) {
elem.append("path")
.attr("class", "line")
.attr("d", function(d) {d.line = this; return line(d.values);})
.attr("clip-path", "url(#clip)")
.style("fill", "none")
.style("stroke", function(d) { return z(d.id); });
}
// for formatting id values
function formatLetter(state){
return state.replace(/[^a-zA-Z]/g, "_");
}
function type(d, _, columns) {
d.date = parseTime(d.date);
for (var i = 1, n = columns.length, col; i < n; ++i){
d[col = columns[i]] = +d[col];
}
return d;
}
function translate(x, y) {
return "translate(" + String(x) + "," + String(y) + ")";
}
</script>
https://d3js.org/d3.v4.min.js