Skip to content

Instantly share code, notes, and snippets.

@anndoko anndoko/barchart.js
Created Oct 8, 2018

Embed
What would you like to do?
var dataitems = [];
var names = [];
$(document).ready(function () {
loadData();
});
// Loads the CSV file
function loadData() {
// load the demographics.csv file
d3.csv("data/candy-data.csv", function (d){
dataitems = d;
visualizeData(dataitems);
});
}
function visualizeData(dataitems) {
var margin = { top: 100, right: 100, bottom: 200, left: 100 },
width = 1000 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scaleBand()
.domain(dataitems.map(function (d) { return d.competitorname; }))
.range([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.domain([0, d3.max(dataitems, function (d) { return d.winpercent; })])
.range([height, 0]);
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 + ")");
svg.selectAll(".bar")
.data(dataitems)
.enter().append("rect")
.attr("class", "bar")
.attr("fill", "grey")
.attr("x", function (d) { return x(d.competitorname); })
.attr("width", x.bandwidth())
.attr("y", function (d) { return y(d.winpercent); })
.attr("height", function (d) { return height - y(d.winpercent); })
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", "rotate(-65)");
// add the y Axis
svg.append("g")
.call(d3.axisLeft(y));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.