Grouped Bar charts.
Simple tutorial for creation of d3 grouped bar charts.
by torresomar
HTML
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="grouped-bar" class="grouped-bar">
</div>
JavaScript
// Define the SVG dimensions.
const margin = {
top: 25,
right: 25,
bottom: 25,
left: 25
}
const height = 310;
const width = 650;
// Use the select library to transform the DOM by selecting our node and appending a new SVG one with certain modifications
const svg = d3.select('#grouped-bar') // Using the id of the div in our html template
.append('svg')
.attr('class', 'grouped-bars-svg')
.attr('height', height)
.attr('width', width)
.style('background', '#fff');
// Create an object with the color mappings rating_key => color
const colors = {
all: '#CFDFA9',
top: '#F2DA8E',
audience: '#EA9485'
}
// Append a g element into our SVG
const main = svg.append('g')
.attr('class', 'grouped-bars-main-group')
.attr('transform', `translate(${margin.left},${margin.top})`);
// Make a request to obtain our dataset
fetch('https://s3-us-west-2.amazonaws.com/data.kryptophsky.com/01-grouped-bar-charts-d3/movies.json')
.then(res => { return res.json() })
.then(renderGraph)
.catch(err => { console.log('Error...', err) });
function renderGraph(data) {
// TODO
const xDomain = data.map(movie => { return movie.key });
const xScale = d3.scaleBand().domain(xDomain);
xScale.range([0, width - margin.left - margin.right]);
const yScale = d3.scaleLinear().domain([0, 100]);
yScale.range([height - margin.top - margin.bottom, 0]);
const ratingsScale = d3.scaleBand().domain(['all', 'top', 'audience']);
ratingsScale.range([0, xScale.bandwidth()]);
ratingsScale.round(true).paddingInner(0.15).paddingOuter(0.95);
const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);
const yGrid = d3.axisLeft(yScale).tickSize(-width + margin.left + margin.right);
main.append('g')
.attr('class', 'grouped-bar-chart grid y-grid')
.attr('transform', `translate(0, 0)`)
.call(yGrid)
.selectAll('text')
.remove();
main.append('g')
.attr('class', 'grouped-bar-chart axis x-axis')
.attr('transform',...