Skip to content

Instantly share code, notes, and snippets.

@curran
Last active February 21, 2017 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curran/647027d31e6001dddceeab4a28127cb3 to your computer and use it in GitHub Desktop.
Save curran/647027d31e6001dddceeab4a28127cb3 to your computer and use it in GitHub Desktop.
[UNLISTED] Pseudo Bar Chart V
license: mit
name value
A 5
B 4
C 3
D 2
E 1
<!DOCTYPE html>
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment