JSFiddle - React, Tailwind, and code Playground

by Muzaffar Rasulov

HTML

<h2>D3JS Simple JSON SVG barchart Horizontal with Axis</h2>
<i>using simple JSON data</i>
<br/> taken from <a href="https://bost.ocks.org/mike/bar/3/">https://bost.ocks.org/mike/bar/3/</a>
<br/>
<br/> A simple JSON store for your web or mobile app: <a target="_blank" href="http://myjson.com">myjson.com</a>
<br/>
<br/>
<div id="chart"></div>

CSS

#chart rect {
  fill: #4aaeea;
}

#chart text {
  fill: white;
  font: 10px sans-serif;
  text-anchor: end;
}

.axis text {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #fff;
  shape-rendering: crispEdges;
}

body {
  background: #1a1a1a;
  color: #eaeaea;
  padding: 10px;
}

JavaScript

var margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

// scale to ordinal because x axis is not numerical
var x = d3.scale.ordinal().rangeRoundBands([0, width], .1);

//scale to numerical value by height
var y = d3.scale.linear().range([height, 0]);

var chart = d3.select("#chart")
  .append("svg") //append svg element inside #chart
  .attr("width", width + (2 * margin.left) + margin.right) //set width
  .attr("height", height + margin.top + margin.bottom); //set height
var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom"); //orient bottom because x-axis will appear below the bars

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left");

d3.json("https://api.myjson.com/bins/4sw50", function(error, data) {
  x.domain(data.map(function(d) {
    return d.receive_date
  }));
  y.domain([0, d3.max(data, function(d) {
    return d.responses
  })]);

  var bar = chart.selectAll("g")
    .data(data)
    .enter()
    .append("g")
    .attr("transform", function(d, i) {
      return "translate(" + x(d.receive_date) + ", 0)";
    });

  bar.append("rect")
    .attr("y", function(d) {
      return y(d.responses);
    })
    .attr("x", function(d, i) {
      return x.rangeBand() + (margin.left / 2);
    })
    .attr("height", function(d) {
      return height - y(d.responses);
    })
    .attr("width", x.rangeBand()); //set width base on range on ordinal data

  bar.append("text")
    .attr("x", x.rangeBand() + margin.left)
    .attr("y", function(d) {
      return y(d.responses) - 10;
    })
    .attr("dy", ".75em")
    .text(function(d) {
      return d.responses;
    });

  chart.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(" + margin.left + "," + height + ")")
    .call(xAxis);

  chart.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + margin.left + ",0)")
    .call(yAxis)
    .append("text")
   ...