A pseudo-bar chart demonstrating the D3 Towards Reusable Charts pattern. Uses:
Built with blockbuilder.org
forked from curran's block: Pseudo Bar Chart IV
xxxxxxxxxx
<html>
<head>
<meta charset="utf-8">
<title>Pseudo Bar Chart IV</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<svg id="bar-chart"></svg>
<script>
function BarChart(){
var width,
height,
xScale = d3.scaleBand(),
yScale = d3.scaleLinear(),
x,
y;
function my(selection){
if(!x) throw new Error("Bar Chart x column must be defined.");
if(!y) throw new Error("Bar Chart y column must be defined.");
if(!width) throw new Error("Bar Chart width must be defined.");
if(!height) throw new Error("Bar Chart height must be defined.");
selection.each(function(data) {
var svg = d3.select(this)
.attr("width", width)
.attr("height", height);
xScale
.domain(data.map(function (d){ return d[x]; }))
.range([0, width]);
yScale
.domain([0, d3.max(data, function (d){ return d[y] })])
.range([height, 0]);
var rects = svg.selectAll("rect")
.data(data);
rects.exit().remove();
rects.enter().append("rect")
.merge(rects)
.attr("x", function (d){ return xScale(d[x]); })
.attr("y", function (d){ return yScale(d[y]); })
.attr("width", xScale.bandwidth())
.attr("height", function (d){ return height - yScale(d[y]); });
});
}
my.x = function (_){
return arguments.length ? (x = _, my) : x;
};
my.y = function (_){
return arguments.length ? (y = _, my) : y;
};
my.width = function (_){
return arguments.length ? (width = _, my) : width;
};
my.height = function (_){
return arguments.length ? (height = _, my) : height;
};
my.padding = function (_){
return arguments.length ? (xScale.padding(_), my) : xScale.padding();
};
return my;
}
function main(){
var barChart = BarChart()
.width(960)
.height(500)
.x("name")
.y("value")
.padding(0.1);
function parseRow(d){
d.value = +d.value; // Parses String to Number.
return d;
}
d3.csv("data.csv", parseRow, function (data){
d3.select("#bar-chart")
.datum(data)
.call(barChart);
});
}
main();
</script>
</body>
</html>
https://d3js.org/d3.v4.min.js