Answers for "how to make a bar graph in JS"

0

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);
Posted by: Guest on June-02-2021

Code answers related to "how to make a bar graph in JS"

Browse Popular Code Answers by Language