Changing barplot color with a button in d3.js

This post describes how to build a button that changes the color of a barplot. You need to understand how to draw a basic barplot first. It is a good way to understand how to build a button in html, and how to build a simple function in Javascript.

Barplot section


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

  • Add a button in the html part. Note the onclick attribute: it means that the changeColor() function will be triggered when you click on it

  • Create the changeColor() function in the Javascript part. It basically select all the rectangles of the plot and change their fill attribute.
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src=""></script>

<!-- Add 2 buttons -->
<button onclick="changeColor('blue')">Get blue</button>
<button onclick="changeColor('red')">Get red</button>

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


// 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.bottom;

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

// Parse the Data
d3.csv("", function(data) {

// X axis
var x = d3.scaleBand()
  .range([ 0, width ])
  .domain( { return d.Country; }))
  .attr("transform", "translate(0," + height + ")")
    .attr("transform", "translate(-10,0)rotate(-45)")
    .style("text-anchor", "end");

// Add Y axis
var y = d3.scaleLinear()
  .domain([0, 13000])
  .range([ height, 0]);

// Bars
    .attr("x", function(d) { return x(d.Country); })
    .attr("y", function(d) { return y(d.Value); })
    .attr("width", x.bandwidth())
    .attr("height", function(d) { return height - y(d.Value); })
    .attr("fill", "#69b3a2")


// This function is called by the buttons on top of the plot
function changeColor(color){
    .style("fill", color)


Related blocks →

  • Simple bar graph in v4 - link

  • Let's make a bar chart - link