Skip to content

Instantly share code, notes, and snippets.

@jamesleesaunders
Last active September 23, 2017 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesleesaunders/4a00b5ce64c64c494bcb to your computer and use it in GitHub Desktop.
Save jamesleesaunders/4a00b5ce64c64c494bcb to your computer and use it in GitHub Desktop.
D3 : Random Colours Using rgb() - Column Chart

Ramdom Colours Using rgb() - Column Chart

In this example we generate another data array of random numbers. Then we generate a basic DIV based column chart using the random number to dictate the column height and colour (note the correct English spelling for colour.. not color!).

Colours can be references in a few different ways:

  • #ff0000
  • rgb(255,0,0)
  • 'red'
<!DOCTYPE html>
<html>
<head>
<title>D3 : Ramdom Colours Using rgb() - Column Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script>
<style type="text/css">
#chartholder {
height: 400px;
width: 600px;
}
.bar {
display: inline-block;
width: 50px;
height: 10px;
margin-right: 2px;
background-color: teal;
}
</style>
</head>
<body>
<div id="chartholder"></div>
<script type="text/javascript">
var data = d3.range(10).map(function () {
return Math.random();
});
var html = d3.select('#chartholder').selectAll('div')
.data(data)
.enter()
.append('div')
.attr('class', 'bar')
.style('height', function (d) {
return d * 400 + 'px';
})
.style('background-color', function (d) {
return "rgb(0, 0, " + (Math.round(d * 200)) + ")";
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment