Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="d3 bar chart horizontal bars">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
    <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
  <style>
        #barChart{
        font-size: 14px;
    }
    .bar {
      fill: steelblue;
    }
    .bar:hover {
      fill: brown;
    }
    .axis path,
    .axis line {
      fill: none;
      stroke: #000;
      shape-rendering: crispEdges;
    }
    .y.axis path {
      display: none;
    }
  </style>
</head>
<body>
  <svg id="barChart"></svg>
  
<script>
  var data = [
      {
        Product: "Shoes",
        Count: 5
      }, {
        Product: "Shirts",
        Count: 9
      }, {
        Product: "Pants",
        Count: 3
      }, {
        Product: "Ties",
        Count: 1
      }, {
        Product: "Socks",
        Count: 7
      }, {
        Product: "Jackets",
        Count: 2
      }];
  
  
  var margin = {
      top: 20,
      right: 20,
      bottom: 30,
      left: 40
    },
    width = 500 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;
  var x = d3.scale.linear()
    .range([0, 150]);
  var y = d3.scale.ordinal()
    .rangeRoundBands([height, 0], .1);
  var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .tickFormat(d3.format("d"))
    .tickSubdivide(0);
  var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");
  var svg = d3.select("svg#barChart")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + (margin.left + 250) + "," + margin.top + ")");
  x.domain([0, d3.max(data, function(d) {
    return d.Count;
  })]); 
  y.domain(data.map(function(d) {
    return d.Product;
  }));
  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .selectAll("text")
    .attr("x", -4)
    .attr("y", 15)
    .attr("dy", ".35em")
    .style("text-anchor", "start");
  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);
  svg.selectAll(".bar")
    .data(data)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", 0)
    .attr("width", function(d) {
      return x(d.Count);
    })
    .attr("y", function(d) {
      return y(d.Product);
    })
    .attr("height", y.rangeBand());
  </script>
</body>
</html>
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
eriksteinebachpro
0viewers