Skip to content

Instantly share code, notes, and snippets.

@caravinden
Last active April 5, 2018 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save caravinden/eb0e5a2b38c8815919290fa838c6b63b to your computer and use it in GitHub Desktop.
Save caravinden/eb0e5a2b38c8815919290fa838c6b63b to your computer and use it in GitHub Desktop.
Horizontal Bar chart d3.v4
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar { fill: steelblue; }
</style>
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var data = [{"salesperson":"Bob","sales":33},{"salesperson":"Robin","sales":12},{"salesperson":"Anne","sales":41},{"salesperson":"Mark","sales":16},{"salesperson":"Joe","sales":59},{"salesperson":"Eve","sales":38},{"salesperson":"Karen","sales":21},{"salesperson":"Kirsty","sales":25},{"salesperson":"Chris","sales":30},{"salesperson":"Lisa","sales":47},{"salesperson":"Tom","sales":5},{"salesperson":"Stacy","sales":20},{"salesperson":"Charles","sales":13},{"salesperson":"Mary","sales":29}];
// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// set the ranges
var y = d3.scaleBand()
.range([height, 0])
.padding(0.1);
var x = d3.scaleLinear()
.range([0, width]);
// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").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 + ")");
// format the data
data.forEach(function(d) {
d.sales = +d.sales;
});
// Scale the range of the data in the domains
x.domain([0, d3.max(data, function(d){ return d.sales; })])
y.domain(data.map(function(d) { return d.salesperson; }));
//y.domain([0, d3.max(data, function(d) { return d.sales; })]);
// append the rectangles for the bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
//.attr("x", function(d) { return x(d.sales); })
.attr("width", function(d) {return x(d.sales); } )
.attr("y", function(d) { return y(d.salesperson); })
.attr("height", y.bandwidth());
// add the x Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// add the y Axis
svg.append("g")
.call(d3.axisLeft(y));
</script>
</body>
@911neo
Copy link

911neo commented Dec 10, 2016

Hello caravinden i have been using your horizontal bar chart for a assignment and it works good , lately i have added a select option to filter it by selected value could you please show me how to update your bar values based on select option value it would be a greate help :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment