function drawGraph(config) {
var x = d3.scale.ordinal()
.domain(config.data)
.rangeRoundBands([0, config.width], 0.2);
var y = d3.scale.linear()
.domain([0, d3.max(config.data)])
.range([0, config.height]);
var container = d3.select(config.container)
.append('div')
.attr('class', 'graph');
var svgElm = container
.append('svg')
.attr('width', config.width)
.attr('height', config.height);
var bar = svgElm.selectAll('.bar')
.data(config.data)
.enter()
.append('rect')
.style('fill', 'hsl(193, 100%, 50%)');
bar.attr('class', 'bar')
.attr('width', x.rangeBand())
.attr('height', y)
.attr('x', x)
.attr('y', function(d) {
return config.height - y(d);
});
}
/**
* The handle of the graph container
*/
var container = document.body.getElementsByClassName('graph-container')[0];
/**
*
* @param arrayLength - The length of the array
* @returns {Array}
*/
function dataGenerator(arrayLength) {
var dataArray = [];
for(var i=0; i<arrayLength; i++) {
var randomData = Math.random()*30;
dataArray.push(randomData);
}
return dataArray;
}
/**
* Configuration object to for the svg graph
* which is initialized with the width and
* height.
*
* @type {{width: number, height: number}}
*/
var configObj = {
width: 250,
height: 250
};
/**
* Generate a new graph on click
*/
document.body.getElementsByClassName('add')[0].addEventListener('click', function() {
var arraySize = 5;
configObj.container = container;
configObj.data = dataGenerator(arraySize);
drawGraph(configObj);
});
var arraySize = 5;
/**
* Create a data field and assign an array to display
* @type {Array}
*/
configObj.data = dataGenerator(arraySize);
/**
* Define a container object to append the graph
*
* @type...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.