How to create line chart with json data using d3.js?

Member

by darion , in category: Javascript , 5 months ago

How to create line chart with json data using d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 5 months ago

@darion 

To create a line chart with JSON data using d3.js, you can follow these steps:

  1. Include the d3.js library in your HTML file:
1
<script src="https://d3js.org/d3.v7.min.js"></script>


  1. Create a container for the line chart in your HTML file:
1
<div id="chart"></div>


  1. Create a JavaScript file and write the code to fetch the JSON data and create the line chart:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Fetch the JSON data
d3.json("data.json").then(function(data) {
    // Set the dimensions and margins of the chart
    var margin = {top: 20, right: 30, bottom: 30, left: 50},
        width = 600 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;

    // Append the SVG object to the chart div
    var svg = d3.select("#chart")
                .append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform",
                      "translate(" + margin.left + "," + margin.top + ")");

    // X scale and axis
    var x = d3.scaleLinear()
              .domain([0, d3.max(data, function(d) { return d.x; })])
              .range([0, width]);
    svg.append("g")
       .attr("transform", "translate(0," + height + ")")
       .call(d3.axisBottom(x));

    // Y scale and axis
    var y = d3.scaleLinear()
              .domain([0, d3.max(data, function(d) { return d.y; })])
              .range([height, 0]);
    svg.append("g")
       .call(d3.axisLeft(y));

    // Create a line generator
    var line = d3.line()
                 .x(function(d) { return x(d.x); })
                 .y(function(d) { return y(d.y); });

    // Add the line to the chart
    svg.append("path")
       .datum(data)
       .attr("fill", "none")
       .attr("stroke", "steelblue")
       .attr("stroke-width", 2)
       .attr("d", line);
});


  1. Create a JSON file (data.json) with the data for the line chart:
1
2
3
4
5
6
7
8
[
    {"x": 0, "y": 10},
    {"x": 1, "y": 20},
    {"x": 2, "y": 15},
    {"x": 3, "y": 25},
    {"x": 4, "y": 18},
    {"x": 5, "y": 30}
]


  1. Load the JavaScript file in your HTML file:
1
<script src="script.js"></script>


  1. Open your HTML file in a web browser to view the line chart with JSON data.


This is a basic example of creating a line chart with JSON data using d3.js. You can customize the chart further by adding labels, tooltips, legends, and other features as needed.