how to make a bar graph in JS code example

Example: how to make a bar graph in JS

const g = document.getElementById("graph");

const graphData = {
  title: "Wild Animals in Istanbul",
  yAxis: "population",
  data: [{
      name: "pigeon",
      value: 30,
      color: "red"
    },
    {
      name: "wolf",
      value: 20,
      color: "blue"
    }
  ]
}

function createGraphIn(g, graphData) {
  var yAxisName = graphData.yAxis;
  var yAxis = document.createElement("div");
  var yAxisContainer = document.createElement("div");
  yAxis.classList.add('y-axis');
  yAxisContainer.classList.add('y-axis-container');
  yAxis.innerText = yAxisName;
  yAxisContainer.appendChild(yAxis);
  g.appendChild(yAxisContainer);
  
  const numOfBars = graphData.data.length;
  var barContainer = document.createElement("div");
  barContainer.classList.add("bar-container");
  for (var i = 0; i < numOfBars; i++) {
    var currentData = graphData.data[i];
    
    var bar = document.createElement("div");
    bar.classList.add('bar');
    bar.style.backgroundColor = currentData.color;
    bar.style.height = currentData.value + "px";
    barContainer.appendChild(bar);
    
    var barDescription = document.createElement("p");
    barDescription.classList.add('desc');
    barDescription.innerText = currentData.name;
    bar.appendChild(barDescription);
  }
  g.appendChild(barContainer); 
}
createGraphIn(g, graphData);

Tags:

Misc Example