Skip to content

Instantly share code, notes, and snippets.

@lucyycao
Created March 2, 2017 20:22
Show Gist options
  • Save lucyycao/4c283b748591967f7450b8fb08253623 to your computer and use it in GitHub Desktop.
Save lucyycao/4c283b748591967f7450b8fb08253623 to your computer and use it in GitHub Desktop.
Bar Chart
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<style> body {margin:0;position:fixed; top:0; right:0; left:0; bottom:0;} </style>
</head>
<body>
<script>
var data = [1,2,3,4,5,6]
var colors = ['#e74c3c', '#f1c40f', '#2ecc71','#2ecc71','#2ecc71'];
var othercolors = d3.scale.category10()
var alldata = [{x: "A", y:100, colors: "red"}, {x: "B", y:200, colors: "green"}]
var margin={top: 20, bottom: 20, left: 50, right: 20};
var svgHeight=400;
var svgWidth=800;
var chartHeight=svgHeight-margin.top-margin.bottom;
var chartWidth=svgWidth-margin.left-margin.right;
var svg = d3.select("body").append("svg")
.attr({
width:svgWidth,
height:svgHeight
})
//scale
var yScale = d3.scale.linear().domain([0,200]).range([chartHeight, 0]);
var xScale = d3.scale.ordinal().domain(["A","B"]).rangeRoundBands([0,chartWidth], 0.2, 0.2);
//axis
var xAxis = d3.svg.axis().orient("bottom").scale(xScale);
var yAxis = d3.svg.axis().orient("left").scale(yScale);
var chartGroup = svg.append("g")
.attr("class", "chartArea")
.attr("transform", "translate("+margin.left + "," + margin.top + ")");
//x axis
chartGroup.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0, "+ chartHeight + ")")
.call(xAxis);
//y axis
chartGroup.append("g")
.attr("class", "y axis")
.attr("transform", "translate(0, "+ 0 + ")")
.call(yAxis);
var bars = chartGroup.selectAll("rect").data(alldata);
bars.enter().append("rect")
.attr({
x: function(d,i) {return xScale(d.x)},
y: function(d,i){return yScale(d.y)},
height: function(d,i) {return chartHeight - yScale(d.y)},
width: xScale.rangeBand()
})
.style("fill", function(d,i){ return othercolors(i)})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment