Built with blockbuilder.org
This code will visualize data from a CSV via two objects: (1) a scatter plot of GF/GA with team code labels and (2) a mouseover that will tell additional details about the team data point
forked from eychang9's block: PLmouseover
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
</style>
</head>
<body>
<script>
var margin = {top: 75, left: 75, right: 75, bottom: 150};
var dataset = [];
// Create SVG element
var svgW = 700;
var svgH = 700;
// Create SVG
var svg = d3.select("body").append("svg")
.attr("width", svgW)
.attr("height", svgH);
// Create data parsing function
var rowConverter = function (d) {
return {
Team: d.Team,
TeamCode: d.TeamCode,
Place: parseInt(d.Place),
Record: d.Record,
GF: parseInt(d.GF),
GA: parseInt(d.GA),
Pts: parseInt(d.Pts),
Notes: d.Notes
};
};
// d3.csv function
d3.csv("201516PL.csv", rowConverter, function (data) {
var dataset = data;
// Generate GF(y)/GA(x) scatter plot
var xScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function (d) {
return d.GA;
})])
.range([margin.left, svgW-margin.right]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function (d) {
return d.GF;
})])
.range([svgH-margin.bottom, margin.top]);
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function (d) {
return xScale(d.GA);
})
.attr("cy", function (d) {
return yScale(d.GF);
})
.attr("r", 5)
.attr("fill", function (d) {
if (d.Notes === "CL") {
return "rgb(0,0,255)";
} else if (d.Notes === "EL") {
return "rgb(0,255,255)";
} else if (d.Notes === "R") {
return "rgb(255,0,0)";
} else {
return "black";
}
})
.on("mouseover", function (d) {
svg.append("text")
.attr("id", "detailText")
.attr("x", svgW/2)
.attr("y", svgH-(margin.bottom/2))
.attr("text-anchor", "middle")
.text(d.Place + ". " + d.Team + " " + d.Record);
d3.select(this)
.attr("fill", "orange")
})
.on("mouseout", function () {
d3.select(this)
.attr("fill", function (d) {
if (d.Notes === "CL") {
return "rgb(0,0,255)";
} else if (d.Notes === "EL") {
return "rgb(0,255,255)";
} else if (d.Notes === "R") {
return "rgb(255,0,0)";
} else {
return "black";
}
})
d3.select("#detailText").remove();
});
// Generate axes
var xAxis = d3.axisBottom(xScale);
var yAxis = d3.axisLeft(yScale);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (svgH-margin.bottom) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + margin.left + ",0)")
.call(yAxis);
// Label axes
svg.append("text")
.attr("x", svgW/2)
.attr("y", svgH-(margin.bottom/1.5))
.attr("text-anchor", "middle")
.text("Goals Against");
svg.append("text")
.attr("x", margin.left/2)
.attr("y", svgH/2)
.attr("text-anchor", "middle")
.attr("transform", "rotate(-90, " + (margin.left/2) + ", " + (svgH/2) + ")")
.text("Goals For");
});
</script>
</body>
https://d3js.org/d3.v4.min.js