Grapher is a minimal wrapper around D3.js to do line plots, bar plots and sparklines.
<script src="./d3.js"></script>
<script src="./grapher.js"></script>
<body>
<h2>My Graph</h2>
<button onclick="switchBarLine()">Switch bar / lines</button>
<div id="myPlot"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.15.0/d3.min.js" integrity="sha256-m0QmIsBXcOMiETRmpT3qg2IQ/i0qazJA2miCHzOmS1Y=" crossorigin="anonymous"></script>
<script src="./grapher.js"></script>
<script>
data = [{"value":3,"Country/Region":"France","date":"2020-01-21T23:00:00.000Z"},
{"value":1,"Country/Region":"France","date":"2020-01-22T23:00:00.000Z"},
{"value":4,"Country/Region":"France","date":"2020-01-23T23:00:00.000Z"},
{"value":7,"Country/Region":"France","date":"2020-01-24T23:00:00.000Z"},
{"value":-3,"Country/Region":"Italy","date":"2020-01-21T23:00:00.000Z"},
{"value":3,"Country/Region":"Italy","date":"2020-01-22T23:00:00.000Z"},
{"value":4,"Country/Region":"Italy","date":"2020-01-23T23:00:00.000Z"},
{"value":10,"Country/Region":"Italy","date":"2020-01-24T23:00:00.000Z"}]
let options = {
"data": data,
"x": {
"name":"date",
"scale": "scaleTime",
"tickFormat": d3.timeFormat("%d/%m/%y"),
"parse": (d) => new Date(d)
},
"y": {
"name": "value",
"scale": "scaleLinear",
"tickFormat": d3.format('.3s')
},
"category": "Country/Region",
"type": "lines",
"style": {
"grid": false
}
}
let myGraph = new Grapher("myPlot", options);
myGraph.draw();
function switchBarLine() {
if (myGraph.options.type == "bar") {
myGraph.draw({"type":"lines"});
} else {
myGraph.draw({"type":"bar"})
}
}
</script>
</body>
Build the package
npm run buildCreate documentation
npm run doc- findTimeFormat
- unique
- getOptimalPrecision
- updateDict
- getDimensionText
- to_csv
- splitString
- wideToLong
- longToWide
- barycenterColor
- getBackgroundColor
- groupBy
- GrapherBase
- Chart
- margin
- margin
- options
- draw
- Donut
- Gauge
Return the timeformat in d3.timeParse function
strstring string containing d3.timeParse(xxx)
Returns string time format argument of d3.timeParse function
Return unique values of an array (including if there are dates)
arrayArray arraysortingboolean whether to sort the array (optional, defaulttrue)_sortfunction sorting function (optional, defaultundefined)
let uniqueArray = unique([1, 1, 2, 3 ])
uniqueArray
> [1, 2, 3]Returns Array of unique values of 'arr'
Get optimal decimal precision for number formatting
maxNnumber maximum number in the data
Returns string optimal format for d3.format
Update a nested dictionary (stored as an Object)
dictObject Object to update with values in newDictnewDictObject Object containing key:values to update dict with
Retrieve the width and height of some text based on its font
Returns Object Object with width and height of the text as if it was on the DOM
Transform a JSON object into a csv
jArray<Object> Array of objects, each object should has the same number of keys (and each key is going to be a column). Each element of the array is going to be a line.headerBoolean If true, first line of the csv fine will be a header composed of the first object keys (optional, defaulttrue)
Returns String return a csv file as a string
Split a string in substrings of length of approx. n characters and splitting on space only. The function will split the string in substring of minimum length 'n' on spaces inside the string.
sstring string to be splitnnumber length of bits to split string 's'sepstring separator to be used to for splitting the string. The character should not be inside the string. (optional, default"|")
Returns Array array of substrings
Transform a 'wide' array of Dict to 'long' array, pivoting on some 'pivot' columns (keys). The long format is a {id, key, value}, where id is one or multiple 'pivot' columns, 'key' are the non pivot columns of the original array and the value are the value of the corresponding keys. A category value can also be passed as a new 'column'. The long format becomes {id, key, value, category}. A mapping function can also be passed to be applied to each long element (for instance to parse a date)
wideDataArray data to pivotpivotColumnsArray list of keys on which to pivot from wide to longkeyNamestring name of the key for variable name in the long format. (optional, default"field_id")valueNamestring name of the key for value in the long format (optional, default"field_value")categorystring? optional category key to be added in the long data (optional, default"undefined")mapLongElementfunction (Dict) optional function to be applied on each long element (optional, defaultundefined)
wideArray = [{'date':'2020-07-19','temperature':32,'pressure':1016},
{'date':'2020-07-20','temperature':25,'pressure':1020}];
longArray = wideToLong(wideArray, ['date']);
longArray = [{'date':'2020-07-19', 'field_id':'temperature','field_value':32},
{'date':'2020-07-19', 'field_id':'pressure','field_value':1016},
{'date':'2020-07-20', 'field_id':'temperature','field_value':25},
{'date':'2020-07-20', 'field_id':'pressure','field_value':1020}]Transform a 'long' array of Dict to 'wide' array, pivoting on some 'index' columns (keys).
longDataArray data to pivotindexArray column(s) to pivot oncolumn(optional, default'field_id')value(optional, default'field_value')keyNamestring name of the key for variable name in the long format. (optional, default"field_id")valueNamestring name of the key for value in the long format (optional, default"field_value")mapLongElementfunction (Dict) optional function to be applied on each long element
longArray = [{'date':'2020-07-19', 'field_id':'temperature','field_value':32},
{'date':'2020-07-19', 'field_id':'pressure','field_value':1016},
{'date':'2020-07-20', 'field_id':'temperature','field_value':25},
{'date':'2020-07-20', 'field_id':'pressure','field_value':1020}]
longToWide(longArray, 'date', 'field_id', 'field_value');
wideArray = [{'date':'2020-07-19','temperature':32,'pressure':1016},
{'date':'2020-07-20','temperature':25,'pressure':1020}];Compute the barycenter between two colors. Returned color will be startColor _ weight + endColor _ (1 - weight)
startColorstring starting color in rgb / hsl formatendColorstring ending color in rgb / hsl formatweightnumber weight of the first color
Returns string the barycenter color
Return the background color of an element, if transparent returns the background color of the parent element. If no parent, then the defaultColor is returned.
elstring DOM element to retrieve bacground color fromdefaultColorstring color to be returned if no background color is found. (optional, default"rgb(255, 255, 255)")
This function mimics Python pandas function group by.
arrayArray the array to group bykeystring key to group by withcolSumArray array of columns to agg by sum (optional, default[])colCountArray array of columns to agg by count (optional, default[])colFirstArray array of columns to keep first (optional, default[])
Base class for Grapher linking the chart to the DOM element and creating the svg
idstring id of the DOM elementtypestring Chart typewidthnumber width of the DOM element (if not already setup in HTML or CSS) (optional, defaultnull)heightnumber height of the DOM element (if not already setup in HTML or CSS) (optional, defaultnull)
Wipe the graph elements created by draw without removing the core elements so that the graph can be drawn again with .draw()
Download the data associated with the Grapher element
The Chart object represents the graph.
You create a Chart by specifying a container (a DOM element)
that will contain the graph, and other options.
idstring of the DOM elementoptionsObject Set of options for the graph.options.dataArray<Object> Array of JSON containing the data (optional, default[])options.xObject Set of options for the x axisoptions.x.namestring Name of the x-axis variable in options.data (optional, defaultx)options.x.scalestring d3-scale, see d3-scale on Github (optional, default"scaleLinear")options.x.parse(function | null) Function to parse the data (useful if x-axis is a date) (optional, defaultnull)options.x.tickFormat(function | null) Function to format the variable when displayed as tick or in tooltip (optional, defaultnull)options.x.label(string | null) Label for x-axis (optional, defaultnull)options.x.domain(Array<number> | null) Hardcode the x-axis bound. Default is to use min and max of x values in options.data (optional, defaultnull)options.x.niceBoolean Extends the domain so that it starts and ends on nice round values (applying d3.nice()), for further reference see d3-scale on Github (optional, defaulttrue)options.x.padding(number | null)? Padding to be used between bars when x.scale is scaleBand.options.x.values(Array<string> | null)? List of values of x axis. Derived from the data if not provided.
options.yObject Set of options for the y axisoptions.y.namestring name of the y-axis variable in options.data (optional, defaultx)options.y.scalestring d3-scale, see d3-scale on Github (optional, default"scaleLinear")options.y.parse(function | null) function to parse the data (useful if y-axis is a date) (optional, defaultnull)options.y.tickFormat(function | null) function to format the variable when displayed as tick or in tooltip (optional, defaultnull)options.y.label(string | null) label for y-axis (optional, defaultnull)options.y.domain(Array<number> | null) Hardcode the y-axis bound. Default is to use min and max of y values in options.data (optional, defaultnull)options.y.niceBoolean Extends the domain so that it starts and ends on nice round values (applying d3.nice()), for further reference see d3-scale on Github (optional, defaulttrue)
options.categoryObject set of options for categoryoptions.categories(Array<string> | Boolean) Hardcode the list of elements of the 'category' variable to select only data's elements belonging to this list. When no list is specified, the list of elements is derived from the data and all 'category' values found in the data are considered. (optional, defaultfalse)options.typestring type of the graph. Possible types are "line", "bar", "stacked-bar", "stacked-area", "dotted-line", "dot", "sparkline" (optional, default"line")options.styleObject list of options for styling the elements of the graphoptions.style.colorsArray<string> List of colors for the lines, bars, dots (not applicable for sparkline). Default is ["#1abb9b","#3497da","#9a59b5","#f0c30f","#e57e22","#e64c3c","#7f8b8c","#CC6666", "#9999CC", "#66CC99"]options.style.barWidthnumber Share of the x axis width that should be filled with bars. Setting to 0.8, lets 20% in space between bars. (optional, default0.8)options.style.strokeWidthnumber stroke-width of the line. Default is 3px (optional, default3)options.style.dotSizenumber dot-size of the dots. Default is 4px (optional, default4)options.style.tooltipColorstring Text color in the tooltip (optional, default"#181818")options.style.tooltipBackgroundColorstring Background color of the tooltip (optional, default"#ffffff")options.style.tooltipOpacitystring Opacity of the tooltip. Default is 0.8 (80%) (optional, default"0.8")options.style.tooltipLineColorstring Color of the vertical line color (optional, default"#000000")options.style.beautifyClosestLine(string | function) Beautify the closest line to current mouse cursor (only works for line or dotted-lines). Possible options are either "widen" (increase the stroke-width by 1), "color" (color the closest line, grayed the others) or you can pass a function that will be applied on every lines and takes four parameters: the element itself, whether the line is the closest, the path and the category. (optional, default"widen")
options.gridObject Options for the gridoptions.grid.xObject Options for grid on the x-axisoptions.grid.x.showBoolean if true, grid will be added (same frequency as ticks) (optional, defaultfalse)options.grid.x.linesArray<{x: string, label: string, position: string, y: string, textAnchor: string, class: string}> Array for vertical lines. For each line, you should at least specify the position on the x-axis (same format as x axis). You can add a label for which you can specify its position by choosing 'position' value among 'start', 'middle', 'end'. The label can also be more precisely positionned by specifying a 'y' and textAnchor value among 'start', 'middle', 'end'. You can also add a class with 'class'. (optional, default[])
options.grid.yObject Options for grid on the y-axisoptions.grid.y.showBoolean if true, grid will be added (same frequency as ticks) (optional, defaulttrue)options.grid.y.linesArray<{y: string, label: string, position: string, x: string, textAnchor: string, class: string}> Array for horizontal lines. For each line, you should at least specify the position on the y-axis (same format as y axis). You can add a label for which you can specify its position by choosing 'position' value among 'start', 'middle', 'end'. The label can also be more precisely positionned by specifying a 'x' and textAnchor value among 'start', 'middle', 'end'. You can also add a class with 'class'. (optional, default[])
options.legendObject Options for the legendoptions.legend.showBoolean show legend. If false, legend will not be displayed. (optional, defaulttrue)options.legend.xnumber legend's x position in the svg (optional, default15)options.legend.ynumber legend's y position in the svg. Default value equals the margin-top of the g element inside the svg.options.legend.intersticenumber space in px between the legend items (optional, default25)options.legend.backgroundColorstring legend's background color (optional, default"#ffffff")options.legend.opacitystring opacity of the legend (optional, default"0.9")
options.downloadObject options for downloading data associated with the graphoptions.filenamestring filename for the csv linked to the data (optional, default"data_<elementId>_<date>.csv")options.sparklineObject options for the sparkline objectoptions.sparkline.range(Array<number> | null) range for the background's band displayed in the sparkline. If null, not the band is not displayed. (optional, defaultnull)options.sparkline.textLastPointBoolean display the last point's value as adjacent text. (optional, defaulttrue)options.sparkline.strokeWidthnumber stroke's width of the sparkline (optional, default1)options.sparkline.lineColorstring line's color of the sparkline (optional, default"#000000")options.sparkline.circleColorstring circle's color for the last point of the sparkline (optional, default"#f00")options.sparkline.textColorstring text's color of the last point value displayed next to the sparkline (optional, default"#f00")options.sparkline.textFontSizestring text's font size (optional, default"85%")options.sparkline.textFontWeightstring text's font weight (optional, default"600")options.sparkline.rangeFillColorstring range's band fill color (optional, default"#ccc")options.sparkline.rangeFillColorstring range's band fill color (optional, default"#ccc")
options.advancedObject Advanced options
widthnumber width of the DOM element (if not already setup in HTML or CSS) (optional, defaultnull)heightnumber height of the DOM element (if not already setup in HTML or CSS) (optional, defaultnull)
let myGraphExample1 = new Grapher('myGraphExample1',
{"data": data,
"x": {
"name": "date",
"scale": "scaleTime",
"parse": (d) => d3.timeParse('%Y-%m-%d')(d),
"tickFormat": d3.timeFormat("%d/%m/%y"),
"label": "Date"
},
"y": {
"name": "value",
"tickFormat": d3.format('.3s'),
"label": "Glucose"
},
"type": "dotted-line",
});Draw the Grapher object
options(Object | null) you can pass an options Object to update the element's option. @link Grapher
Get and sets the values of the inner margins
marginObjectmargin.topstring margin top (optional, default10)margin.right(string | function) margin right depends of the width of the graph (optional, default(x)=>x<400?20:30)margin.bottomstring margin bottommargin.left(string | function) margin left depends of the width of the graph (optional, default(x)=>x<400?40:60)
Returns Object
Get and sets the values of the inner margins
marginObjectmargin.topstring margin top (optional, default10)margin.right(string | function) margin right depends of the width of the graph (optional, default(x)=>x<400?20:30)margin.bottomstring margin bottommargin.left(string | function) margin left depends of the width of the graph (optional, default(x)=>x<400?40:60)
Returns Object
Gets and sets the option for Grapher object.
Note that setter is called only by typing myGraph.options = {something};
Typing myGraph.options.data = something; do work but setter is not called and data is not parsed again, etc.
optionsObject @link Grapher
Draw the Grapher object
options(Object | null) you can pass an options Object to update the element's option. @link Grapher
The Donut class is a children class of the Grapher class. This is still a work in progress. Currently the Donut is mainly a Gauge.
idstring id of the DOM elementoptionsObject Set options for the Gaugeoptions.valuenumber Value to display (optional, default50)options.foregroundColorfunction Function to plot a foreground color (function of the value). Default is d => #1abb9b. It's a function rather than a string so that it allows you to change the color depending on the value.options.backgroundColorstring Background color of the donut. Default is the "weighted average" between the background color and foreground color with a 60% weight on the background color.options.innerRadiusnumber inner radius of the donut. Default is 40% of the size. (optional, default0.4*size)options.outerRadiusnumber outer radius of the donut. Default is 50% of the size. (optional, default0.5*size)options.startAnglenumber starting angle. Default is -180 (other values allows you to plot less than a "circle"). (optional, default-180)options.endAnglenumber ending angle. Default is 180 (optional, default180)options.minValuenumber mininum value when the angle is -180, default is 0. (optional, default0)options.maxValuenumber maximum value when the angle is 180, default is 100. (optional, default100)options.displayValueboolean? display value inside the donut.options.fontSizestring fontSize of the displayed value inside the donut. Default is the font size of the DOM element.options.cornerRadiusnumber corner radius of the arc (see cornerRadius of d3.arc for more details) (optional, default0)options.maxHeightnumber maximum height of the DOM element. Default is DOM element size. (optional, defaultsize)options.padAnglenumber pad angle of the arc (see padAngle of d3.arc for more details) (optional, default0.03)
displayTextfunction text to be displayed inside the donut. It's a function of the value. Default d => d (e.g. dispkay the value).size(number | null) size of the gauge (for a gauge, width and height are the same).typestring type of the graph. (optional, default"donut")
let myArc = new g.Donut("myArc",
{"value": 30},
size=100);
myArc.draw();Return a d3 scale for colors
The Gauge is a child of Donut class with convenient defaults for plotting a gauge.
idstring id of the DOM elementoptionsObject Set options for the Gaugesize(number | null) size of the gauge (for a gauge, width and height are the same).
let myGauge = new g.Donut("myGauge",
{"value": 20},
size=100);
myGauge.draw();There are many libraries to do plots out-there, starting by D3.js. You can also have a look to more high-level libraries like C3.js, plot.ly, Chart.js, Vega.
Copyright: Louis de Charsonville, louisdecharson@posteo.net