Sunday, October 21, 2018

Bar chart with d3.js library - vertical bar chart

Bar Chart

This article contains how to draw a vertical bar graph with d3 JS library. It contains a static data set. You can assign dynamic values and colors using php or any other appropriate language

Click to view Reference
Click to view official website


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Bar Chart</title>

 <style>
  html, body, #barchart { margin: 0; height: 100% }
  /*Rectangle bar class styling*/
  /*.bar { fill: #0080FF }*/
  .bar:hover { fill: #003366 }
  /*Text class styling*/
  /*.text { fill: white; font-family: sans-serif }*/
 </style>

    <!-- Reference minified version of D3 -->
    <script type="text/javascript" src="https://d3js.org/d3.v3.min.js"></script>
  </head>

  <body>
 <div id="barchart">
 </div>
    <script>
  // Create data array of values to visualize
  var dataArray = [63, 61, 54];
  var colArray = ["red","green","blue"];
  var txtArray = ["text1","text2","text3"];
  
  // Create variable for the SVG
  var svg = d3.select("#barchart").append("svg")
   .attr("height","100%")
   .attr("width","100%");

  // Select, append to SVG, and add attributes to rectangles for bar chart
  svg.selectAll("rect") // d=data, i=index
   .data(dataArray)
   .enter().append("rect")
   .attr("class", "bar")
   .style("fill", function(d, i){ return colArray[i]; })
   .attr("height", function(d, i) {return (d * 1)})
   .attr("width","40")
   .attr("x", function(d, i) {return (i * 60) + 25})
   .attr("y", function(d, i) {return 100 - (d * 1)});

  // Select, append to SVG, and add attributes to text
  svg.selectAll("text")
           .data(dataArray)
           .enter().append("text")
    .text(function(d) {return d+"%"})
           .attr("class", "text")
           .style("fill", function(d, i){ return colArray[i]; })
           .attr("x", function(d, i) {return (i * 60) + 36})
           .attr("y", function(d, i) {return 120 });
  
   svg.selectAll("text2")
           .data(dataArray)
    .enter().append("text")
    .text(function(d, i) {return txtArray[i]})
           .attr("class", "text")
    .style("fill", function(d, i){ return colArray[i]; })
           .attr("x", function(d, i) {return (i * 60) + 30})
           .attr("y", function(d, i) {return 135 });

 </script>
  </body>
</html>


No comments:

Post a Comment