Home > Web Front-end > JS Tutorial > Creating Simple Line and Bar Charts Using D3.js

Creating Simple Line and Bar Charts Using D3.js

Lisa Kudrow
Release: 2025-02-21 11:20:15
Original
373 people have browsed it

Creating Simple Line and Bar Charts Using D3.js

This article builds upon a previous tutorial on bubble charts using D3.js, a JavaScript library for data visualization. We'll now explore creating line and bar charts with D3.js, leveraging HTML, SVG, and CSS. Familiarity with the previous article is recommended. Key takeaways include understanding D3.js's role in interactive visualizations, the mechanics of line chart creation (scales, axes, line generators), bar chart construction (ordinal scales, rectangles), and enhancing user experience through interactivity (tooltips, event handlers, transitions). Customization options, such as axis scaling and styling, are also highlighted.

Line Charts: A Step-by-Step Guide

Our example uses the following dataset:

var lineData = [{x: 1, y: 5}, {x: 20, y: 20}, {x: 40, y: 10}, {x: 60, y: 40}, {x: 80, y: 5}, {x: 100, y: 60}];
Copy after login

And an SVG element:

<svg id="visualisation" width="1000" height="500"></svg>
Copy after login

We define scales, axes, and margins:

var vis = d3.select('#visualisation'),
    WIDTH = 1000,
    HEIGHT = 500,
    MARGINS = {top: 20, right: 20, bottom: 20, left: 50},
    xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(lineData, function(d) { return d.x; }), d3.max(lineData, function(d) { return d.x; })]),
    yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(lineData, function(d) { return d.y; }), d3.max(lineData, function(d) { return d.y; })]),
    xAxis = d3.svg.axis().scale(xRange).tickSize(5).tickSubdivide(true),
    yAxis = d3.svg.axis().scale(yRange).tickSize(5).orient('left').tickSubdivide(true);

vis.append('svg:g').attr('class', 'x axis').attr('transform', 'translate(0,' + (HEIGHT - MARGINS.bottom) + ')').call(xAxis);
vis.append('svg:g').attr('class', 'y axis').attr('transform', 'translate(' + (MARGINS.left) + ',0)').call(yAxis);
Copy after login

A line generator function is then created:

var lineFunc = d3.svg.line()
  .x(function(d) { return xRange(d.x); })
  .y(function(d) { return yRange(d.y); })
  .interpolate('linear');
Copy after login

Finally, the line is appended to the SVG:

vis.append('svg:path')
  .attr('d', lineFunc(lineData))
  .attr('stroke', 'blue')
  .attr('stroke-width', 2)
  .attr('fill', 'none');
Copy after login

Bar Charts: Building on the Foundation

For bar charts, we reuse the axis creation but modify the scales and add rectangles:

function InitChart() {
  // ... (barData remains the same as lineData, for simplicity) ...
  var xRange = d3.scale.ordinal().rangeRoundBands([MARGINS.left, WIDTH - MARGINS.right], 0.1).domain(barData.map(function(d) { return d.x; }));
  var yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0, d3.max(barData, function(d) { return d.y; })]);
  // ... (xAxis and yAxis remain the same) ...

  vis.selectAll('rect')
    .data(barData)
    .enter()
    .append('rect')
    .attr('x', function(d) { return xRange(d.x); })
    .attr('y', function(d) { return yRange(d.y); })
    .attr('width', xRange.rangeBand())
    .attr('height', function(d) { return ((HEIGHT - MARGINS.bottom) - yRange(d.y)); })
    .attr('fill', 'grey')
    .on('mouseover', function(d) { d3.select(this).attr('fill', 'blue'); })
    .on('mouseout', function(d) { d3.select(this).attr('fill', 'grey'); });
}

InitChart();
Copy after login

This enhanced example includes mouseover and mouseout event handlers for interactivity. Further customization and advanced techniques are possible with D3.js, allowing for highly tailored and dynamic data visualizations. The provided FAQs section offers further guidance on adding labels, tooltips, responsiveness, animations, sorting, titles, legends, and handling missing data.

The above is the detailed content of Creating Simple Line and Bar Charts Using D3.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template