Button to change input data in barplot





This post describes how to build a button that changes the input dataset of a barplot. You need to understand how to draw a basic barplot first. It is a good way to understand the enter() and exit functions of d3.

Important note: This example does not update the X and Y axis, it works only if the 2 datasets have the same groups and same Y range. See here for an upgraded version


Barplot section

Steps:

  • First of all, understand how to build a basic barplot.

  • Add 2 buttons in the html part. When you click the button, a function called update() is triggered.

  • This update() function updates the value of the 3 groups

  • See here for more info on transition
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Add 2 buttons -->
<button onclick="update(data1)">Variable 1</button>
<button onclick="update(data2)">Variable 2</button>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

<script>

// create 2 data_set
var data1 = [
   {group: "A", value: 4},
   {group: "B", value: 16},
   {group: "C", value: 8}
];

var data2 = [
   {group: "A", value: 7},
   {group: "B", value: 1},
   {group: "C", value: 20}
];

// set the dimensions and margins of the graph
var margin = {top: 30, right: 30, bottom: 70, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

// X axis
var x = d3.scaleBand()
  .range([ 0, width ])
  .domain(data1.map(function(d) { return d.group; }))
  .padding(0.2);
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x))

// Add Y axis
var y = d3.scaleLinear()
  .domain([0, 20])
  .range([ height, 0]);
svg.append("g")
  .attr("class", "myYaxis")
  .call(d3.axisLeft(y));

// A function that create / update the plot for a given variable:
function update(data) {

  var u = svg.selectAll("rect")
    .data(data)

  u
    .enter()
    .append("rect")
    .merge(u)
    .transition()
    .duration(1000)
      .attr("x", function(d) { return x(d.group); })
      .attr("y", function(d) { return y(d.value); })
      .attr("width", x.bandwidth())
      .attr("height", function(d) { return height - y(d.value); })
      .attr("fill", "#69b3a2")
}

// Initialize the plot with the first dataset
update(data1)

</script>

Related blocks →

  • Simple bar graph in v4 - link

  • Let's make a bar chart - link