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 do I create a zoomable line chart using d3.js?
- How do I create a zoomable chart using d3.js?
- How do I create a graph using D3.js?
- How can I use d3.js to create a zoom scale?
- How do I use the z-index property with d3.js?
- How do I use D3.js to zoom on the x-axis?
- How do I use d3.js to create visualizations?
- How do I install and use D3.js with Yarn?
- How do I use d3.js to zoom to a selected area?
- How do I add y-axis lines to a chart in d3.js?
See more codes...