.imalgam.
Posted 2/28/2022
Line Graph
A simple canvas implementation of a 2-d line graph
Source Code
This is the first of a series of postings demonstrating basic JavaScript implementations of charts and graphs. Imalgam is creating visualization tools to aid with projects under development, and some of the results will be shared here.
Samples
Below are sample renderings using the LineGraph JavaScript class. In the first case (Square Root), the data source is a list of (x, y) values, and in the second case (Sine function) the data source is a JavaScript lambda function characterizing the values of y as a function of x.
Square Root
    const data = [];
    for (let i = 0; i < 200; i++) {
        data.push([i/20.0, Math.pow(i/20.0,0.5)]);
    }
    new LineGraph(
        {"title": "y = f(x) = Math.pow(x, 0.5)",
         "legend": {"x": "X value", "y": "Y value"},
         "data": data
        }
    ).renderTo(document.getElementById("squareRootCanvas"));
                            
Sine function
    new LineGraph(
        {"title": "y = f(x) = Math.sin(x)",
        "legend": {"x": "X value", "y": "Y value"},
        "dataFunction": a => Math.sin(a),
        "min": 0.0,
        "max": 9.0
        }
    ).renderTo(document.getElementById("sineCanvas"));
                        
Usage
The LineGraph class has two externally consumed methods, the constructor and renderTo. The constructor takes as its argument the graph's configuration, described in detail below. The renderTo method takes as its argument a canvas object in the DOM where the graph is rendered. The constructor does not copy/clone the configuration object, so that any changes to the configuration object passed to the constructor will affect the rendering if said change is made before calling renderTo.
LineGraph configuration Object
Field
Notes
title
[Optional] Title of the chart, displayed centered at the top of the chart.
legend
[Optional] Legend Object.
data
[Optional] Array whose elements are two-entry Arrays representing points to be rendered. The two-entry arrays are of the form [x-value, y-value]. data is optional, it ought not be present if dataFunction is provided.
dataFunction
[Optional] A function which when passed a x-value returns the associated y-value for the rendered graph. dataFunction is optional, and overrides data if it is also present.
min
[Optional] Minimum x-value of the graph, if dataFunction is provided.
max
[Optional] Maximum x-value of the graph, if dataFunction is provided.
Legend Object
Field
Notes
x
[Optional] Label of the x-axis.
y
[Optional] Label of the y-axis.
Imalgam © 2022