Skip to content

Latest commit

 

History

History
1115 lines (959 loc) · 41 KB

File metadata and controls

1115 lines (959 loc) · 41 KB

API


Constructor

new SimpleGraph(options)

Options

NameTypeDescription
containerstringThe DOM element query/selector to the element to append the graph to. Defaults to "body".
margins object Optional custom margins.
Properties
NameTypeDescription
leftnumberLeft margin. Defaults to 40.
rightnumberRight margin. Defaults to 40.
topnumberTop margin. Defaults to 20.
bottomnumberBottom margin. Defaults to 20.
widthnumberTotal graph width (including margins). Defaults to 600.
heightnumberTotal graph height (including margins). Defaults to 400.
allowDrawBeyondGraphbooleanAllow drawing beyond graph. If true, all data will be drawn as supplied. If false, points beyond the x/y-axis range will not be drawn and lines/areas will be cut off where they extend past the x/y-axis ranges.
colorScaled3.scale Optional color scale to use with data. If data series will have non-numeric identifiers, it should be a categorical or ordinal scale. Defaults to d3.scaleOrdinal(d3.schemeCategory10).
stylesobjectKey-value pairs of additional CSS styles to apply to SVG.
axis object Axis properties.
Properties
NameDescription
xX-Axis options (see Axis Options).
yY-Axis options (see Axis Options).
y2Y2-Axis options (see Axis Options).
styles Optional key-value object of shared axis styles. Values filled in by default below:
PropertyDefault Value
fill"none"
stroke-width0.5
stroke"black"

Properties

A few (but not comprehensive) list of the important variables in an initialized SimpleGraph object are below:

  • svg - The D3 wrapper for the SVG node
  • svgGraph - The D3 wrapper for the <g> node in the SVG
  • x - The x-axis (See below for details)
  • y - The y-axis (See below for details)
  • y2 - The second y-axis (See below for details), if it exists

Axis

  • axis - The main D3 axis object for this axis
  • axisTwo - For the x-axis, the D3 axis object in case the x-axis is desired to be drawn on top of the graph
  • break - The axis breaks, if they exist
  • format - The D3 format object for this axis's tick values
  • gridAxis - The D3 axis object for the gridlines (as they may be drawn with different tick intervals than the axis itself)
  • isDate - True if date values
  • isLog - True if log-scale
  • label - The axis name/label
  • min - The axis min value
  • max - The axis max value
  • scale - The D3 scale object for this axis

Misc. Functions

SimpleGraph.getSvgElement() : Returns D3 wrapper for SVG node.

       Returns: SimpleGraph.svg

SimpleGraph.getSvgGraphic() : Returns D3 wrapper for graphic node in SVG node.

       Returns: SimpleGraph.svgGraph

SimpleGraph.remove() : Removes SVG node from container.

       Returns: Self, for chaining functions.

SimpleGraph.destroy() : Removes and destroys SVG and this object. Irreversible.

Axis, Grid, and Legend Functions

SimpleGraph.resetAxisOptions(axisOptions) : Redefine axis options. As calling this will invalidate anything drawn on the graph, all data is cleared from the graph on calling this.

NameTypeDescription
axisOptions object Map of axis options by axis name.
Properties
NameDescription
xLiteral of x-Axis options (see Axis Options).
yLiteral of y-Axis options (see Axis Options).
y2Optional literal of y2-Axis options (see Axis Options).
styles Optional key-value object of shared axis styles. Defaults to fill="none", stroke="black", and stroke-width=0.5.

       Returns: Self, for chaining functions.

SimpleGraph.drawAxes([labelPosition[, xAxisPosition[, axisLabelMargin]]]) : Redraws the axes on the graph.

NameTypeDescription
labelPositionstringKeywords for the label positions on each axis. Keywords include 'inside' or 'outside' for the position of both axis labels either inside or outside of the axis lines; 'center' to center both axis labels along parallel of respective axis; 'left' or 'right' to determine placement of x-axis label along axis parallel; 'top' or 'bottom' to determine placement of y-axis label along axis parallel. Keywords are assigned in the order they are read. Thus a call of "center top" would first center both labels, then move the y-axis label to the top. Defaults to "outside center".
xAxisPositionstringPlacement option of the x-axis, allowing you to draw the x-axis line and labels on top or bottom. Defaults to "bottom".
axisLabelMarginnumberLabels are automatically placed at a margin determined not to overlap with the tick marks. However you may specify and additional margin here.

       Returns: Self, for chaining functions.

SimpleGraph.drawGrid([style]) : Draw grid. If grid already exists, redraws it.

NameTypeDescription
styleobjectOptional key-value object of grid styles. Defaults to opacity=0.4, stroke="#555", and stroke-width=0.3.

       Returns: Self, for chaining functions.

SimpleGraph.removeGrid() : Remove grid.

       Returns: Self, for chaining functions.

SimpleGraph.drawLegend(position[, anchor[, bgstyle[, itemsPerColumn[, rowHeight[, exclude]]]]]) : Draw the legend onto the graph. If legend already exists, will redraw it.

NameTypeDescription
positionnumber[]x,y coordinate position from top-left corner of SVG.
anchorstringOptional anchor for the coordinate x-position (left, middle, or right). Defaults "left".
bgstyleobjectOptional styles for the legend. These are SVG style attributes with the exception of support for padding.
itemsPerColumnnumberOptional limit on items per column. On reaching this number, a new column will be started to the right. If set to 0 or less, all will be put in single column. Note that if the next column exceeds the right margin of the graph, placement errors will result.
rowHeightnumberThe height per row. Default of 24 is set to best fit size of text and icons in legend (the second which is currently uncustomizable) so use care if decreasing row height.

       Returns: Self, for chaining functions.

Color/Category Functions

SimpleGraph.getColorBySeriesName(name, create) : Get the color or style related to a data series. Attempts to return the style first, but failing that will return the color string. Note that colors will not be assigned to a data series until drawn, thus data series that do exist but haven't been drawn yet may not return a color.

NameTypeDescription
seriesstringThe series name.
createbooleanIf true, creates color in colorScale if color is not yet assigned. If false or left undefined, color is only returned if one has been assigned to the data series name.

       Returns: Color value, or null.

SimpleGraph.resetColorScale(colorScale) : Reset domain on color scale, or replace with provided.

NameTypeDescription
colorScaled3.colorScaleolor scale to replace with or null.

       Returns: Self, for chaining functions.

SimpleGraph.setSeriesColor(series, color) : Sets a custom color (overriding the color scale) for a given series name.

NameTypeDescription
seriesstringThe series name.
colorstringThe color value.

       Returns: Self, for chaining functions.

SimpleGraph.removeSeriesColor(series) : Remove custom color for series name.

NameTypeDescription
seriesstringThe series name.

       Returns: Self, for chaining functions.

Add Data Functions

SimpleGraph.addPointData(name, xValue, yValue[, size[, y2Axis[, showNulls]]]) : Add single point data.

NameTypeDescription
namestringThe name of the data series this point belongs to.
xValuenumberThe x-value.
yValuenumberThe y-value.
sizenumber|callbackThe size of the points when drawn. May also be a callback function where the 'this' scope would be the data point object (with keys series, x, y, and additional data keys, if supplied). Defaults to 10.
y2AxisbooleanIf true, point is assigned to y2 axis.
showNullsbooleanIf true, converts undefined/null y-values to 0. If false, undefined/null y-values are not added.

       Returns: Self, for chaining functions.

SimpleGraph.addPointsData(data, dataPointName, xValueName, yValueName[, additionalDataKeys[, size[, y2Axis[, showNulls]]]]) : Add multiple point data from an array of object literals.

NameTypeDescription
dataobject[]The plot data as an array of objects. Use the dataPointName, xValueName, and yValueName parameters to tell the function how to parse the data.
dataPointNamestringThe key name in each data object to retrieve the data point or data series name and label. If it cannot find the given key in the data object, assumes the given string is the series name for all points. If it is null or undefined, uses the index position (thus all points will be of unique series).
xValueNamestringThe key name in each data object to retrieve the x-value.
yValueNamestringThe key name in each data object to retrieve the y-value.
additionalDataKeysstring[]Additional keys for data you want to store for each point.
sizenumber|callbackThe size of the points when drawn. May also be a callback function where the 'this' scope would be the data point object (with keys series, x, y, and additional data keys, if supplied). Defaults to 10.
y2AxisbooleanIf true, point is assigned to y2 axis.
showNullsbooleanIf true, converts undefined/null y-values to 0. If false, undefined/null y-values are not added.

       Returns: Self, for chaining functions.

SimpleGraph.addPointsDataAsArray(name, data[, size[, y2Axis[, showNulls]]]) : Add multiple point data from an array of x,y coordinates.

NameTypeDescription
namestringThe name of the data series.
datanumber[][]The plot data as an array of [x,y] arrays.
sizenumber|callbackThe size of the points when drawn. May also be a callback function where the 'this' scope would be the data point object (with keys series, x, y, and additional data keys, if supplied). Defaults to 10.
y2AxisbooleanIf true, point is assigned to y2 axis.
showNullsbooleanIf true, converts undefined/null y-values to 0. If false, undefined/null y-values are not added.

       Returns: Self, for chaining functions.

SimpleGraph.addLineDataAsCoordinates(name, lineCoordinates[, style[, interpolation[, y2Axis]]]) : Add line data as an array of coordinates.

NameTypeDescription
namestringThe name of the data series.
lineCoordinatesnumber[][]Array of x,y coordinates.
styleobjectObject literal of key-value pairs that will be applied as the resulting SVG element's CSS style. Defaults to stroke-width=1.5.
interpolationd3.curveType of interpolation for line curve. See D3 Curve Factories
y2AxisbooleanWhether coordinates are for 2nd y-axis.

       Returns: Self, for chaining functions.

SimpleGraph.addLineDataAsFunction(name, lineFunction[, style[, resolution[, interpolation[, xRange[, y2Axis]]]]]) : Add line data as a function.

NameTypeDescription
namestringThe name of the data series.
lineFunctionfunctionCallback function such that function(x) returns y.
styleobjectObject literal of key-value pairs that will be applied as the resulting SVG element's CSS style. Defaults to stroke-width=1.5.
resolutionnumberHow many coordinates to calculate when drawing the line (defaults to every 20 pixels of width if not provided and if provided enforces minimum of 2).
interpolationd3.curveType of interpolation for line curve. See D3 Curve Factories
xRangenumberThe x-range of the line. Defaults to the min-max of the graph. If supplied will still be truncated to the min-max of the graph if it extends past.
y2AxisbooleanWhether coordinates are for 2nd y-axis.

       Returns: Self, for chaining functions.

SimpleGraph.addLinesDataFromPoints([style[, interpolation[, handleOverlap]]]) : Add line data from coordinates.

NameTypeDescription
styleobjectObject literal of key-value pairs that will be applied as the resulting SVG element's CSS style. Defaults to stroke-width=1.5.
interpolationd3.curveType of interpolation for line curve. See D3 Curve Factories
handleOverlapstringIf there are 2 or more points overlapped for a given x-value, how to handle the y-value for the line. Options are "average", "median", "highest", and "lowest".

       Returns: Self, for chaining functions.

SimpleGraph.addAreaBetweenTwoLines(name, lineFunctionBottom, lineFunctionTop[, style[, resolution[, interpolation[, xRange[, y2Axis]]]]]) : Add area data series with function pair defining bottom and top bounds of area.

NameTypeDescription
namestringThe name of the data series.
lineFunctionBottomfunctionCallback function for bottom border of the area such that function(x) returns y0.
lineFunctionTopfunctionCallback function for top border of the area such that function(x) returns y1.
styleobjectObject literal of key-value pairs that will be applied as the resulting SVG element's CSS style. Defaults to fill="#ccc".
resolutionnumberHow many coordinates to calculate when drawing the line (defaults to every 20 pixels of width if not provided and if provided enforces minimum of 2).
interpolationd3.curveType of interpolation for line curve. See D3 Curve Factories
xRangenumber[]|Date[]The [min, max] x-range of the line. Defaults to the min-max of the graph. If supplied will still be truncated to the min-max of the graph if it extends past.
y2AxisbooleanWhether coordinates are for 2nd y-axis.

       Returns: Self, for chaining functions.

SimpleGraph.addAreaAsCoordinates(name, areaCoordinates[, style[, interpolation[, y2Axis]]]) : Add area data series as array of area coordinates.

NameTypeDescription
namestringThe name of the data series.
areaCoordinatesnumber[][]Array of area coordinate triplets (i.e. [x, y0, y1]).
styleobjectObject literal of key-value pairs that will be applied as the resulting SVG element's CSS style. Defaults to fill="#ccc".
interpolationd3.curveType of interpolation for line curve. See D3 Curve Factories
y2AxisbooleanWhether coordinates are for 2nd y-axis.

       Returns: Self, for chaining functions.

Remove Data Functions

SimpleGraph.clearPointsData() : Remove all points data.

       Returns: Self, for chaining functions.

SimpleGraph.clearLinesData() : Remove all lines data.

       Returns: Self, for chaining functions.

SimpleGraph.clearAreasData() : Remove all areas data.

       Returns: Self, for chaining functions.

SimpleGraph.clearAllData() : Remove all data.

       Returns: Self, for chaining functions.

Additional Data Functions

SimpleGraph.getPointsDataBySeries(seriesName) : Get point data series by name.

NameTypeDescription
seriesNamestringName of the data series to retrieve.

       Returns: pointData[] - Array of pointData.

SimpleGraph.getPointCoordinatesBySeries(seriesName) : Get point coordinates by data series name.

NameTypeDescription
seriesNamestringName of the data series to retrieve.

       Returns: number[][] - Array of point coordinates.

SimpleGraph.getLinesDataBySeries(seriesName) : Get line data series by name.

NameTypeDescription
seriesNamestringName of the data series to retrieve.

       Returns: lineData[] - Array of lineData.

SimpleGraph.getAreasDataBySeries(seriesName) : Get area data series by name.

NameTypeDescription
seriesNamestringName of the data series to retrieve.

       Returns: areaData[] - Array of areaData.

Draw Data Functions

SimpleGraph.drawPoints() : (Re)draw all points data on graph. Points will have class .sg-point.

       Returns: Self, for chaining functions.

SimpleGraph.drawLines() : (Re)draw all points data on graph. Lines will have class .sg-line or .sg-plotted-line.

       Returns: Self, for chaining functions.

SimpleGraph.drawAreas() : (Re)draw all area data on graph. Areas will have class .plotted-areas.

       Returns: Self, for chaining functions.

Remove From Graph Functions

SimpleGraph.removePoints() : Remove all drawn points on graph. Does not remove the underlying data.

       Returns: Self, for chaining functions.

SimpleGraph.removeLines() : Remove all drawn lines on graph. Does not remove the underlying data.

       Returns: Self, for chaining functions.

SimpleGraph.removeAreas() : Remove all drawn areas on graph. Does not remove the underlying data.

       Returns: Self, for chaining functions.

SimpleGraph.removeAll() : Remove all drawn data series on graph. Does not remove the underlying data.

       Returns: Self, for chaining functions.

Tooltip Functions

SimpleGraph.addTooltipToPoints(tooltipFunction[, options]) : Add tooltip function to the points on the graph. Does not add tooltips to the lines connecting points, if they were added. That is handled by addTooltipToLines(). You can check the series name in the callback's returned SVG element or the class to determine type, regular lines are .sg-plotted-line and lines drawn from connecting points are .sg-line.

NameTypeDescription
tooltipFunctiontooltipTextFunctionCallback function that handles the dynamic text appearing in the tooltip.
options object
Properties
NameTypeDescription
offsetnumber[]The x,y offset of the tooltip from the cursor (default [10,-15] places the tooltip to the bottom right of the cursor).
styleobjectObject literal of key-value pairs that will be applied as the tooltip div's CSS style.

       Returns: Self, for chaining functions.

SimpleGraph.addTooltipToLines(tooltipFunction[, options]) : Add tooltip function to the lines on the graph.

NameTypeDescription
tooltipFunctiontooltipTextFunctionCallback function that handles the dynamic text appearing in the tooltip.
options object
Properties
NameTypeDescription
offsetnumber[]The x,y offset of the tooltip from the cursor (default [10,-15] places the tooltip to the bottom right of the cursor).
styleobjectObject literal of key-value pairs that will be applied as the tooltip div's CSS style.

       Returns: Self, for chaining functions.

SimpleGraph.addTooltipToAreas(tooltipFunction[, options]) : Add tooltip function to the areas on the graph.

NameTypeDescription
tooltipFunctiontooltipTextFunctionCallback function that handles the dynamic text appearing in the tooltip.
options object
Properties
NameTypeDescription
offsetnumber[]The x,y offset of the tooltip from the cursor (default [10,-15] places the tooltip to the bottom right of the cursor).
styleobjectObject literal of key-value pairs that will be applied as the tooltip div's CSS style.

       Returns: Self, for chaining functions.

Highlight Functions

SimpleGraph.highlightPoints(series[, validationCallback[, size[, fill[, stylesDict]]]]) : Highlights points by drawing new SVG over points. Highlights a given data series, using optional validationCallback to filter points within data series. Note that while size, fill, and stylesDict are all optional, if none are supplied, the highlight will look exactly like the point and no difference will be noticeable.

NameTypeDescription
seriesstringThe name of the data series.
validationCallbackfunctionThe callback function to validate whether to highlight given point. Passed argument of point data for given point. Return true to include point. If callback is null, assumes all points to be included.
sizenumber|functionPoint size or callback function to determine point size. Called in scope such that `this` will refer to the point data. If null, uses assigned `pointsize` for point data.
fillstringFill value. If null, uses same as for data series.
stylesDictobjectOptional key-value dictionary of styles to apply to SVG.

       Returns: Self, for chaining functions.

SimpleGraph.removeHighlightPoints() : Remove any highlights on points.

       Returns: Self, for chaining functions.

SimpleGraph.removeHighlights() : Remove all highlights.

       Returns: Self, for chaining functions.

Save Graph Functions

SimpleGraph.saveAsPng(pngName) : Save graph as a PNG. Note, in non-Edge Internet Explorer, the canvg library is required due to security error. This library is not packaged with SimpleGraph and simply assumed loaded into global space. If canvg object is not found, function will simply error on IE.

NameTypeDescription
pngNamestringDefault name to save png (".png" automatically appended if not already).
       **Returns:** Self, for chaining functions.

Definitions

Axis Options

NameTypeDescription
break object Optional. Places an x-axis break.
Properties
NameTypeDescription
domainnumber[]Places an axis break across this range.
rangegapnumberThe pixel width to draw for this axis break.
formatstringString formatter for tick labels. Defaults to ".0f" if numeric scale or "%Y-%m-%d" if date scale.
grid object Optional. Specify ticks for grid differently than axis bar/label.
Properties
NameTypeDescription
ticksnumberTick intervals for grid. (See ticks).
tickValuesnumber[]Tick values for grid. (See tickValues).
labelstringAxis name/label.
logBasenumberOptional base number if using logarithmic scale. Defaults to 10.
maxnumberMaximum value of axis. Defaults to 100.
minnumberMinimum value of axis. Defaults to 0.
scaled3.scaleOptional class for scale type. Must be D3 scale class. Defaults to d3.scaleLinear.
ticksnumberOptional. Number of evenly spaced tick intervals on axis to create (due to nature of axis, may not always create exactly this amount but will attempt to).
tickValuesnumber[]Optional. Specific values on axis to create tick marks on (this will take priority over `ticks` if both are supplied).

Point Data

NameTypeDescription
seriesstringThe name of the data series this point belongs to.
xnumber|DateThe x-value.
ynumberThe y-value.
y2booleanIf true, the y-value correlates to the y2 axis.
pointsizenumber|functionThe symbol size. May be a number, a callback function, or null.

Line Data

NameTypeDescription
seriesstringThe name of the data series this point belongs to.
lineFunctionfunctionCallback functions defining the line such that f(x)=y. Null if line is defined from coordinates.
coordsnumber[][]Array of line coordinates [x, y] or null if line is defined from function.
resolutionnumberHow many coordinates to calculate when drawing the line. Null if line is defined from coordinates.
xRangenumber[]The [min, max] x-range of the line. Null if line is defined from coordinates.
y2booleanIf true, the y-value correlates to the y2 axis.
interpolated3.CurveType of interpolation for line curve. See D3 Curve Factories
styleobject[]Object literal of key-value pairs that will be applied as the resulting SVG element's CSS style.

Area Data

NameTypeDescription
seriesstringThe name of the data series this point belongs to.
areaFunctionsfunction[]Array of bottom and top callback functions defining the area such that f(x)=y. Null if area is defined from coordinates.
coordsnumber[][]Array of area coordinate triplets [x, y0, y1] or null if area is defined from functions.
resolutionnumberHow many coordinates to calculate when drawing the line. Null if area is defined from coordinates.
xRangenumber[]The [min, max] x-range of the line. Null if area is defined from coordinates.
y2booleanIf true, the y-value correlates to the y2 axis.
styleobject[]Object literal of key-value pairs that will be applied as the resulting SVG element's CSS style.
interpolated3.CurveType of interpolation for line curve. See D3 Curve Factories

Tooltip Text Function

Handles the text appearing in the tooltip. Expected to return text/html. The following parameters are passed to provided to pull relevant data.

NameTypeDescription
dataobjectThe data object bound to the hovered SVG element. See above definitions for point data, line data, or area data, as relevant.
positionnumber[]The x,y relative mouse position on the parent SVG.
svgsSVGElement[]Array of the SVG elements in the layer selected(or null).
indexnumberIndex of selected element in array above such that svgs[index] gives the specific SVG element.
<style> table { border-collapse: collapse; font-size: 0.9em; margin-left: 2.5em; } th { text-align: left; background-color: #bbb; } td h5 { margin: 0.4em 0.2em; font-size: 1.05em; font-style: italic; } td table { font-size: 1em; margin: 0.2em; width: 100%; } td table th { background-color: #d6d6d6; border-color: #ddd; } td table td { background-color: #fff; border-color: #ddd; } </style>