javascript-d3How to create a Gantt chart using D3.js?
Creating a Gantt chart using D3.js is a great way to visualize project timelines and progress. The following example code uses D3.js to create a Gantt chart:
// Create SVG
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
// Create scales
var xScale = d3.scaleTime()
.domain([d3.min(data, d => d.startTime), d3.max(data, d => d.endTime)])
.range([0, width]);
var yScale = d3.scaleBand()
.domain(data.map(d => d.name))
.range([0, height]);
// Create Gantt chart
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", d => xScale(d.startTime))
.attr("y", d => yScale(d.name))
.attr("width", d => xScale(d.endTime) - xScale(d.startTime))
.attr("height", yScale.bandwidth());
This code will create an SVG element, create two scales (xScale and yScale) to map data values to the chart's x and y axes, and then create a Gantt chart by appending rectangles to the SVG element. The rectangles are positioned using the x and y scales, and their width and height are based on the data's start and end times.
The code consists of the following parts:
- Creation of SVG element:
var svg = d3.select("body").append("svg").attr("width", width).attr("height", height);
- Creation of xScale:
var xScale = d3.scaleTime().domain([d3.min(data, d => d.startTime), d3.max(data, d => d.endTime)]).range([0, width]);
- Creation of yScale:
var yScale = d3.scaleBand().domain(data.map(d => d.name)).range([0, height]);
- Creation of Gantt chart:
svg.selectAll("rect").data(data).enter().append("rect").attr("x", d => xScale(d.startTime)).attr("y", d => yScale(d.name)).attr("width", d => xScale(d.endTime) - xScale(d.startTime)).attr("height", yScale.bandwidth());
For more information on creating Gantt charts using D3.js, please see the following links:
More of Javascript D3
- How can I display Unix time using d3.js?
- How can I use D3.js to create interactive visualizations on Udemy?
- How do I use D3.js to zoom on the x-axis?
- How do I set up the x axis in d3.js?
- What is the purpose of using d3.js?
- How do I create a zoomable line chart using d3.js?
- How do I use d3.js to zoom to a selected area?
- How do I create a zoomable chart using d3.js?
- How can I use d3.js to create a zoom scale?
- How do I implement zooming in a d3.js visualization?
See more codes...