Skip to content

Instantly share code, notes, and snippets.

@DDDDDanica
Last active April 4, 2017 21:00
Show Gist options
  • Save DDDDDanica/37ca2212f3d3f65fa88d20d7691a1325 to your computer and use it in GitHub Desktop.
Save DDDDDanica/37ca2212f3d3f65fa88d20d7691a1325 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.7/d3.min.js"></script>
<style>
svg {
font: 12px sans-serif;
}
path.line {
fill: none;
stroke: #666;
stroke-width: 1.5px;
}
path.area {
fill: #e7e7e7;
}
.axis {
shape-rendering: crispEdges;
}
.x.axis line {
stroke: #fff;
}
.x.axis .minor {
stroke-opacity: .5;
}
.x.axis path {
display: none;
}
.y.axis line,
.y.axis path {
fill: none;
stroke: #000;
}
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
let mydata=[{"x": "A", "y": 1}, {"x": "B", "y": 2}, {"x": "C", "y": 3}, {"x": "D", "y": 4}, {"x": "E", "y": 5}, {"x": "F", "y": 8}];
let color = d3.scale.category10();
let margin ={top: 30, right:40, bottom: 40, left:40};
let width = 660 - margin.left -margin.right;
let height = 500 - margin.top - margin.bottom;
let svg = d3.select("body").append("svg")
.attr({
width: width + margin.left + margin.right,
height: height + margin.top + margin.bottom,
});
let g = svg.append('g')
.attr("transform", "translate("+ margin.left +","+margin.top +")");
let y_scale = d3.scale.linear()
.domain([0, d3.max(mydata.map((d)=>{return d.y}))])
.range([height,0]);
let x_scale = d3.scale.ordinal()
.domain(mydata.map((d) => {return d.x;}))
.rangeRoundBands([0,width], 0.2, 0.2);
let xAxis = d3.svg.axis()
.scale(x_scale)
.orient("bottom")
.tickPadding(6)
.tickSize(-2);
let yAxis = d3.svg.axis()
.scale(y_scale)
.orient("left")
.tickSize(-2);
let rectangules = g.selectAll('rect').data(mydata)
.enter().append('rect');
rectangules.attr({
x:function(d) { return x_scale(d.x); },
y:function(d) {return y_scale(d.y)},
height: (d, i) => {return height - y_scale(d.y); },
width:x_scale.rangeBand()
})
.style("fill", function(d, i) { return color(i)})
.style('fill-opacity', 0.6);
g.append("g")
.attr("class", "x axias")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
g.append("g")
.attr("class", "y axias")
.call(yAxis);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment