Scatter chart API reference
- Example
- Format of the data array (colors/tooltips)
- Properties
- Methods
- Box/Whisker (candlestick) plots
- Specific points for labels on the X-axis
- Custom tickmarks
- Note about colors and the key
- Note about the crosshairs event
- Adding a trend line to your chart
- Note about the data_arr array
- Date/time based charts
- Bubble charts
- The Lasso feature
- Marimekko charts
- The coordinates properties
- How to make trendline/dual-color Scatter charts
- Events
- Effects
Example
<script> tooltip = '%{key}'; scatter = new RGraph.Scatter({ id: 'cvs', data: [ [ {x:10,y:15,color: 'gray',tooltip:tooltip}, {x:36,y:26,color: 'gray',tooltip:tooltip}, {x:74,y:34,color: 'gray',tooltip:tooltip}, {x:111,y:29,color: 'gray',tooltip:tooltip}, {x:145,y:38,color: 'gray',tooltip:tooltip}, {x:176,y:41,color: 'gray',tooltip:tooltip}, {x:215,y:49,color: 'gray',tooltip:tooltip}, {x:254,y:55,color: 'gray',tooltip:tooltip}, {x:295,y:62,color: 'gray',tooltip:tooltip}, {x:342,y:74,color: 'gray',tooltip:tooltip} ] ], options: { marginLeft: 50, tooltipsFormattedKeyLabels: ['Richard','John','Luis','Pob','Pete','Olga','Kiffen','Hevin','Joy','Hoolio'], tooltipsFormattedKeyColors: ['black','red'], tooltipsCss: { fontSize: '16pt', boxShadow: '', textAlign: 'left' }, trendline: true, trendlineColor: ['gray','red'], trendlineMargin: 5, backgroundGridBorder: false, backgroundGridVlines: false, yaxis: false, yaxisScaleMax: 100, backgroundGridColor: '#eee', xaxisLabels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], xaxisScaleMax: 365, tickmarksSize: 10, textSize: 16 } }).draw(); </script>
Format of the data array (colors/tooltips)
Each point on the Scatter chart
is made by supplying an array
of up to 4 elements (from version 6.11 it can also be an
object which has up to four properties -
details below):
- The X value (required)
- The Y value (required). As well as a single number this can also be an array of numbers that describe a boxplot/whisker.
- The color (optional)
- The tooltip for this mark (optional)
If you wish to specify a tooltip, but not a color (ie use the
default
color instead), you can pass null
instead
of a color.
<script> // // A single dataset // data = [ [67,78], // A basic datapoint [67,40,'red'], // A datapoint with a color specified [150,26,'green','A tooltip!'], // A datapoint with a color and tooltip specified [164,35, null, 'Just the tooltip'], // A datapoint with no color and a tooltip ]; // // Multiple datasets // data = [ [ [67,78], // A basic datapoint [67,40,'red'], // A datapoint with a color specified [150,26,'green','A tooltip!'], // A datapoint with a color and tooltip specified [164,35, null, 'Just the tooltip'] // A datapoint with no color and a tooltip ], [ [7,41], [9,45,'red'], [8,23,'green','A tooltip!'], [15,32, null, 'Just the tooltip'] ] ]; new RGraph.Scatter({ id: 'cvs', data: data, options: { xaxisScaleMax: 365 } }).draw(); </script>
Object based point definitions
From version 6.11 the canvas
Scatter chart
can
handle the array for each point being an object instead. You
may find that this is easier to create and understand. There's
an example of this below that shows the datasets from the
above code converted to use objects instead.
<script> // // A single dataset // data = [ {x: 67, y: 78 }, // A basic datapoint {x: 67, y: 40, color: 'red'}, // A datapoint with a color specified {x: 150, y: 26, color: 'green', tooltip: 'A tooltip!'}, // A datapoint with a color and tooltip specified {x: 164, y: 35, tooltip: 'Just the tooltip'} // A datapoint with no color and a tooltip ]; // // Multiple datasets // data = [ [ {x: 67, y: 78}, // A basic datapoint {x: 67, y: 40, color: 'red'}, // A datapoint with a color specified {x: 150, y: 26, color: 'green', tooltip: 'A tooltip!'}, // A datapoint with a color and tooltip specified {x: 164, y: 35, tooltip: 'Just the tooltip'} // A datapoint with no color and a tooltip ], [ {x: 7, y: 41}, {x: 9, y: 45, color: 'red'}, {x: 8, y: 23, color: 'green', tooltip: 'A tooltip!'}, {x: 15, y: 32, tooltip: 'Just the tooltip'} ] ]; new RGraph.Scatter({ id: 'cvs', data: data, options: { xaxisScaleMax: 365 } }).draw(); </script>
Properties
You can use these properties to control how the chart appears. You can set them by including them in the options section of the configuration as shown above.
- Background properties
- X-axis properties
- Y-axis properties
- Color properties
- Labels and text properties
- Margin properties
- Tickmark properties
- Title properties
- Interactive features properties
- Line properties
- Trend line properties
- Bubble properties
- Lasso properties
- Key properties
- Marimekko properties
- Miscellaneous properties
Background properties
css
background color to the canvas
tag.myScatter.set('backgroundHbars', [[75, 10, 'yellow'], [85, 15, 'red']]);This would give you two bars, one red and a lower yellow bar. The units correspond to your scale and are the starting point and the height.
myScatter.set('backgroundVbars', [[0, 181, 'rgba(0,255,0,0.5)']]);Normally the values are:
- The start value
- The extent of the bar (the width in scale terms)
- The color
Date/Time
chart that isn't very practical - so when you're using Date/Time
values the two values that you specify should be the start and end Date/Time
s like this: obj.set('backgroundVbars', [['2013/06/01','2013/07/01','pink']]);
true
.true
. This takes precedence over dashed lines.array
to this property. It should be an array
of two or more numbers that specifies the size of dashes and gaps like this: [5, 10]draw
event may mean that the event fires twice. There is a property that you can check though that is set when the image has loaded: obj.__rgraph_background_image_loaded__
Simply check this flag in your draw
event. If it's true then the background image has loaded.canvas
with many charts - you may need to specify this.canvas
with many charts - you may need to specify this.top left
bottom right
bottom
right
linewidth
of the border that goes around the chart area.X-axis properties
x-axis
is positioned. If you wish to show negative values then you should set this to center
or you can now (Jul 2016) use an offset x-axis
by leaving this property at the default bottom
and using the yaxisScaleMax
and yaxisScaleMin
properties.linewidth
used for the x-axis
and the x-axis
tickmarks.x-axis
.%{value_formatted}
macro.%{value_formatted}
macro.%{value_formatted}
macro.%{value_formatted}
macro.%{value_formatted}
macro.x-axis
labels. For example, you could set this to 45 to get angled labels.section
for most chart types and edge
for Line charts
. You probably won't need to change this.css
class to the x-axis
labels which you can then use for styling purposes or to make retrieving the span
tags easier (the dom
elements). If you inspect the labels in your browser's javascript
console (you will first need to enable the textAccessiblePointerevents
property) you will be able to see the other css
classes that are assigned to the labels.scaleDecimals
property is used.
function myFormatter(opt)
{
var obj = opt.object,
num = opt.number;
return num + 'F'; // An example of formatting
}
x-axis
value you wish to set. For example, if you're displaying products sold in a year, you might use 365.x-axis
title.x-axis
title.x-axis
title is bold or not.x-axis
title is italic or not.x-axis
title.x-axis
title.Y-axis properties
y-axis
tickmarks there are.x-axis
position warrants it)x-axis
position warrants it)['Low', 'Medium', 'High']
. Note: Since March 2013 you may now need to add an extra (optionally) empty element to the array of labels to achieve your desired result.y-axis
. It does not affect a scale.y-axis
title.y-axis
title.y-axis
title is bold or not.y-axis
title is italic or not.y-axis
title.y-axis
titles X coordinate.y-axis
titles Y coordinate.y-axis
title.y-axis
title.y-axis
title is accessible or not.y-axis
is measured in. This string is displayed before the actual number, allowing you to specify values such as $50
.y-axis
is measured in. This string is displayed after the actual number, allowing you to specify values such as 50ms
.function myFormatter(opt) { var num = Number(opt.number) * 5; return String(num) } obj.set('yaxisScaleFormatter', myFormatter);
Color properties
Labels and text properties
true
this will show the values of the points above them.DateTime
value is: labelsAboveFormatterX: function (obj, value) { var d = new Date(value); date = d.getDate(); month = d.getMonth(); year = d.getFullYear(); return '{1}/{2}/{3}'.format(date, month, year); },
DateTime
value is: labelsAboveFormatterY: function (obj, value) { return value; },
dom
text in place of canvas
text. It makes for much higher quality text that you can also select if desired (for copy/paste operations). It won't fit all situations and you can read more about the DOM text feature here. A good way to control borders/margins/padding etc is not to set them on the canvas
but to wrap the canvas
in a div
and set them on that like this:
<div style="margin-left: 50px; display: inline-block"> <canvas id="cvs" width="650" height="250"></canvas> </div>
visible
or hidden
and it controls whether the text is clipped to the edges of the canvas
. It defaults to be visible and means you can set small margins if you wish.dom
text responds to mouse based events or not (it sets the pointer-events
css
property to none
).Margin properties
Tickmark properties
cross
, plus
, circle
, diamond
, square
or null
(no tickmarks). As of August 2014, this can be a location of an image file to use as the tickmarks or a data: URL. See below for details. This property can also be a function which allows you to draw the tickmark yourself - details below.left
right
or center
and determines the horizontal alignment of the tickmark.top
bottom
or center
and determines the vertical alignment of the tickmark.Title properties
textFont
setting is used (usually Arial
).4pt
bigger than the textSize
setting."-5"
- in which case it's converted to a number and added to the calculated coordinate - allowing you to adjust the calculated coordinate."-5"
- in which case it's converted to a number and added to the calculated coordinate - allowing you to adjust the calculated coordinate.marginTop
value.Interactive features properties
slide
fade
or none
.true
to get this behaviour. Keep in mind that if you have a lot of bars/segments/points/etc then it's possible for the chart to become quite crowded. If you need to subsequently clear all of the tooltips there's an api
function available to do that for you and it's called: RGraph.tooltip.persistent.clear()
If you want to access any (or all) of the tooltip div
tags then you can do so using the RGraph.tooltip.persistent
object. This option works when you have the tooltipsEvent
property set to mousemove
%{value_formatted}
option.%{value_formatted}
option.%{value_formatted}
option.%{value_formatted}
option.%{value_formatted}
option.%{key}
option to use.square
or circle
css
values to the key color shape that appears in the tooltip key. Note the property name is "color" and not "colors" like previous properties. It should be an object of css
properties like this: tooltipsFormattedKeyColorsCss : { border: "1px solid #ddd"; }
ul
and ol
.tooltipsFormattedListItems: [ ['Bill','Jerry','Berty'], // First tooltip ['Gill','Carrie','Lucy'], // Second tooltip ['Pob','Nobby','Hilda'] // Third tooltip ]You can use
css
to style this list - for example:.RGraph_tooltip ul#rgraph_formatted_tooltips_list li { text-align: left; color: yellow; }
th
tags.css
values applied to the tooltips pointer (a css
border, for example) then specify an object containing those values to this property. For example: tooltipsPointerCss: { borderLeft: 'gray 2px solid', borderBottom: 'gray 2px solid' }
false
tooltips are positioned next to the mouse pointer.css
that gets applied to all of the tooltips, but don't want to use the RGraph.tooltips.style
object (which gets applied to all of the tooltips on the page for every chart) you can use this property to give some per-object css
for the tooltips. These are css
styles that get applied to all of the tooltips for the specific object only. It should look like this:tooltipsCss: { fontFamily: 'Verdana', fontSize: '20pt' }
css
class the chart uses.pie-tooltipshotspotignore.html
. You can use the transparent
color to allow the rear chart to be seen in such a case. It can be:
- A single
boolean
value (ietrue
orfalse
) to enable or disable all of the hotspots -true
means the hotspot will be ignored - A single number (the zero-indexed number corresponding to the hotspot to ignore)
- An array of numbers (the numbers are the indexes of hotspots to ignore)
- An array of
boolean
true
orfalse
values - the position of these values correspond to the index(es) of the segments to ignore (for example[false, false, true, false, false]
-true
means the corresponding hotspot will be ignored)
true
, you will get a crosshair centering on the current mouse position.true
, this will show the coordinates that the crosshairs are currently over.true
, this makes the coordinates static (attached), instead of following the pointer around.object
(which is the chart object) and value
(which is the X value).object
(which is the chart object) and value
(which is the Y value).true
the horizontal grid line will snap to the scale values.array
of values that determine whether a point is adjustable or not. A true
value for when it is, a false
value for when it's not.Line properties
Line chart
, Scatter chart
lines can be stepped by setting this to true.Trend line properties
linewidth
of the trend line(s). It can be a single number or an array of numbers if you have multiple datasets.true
then the trend lines on the chart will be dashed.true
then the trend lines on the chart will be dotted,trendlineMargin
property).Bubble properties
Lasso properties
state
object and you can access the state.points
property to get a list of datasets/indexes of points which are highlighted. For example: // ... lassoCallback: function (state) { // You can access the state.points array to get the points which are highlighted } // ...
lasso
data (the selected areas and points) is persisted across page refreshes or not. By default persistence just uses the window.localStorage
variable to store information.window.localStorage
variable to store the data. If you use the lassoPersistSave
and lassoPersistLoad
properties to store data somewhere else you might not want this to occur - so, using this property, you can turn it off.ajax
call to save the persistence information to your server. For example: // ... lassoPersistSave: function (state) { // You can access the state.points array to get the points which are highlighted } // ...
// ... lassoPersistLoad: function () { // Load the persistence data here and return it // return data; } // ...
Key properties
The key properties are documented on the key documentation page.Marimekko properties
linewidth
of the stroke that's used around the segments.array
of colors that are used for the segments on the chart.marimekkoColors
property are used in order, for each bar. With this property set to true
though the colors are used in the order that you give across the whole set of bars.array
of labels which are placed above the bars in the top margin. This can either be an array
of simple strings
, an array
of strings that use substitution macros or a string
that uses substitution macros. This last option is probably the most useful option. Read the formatted labels documentation for more information on this last option.textColor
property.textSize
property.textFont
property.textBold
property.textItalic
property.%{value_formatted}
macro.%{value_formatted}
macro.%{value_formatted}
macro.%{value_formatted}
macro.%{value_formatted}
macro.true
or false
and determines whether labels are drawn inside the bars - showing the value.textColor
property.textFont
property.textBold
property.textItalic
property.Miscellaneous properties
null
but you can set it to a function if you wish so that function is called to do the chart highlighting. It's passed the shape object as an argument. As of version 5.23 you can also set this to invert as well. If you do this on a dark background you may find that you need to change the highlightFill
color setting as well.canvas
.yaxisScaleMax
but you still want to see marks drawn that go above this maximum then you'll need to set this property to true.- value: The value you want the line positioned at or the keyword average (default: average)
- color: The color of the line (default: #666)
- dashed: Whether the line is dashed or not (default: true)
- dotted: Whether the line is dotted or not (default: false)
- linewidth: The
linewidth
of the line (default: 1) - label: this is The label that appears above (by default) the line. If you don't want a label you can set this to an empty string. default: Average (%{value})
- labelPosition: This can be a string that consists of the following keywords: left/center/right/left-margin/right-margin top/bottom (default: top right)
- labelFont: The font that the label is drawn in (default: [the same as the textFont property])
- labelColor: The color that the label is drawn in (default: #666)
- labelSize: The size of the label (in points) (default: 4 points less than the textSize setting)
- labelBold: Whether the label is bold or not (default: null [falls back to the textBold setting])
- labelItalic: Whether the label is italic or not (default: null [falls back to the textItalic setting])
- labelValueDecimals: How many decimals are shown on the number. (default: 2)
- labelValuePoint: The character used as the decimal point. (default: .)
- labelValueThousand: The character used as the thousand separator charactor.(default: ,)
- labelValueUnitsPre: This string is prended to the number. (default: [an empty string])
- labelValueUnitsPost: This string is appended to the number. (default: [an empty string])
- labelOffsetx: The horizontal offset that's applied to the X coordinate. (default: 0)
- labelOffsety: The vertical offset that's applied to the Y coordinate. (default: 0)
- labelValueFormatter: This function handles ALL of the formatting of the number. (default: null)
obj.set('horizontalLines', [ { value: 'average', dashed: true, labelPosition:'left bottom' }, { value: 10.48, label:'Value (%{value})', labelValueDecimals: 2, labelValueThousand: ',', labelValuePoint:'.', labelValueUnitsPre:'', labelValueUnitsPost:'' //labelValueFormatter: function (opt) //{ // return opt.number; //} } ]);
Methods
obj.get(name)
An accessor that you can use to retrieve the values of properties.
obj.set(name, value)
An accessor that you can use to set the values of properties.
obj.getShape(event)
This function makes it easier to get hold of which point on the Scatter chart
has been clicked or hovered over. It returns an object that has
the following properties:
object |
The chart object |
x |
The X coordinate |
y |
The Y coordinate |
dataset |
The zero-indexed dataset (the Scatter chart supports multiple datasets).
|
index |
The zero-indexed index of the point. |
sequentialIndex |
The zero-indexed sequential index of the point. For example, on a chart where there are three datasets of three points each - this goes from 0 up to 8. |
tooltip |
If a tooltip is associated with this point this will be it.id:
strings are expanded for you (where the tooltip text is retrieved from the html
tag with the matching ID).
|
<script> scatter.canvas.onmousemove = function (e) { var canvas = e.target; var obj = canvas.__object__; var shape = obj.getShape(e); if (shape) { obj.path( 'b a % % 5 0 6.29 f red', shape.x, shape.y ); } } </script>
In boxplots the shape object is slightly different:
object |
The chart object |
x |
The X coordinate |
y |
The Y coordinate |
width |
The width of the bar |
height |
The height of the bar |
dataset |
The zero-indexed dataset . Scatter charts can have multiple datasets and this
indicates the dataset index.
|
index |
The zero-indexed index of the box. |
sequentialIndex |
The zero-indexed sequential index of the box. |
tooltip |
If a tooltip is associated with this box this will be it. id:
strings are expanded for you (where the tooltip text is retrieved from the html
tag with the matching ID).
|
<script> scatter.canvas.onclick = function (e) { RGraph.redraw(); var canvas = e.target, obj = canvas.__object__, shape = obj.getShape(e); if (shape) { obj.path( 'lc square lj square b r % % % % f red', shape.x, shape.y, shape.width, shape.height ); } } </script>
obj.getXValue(mixed)
This method can be used to get the X value at a particular point or at
the mouse coordinates, based on the X maximum value
that is being used. Not simply the coordinates of the mouse. The argument
can either be an event object (for use in event
listener functions) OR a two-element array consisting of the X and Y
coordinates (ie when you're not necessarily in an event
listener). It returns null
if the mouse or coordinates are in the
margin areas.
obj.getYValue(mixed)
This method can be used to get the Y value at a particular point or at
the mouse coordinates, based on the scale that is in use.
Not simply the coordinates of the mouse. The argument can either be an
event object (for use in event listener functions) OR a two-element
array consisting of the X and Y coordinates (ie when you're not
necessarily in an event listener). It returns null
if the mouse
or coordinates are in the margin areas.
obj.getYCoord(value)
This method can be used to get an appropriate Y coordinate for a value when you're doing custom drawing on the chart. It returns the coordinate for the max/min value if the given number is out of range.
obj.getXCoord(value)
This method can be used to get an appropriate X coordinate for a value
when you're doing custom drawing on the chart. It returns
null
if the given number is out of range. If you're using a Date/Time
chart with the min
and max
set to Date/Time
strings
you can also pass this function a Date/Time
string eg:
obj.getXCoord('2013-06-12T15:14:16');
obj.on(event, function)
This method can be used to set an event listener on an object.
It operates similarly to the jquery
on
function.
The first argument is the event that you wish to attach to and the
second is the handler function. For example:
obj.on('draw', function (obj)
{
// Put your event code here
});
The function is useful if you use method chaining when creating your charts:
<script> new RGraph.Scatter({ id: 'cvs', data: [ [12,35],[23,53],[35,35],[45,58],[56,55],[86,86] ], options: { xaxisScaleMax: 100 } }).on('draw', function (obj) { // Put your draw event code here }).on('click', function (e, shape) { // Put your click event code here }).draw(); </script>
RGraph.Scatter.random(object)
This method can be used to create a random set of data if you're creating an example chart and don't want to manually generate lots of dummy data. The only (optional) argument is an object which can contain the following keys:
count
The number of points to generate. Default: 20xmin
The minimu X value. Default: 0xmax
The maximum X value. Default: 10ymin
The minimum Y value. Default: 0ymax
The maximum Y value. Default: 10tooltip
Whether a tooltip is generated. Default: false
<script> var data = RGraph.Scatter.random({ count: 50, xmax: 365, ymax: 100, tooltip: true }); </script>
obj.exec(function)
The exec function is documented here.
obj.responsive(configuration)
The responsive
function helps your charts
respond to different browser window sizes and screen
resolutions. For example, for smaller screens, you
might want to have angled labels or show shorter
versions of them completely.
Update: There is now the responsive configuration option available to you and this is now the preferred method of configuration.
The responsive function and configuration option are documented on their own page here.
Box/Whisker (candlestick) plots
Instead of a single Y value, you can specify an array of 5, 6, 7 or 8 values, which will be used to make a box plot (also known as a candlestick plot). These values are (in order):
- Lower whisker
- Bottom of the box
- Middle value (which isn't necessarily in the center of the box - this depends on your data)
- Top of the box
- Upper whisker
- Upper color (optional)
- Lower color (optional)
- Width (optional)
<script> new RGraph.Scatter({ id: 'scatter8', data: [ [10,[1,1,16,24,24, 'red', 'green']], [105,[5,10,15,25,25, 'red', 'green']], [125,[10,15,25,35,45, 'red', 'green']], [325,[10,15,25,35,45, 'red', 'green', 30]] ], options: { title: 'An example of a boxplot', xaxisLabels: ['Q1', 'Q2', 'Q3', 'Q4'], xaxisScaleMax: 365, yaxisScaleMax: 50, boxplotWidth: 12 // the default width } }).draw(); </script>
Capped ends
For better compatibility with stock charts, you can now specify that the
horizontal lines at the ends of the box plot
are not shown with the boxplotCapped
option.
Specific points for labels on the x-axis
Instead of a simple string that's used as the label, each entry of the labels array can be a two-element array consisting of the label and the X value that the label should be placed at. For example:
scatter.set({ xaxisLabels:[ ['Quarter 1', 0], ['Quarter 2', 90], ['Quarter 3', 181], ['Quarter 4', 273] ] });
Custom tickmarks
If none of the available tickmark styles are suitable, you can specify a function that draws the tickmark, enabling you to draw the tickmark yourself. For example:
<script> // // The function that is called once per tickmark, to draw it // // @param object obj The chart object // @param object data The chart data // @param number x The X coordinate // @param number y The Y coordinate // @param number xValue The X value // @param number yValue The Y value // @param number xMax The maximum X scale value // @param number yMax The maximum Y scale value // @param string color The color of the tickmark // @param number dataset The index of the data (which starts at zero // @param number index The index of the data in the dataset (which starts at zero) // // You can set the function in the regular chart configuration: // tickmarksStyle: function (obj, data, x, y, xValue, yValue, xMax, yMax, color, dataset, index) { // Draw your custom tick here }, // // Or you can set it seperately using the obj.set() function: // line.set('tickmarksStyle', function (obj, data, x, y, xValue, yValue, xMax, yMax, color, dataset, index) { // Draw your custom tick here }); </script>
As of August 2014 you can also specify an image to use as a tickmark. Various styles of URL are supported:
obj.set({tickmarks: 'image:foo.png'}); // Starts with image: prefix obj.set({tickmarks: '/images/foo.png'}); // Starts with a / obj.set({tickmarks: '../images/foo.png'}); // Starts with ../ obj.set({tickmarks: 'data: ...'}); // Starts with data: (for inline images) obj.set({tickmarks: 'images/foo.png'}); // Starts with images/
Note about colors and the key
If you're using a key you may need to set lineColors
to
allow it to use the correct colors. For example:
obj.set('lineColors', ['red','green','blue']);
Note about the crosshairs event
With the Scatter chart
you can use the crosshairs
custom
event to pull out the crosshair coordinates like this
(the coordinates are only available if you have them displayed):
function myFunc (obj)
{
var xCoord = obj.canvas.__crosshairs_x__;
var yCoord = obj.canvas.__crosshairs_y__;
}
RGraph.addCustomEventListener(obj, 'crosshairs', function ()
{
// Handle the event here
});
Adding a trend line to your chart
Since version 5.22 RGraph has supported trend lines on the
Scatter chart
. This is as easy as setting
the trendline
option to true and RGraph will
calculate the best-fit line for your data.
The Scatter chart
example linked at the top of the page
is using the
trendline
option and
there's also an example shown below:
<script>
new RGraph.Scatter({
id: 'cvs',
data: [[1,56],[2,45],[3,48],[4,65],[5,66],[6,70],[7,71],[8,69],[9,75],[8,76]],
options: {
yaxisScaleMax:100,
yaxisScaleMin:40,
xaxisScaleMax: 10,
xaxisLabels: ['A','B','C','D','E','F','G'],
trendline: true,
trendlineColor: 'red',
trendlineDashed: false
}
}).draw();
</script>
There are a few ways to configure the lines which you can see
in the trend line section
of the api
documentation.
Note about the data_arr array
Sometimes you may wish to view your data as one big array, instead of one array per dataset. In this case, theobj.data_arr
is available. This is one long array containing all of
the individual data points. Remember that
with the Scatter chart
the data points themselves are arrays/objects of
X/Y/color/tooltip etc information.
DateTime based charts
Instead of using a number as the X coordinate, you can use a
DateTime
value instead. Likewise, you can use
the same style Date/Time
values as the xaxisScaleMin
and
xaxisScaleMax
values. The underlying Date/Time
parsing uses
the
Date.parse
function (via the RGraph.parseDate
function) so you can use values such as: 2012-01-01 00:00:00
There's an example of a Date/Time
chart in
the download archive
(scatter-date-time-values.html
)
Update (version 5.25) - Moment.js added to RGraph
The Date/Time
parsing in RGraph is versatile and recognises a lot of formats. The Moment.js
library however is a dedicated library for parsing and manipulating dates and times. From
version 5.25 the Moment.js
library is bundled with RGraph. You can include it in your page
by including the file RGraph.common.moment.js
in your page. Once you've done
that you can use the Moment.js
api
to manipulate dates as you require. Here's a very simplistic
example of using Moment.js
to set the minimum and maximum values of a Scatter chart
:
new RGraph.Scatter({ id: 'cvs', data: data, options: { tickmarksSize: 10, xaxisTickmarksCount: 7, xaxisScaleMin: moment('2020-01-01'), xaxisScaleMax: moment('2020-01-01').add(1, 'year'), backgroundGridVlines: false, marginRight: 100 } }).draw();
The html
tag to include the Moment.js
library in your page is this:
<script src="RGraph.moment.js"></script>
Bubble charts
The RGraph Scatter chart
can show Bubble charts
natively. From
version 5.26 the way you make Bubble charts
has changed and been integrated into
the Scatter chart
.
There's an example of the code that's necessary to show this type of chart shown below. The various properties are:
<script> // Create and configure the Scatter chart scatter = new RGraph.Scatter({ id: 'cvs', data: [ [30,15, 'red', 'Red bubble tooltip'], [60,5, 'blue', 'Blue bubble tooltip'], [90,8, 'pink', 'Pink bubble tooltip'], [120,19, 'green', 'Green bubble tooltip'], [150,14, 'gray', 'Gray bubble tooltip'], [50,12, 'red', 'Red bubble tooltip'], [180,24, 'gray', 'Gray bubble tooltip'], [250,21, 'black', 'Black bubble tooltip'] ], options: { xaxisScaleMax: 365, xaxisLabels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], textSize:14, backgroundGridVlines: false, backgroundGridBorder: false, xaxisTickmarks:false, yaxisTickmarks:false, xaxisLinewidth: 2, yaxisLinewidth: 2, tooltipsHotspot: 10, title: 'A bubble chart', titleBold: true, titleSize: 16, titleY: '-5', bubbleMin: 0, bubbleMax: 100, bubbleWidth: 50, bubbleData: [60,60,70,80,90,84,86,87] } }).draw().on('mouseout', function (e) { RGraph.hideTooltip(); RGraph.redraw(); }); </script>
The Lasso feature
The Lasso feature is new in version 6.13
- it
allows you to select points on your Scatter chart
and
highlight them. There are a number of properties that are
available to you that allow you to customise that appearance
and how the feature behaves (for example a callback
function so that you can integrate it into your existing code
along with persistence, custom persistence load/save
functions and appearance customisation).
You can read the property descriptions here.
Note:
There's an obj.clearLassoState()
function that
you can use if you want to clear the current selections. You'll
need to call RGraph.redraw()
after using this
function. For example:
<button onclick="myScatter.clearLassoState(); RGraph.redraw();">Reset the canvas</button>
Here's a full example:
<script> data = [ [10,1],[10,2],[10,3],[10,4],[10,5], [20,1],[20,2],[20,3],[20,4],[20,5], [30,1],[30,2],[30,3],[30,4],[30,5], [40,1],[40,2],[40,3, 'red', 'Hello!'],[40,4],[40,5], [50,1],[50,2],[50,3],[50,4],[50,5], [60,1],[60,2],[60,3],[60,4],[60,5] ]; // Create and configure the Scatter chart scatter = new RGraph.Scatter({ id: 'cvs', data: data, options: { lasso: true, //lassoStroke: '#006', //lassoFill: '#f006', //lassoLinewidth: 1, //lassoHighlightLinewidth: 2, //lassoHighlightStroke: '#0000', //lassoHighlightFill: 'red', //This callback is called what points are cleared // //lassoClearCallback: function (state) //{ // $c(state); //}, // When points are selected - this callback function // is called // //lassoCallback: function (state) //{ // //$c(state); //}, // Whether to enable persistence or not. If nothing // else is specified then the state information is // stored in the window.localStorage variable lassoPersist: true, // Store the state information in the browser-based // window.localStorage variable lassoPersistLocal: true, //lassoPersistSave: function (state) //{ // // Store the state information (for example, // // in a database). The state information is // // in the form of a JSON object. // // console.log(state); //}, //lassoPersistLoad: function () //{ // // Get the data (for example, from a database, // // and return it (it should be a valid JavaScript // // object). // // // // return state; //}, xaxisScaleMax: 365, backgroundGridVlines: false, backgroundGridBorder: false, xaxis: false, yaxis: false, tickmarksStyle: 'circle', tickmarksSize: 8, } }).draw(); </script>
Also, you can double-click on a selection rectangle that you've
added to remove it. And you can double click on an empty
area of the canvas
to get rid of all of the
selection rectangles.
Marimekko charts
The RGraph Scatter chart
now (v6.14+
)
has the
ability to create Marimekko charts
. These could be
likened to
Histogram charts
or stacked Bar charts
because of the way that
they present data. Each stack of segments can take up an
arbitrary amount of space depending on the proportion of the
X value. The array
of Y values that you provide is then
organised much like a stacked Bar chart
with the
values
converted to percentages so the total Y value adds up to
100%
. The code that creates the chart that's
shown here is below.
<script src="RGraph.common.core.js" ></script> <script src="RGraph.common.dynamic.js" ></script> <script src="RGraph.common.tooltips.js" ></script> <script src="RGraph.scatter.js" ></script> <script> // Use the dedicate Marimekko class to create the chart new RGraph.Scatter.Marimekko({ id: 'cvs', data: [], // The Marimekko data is given as a property instead of here options: { // The Marimekko data marimekkoData:[ [5,[4,8,6,6]], [3,[4,5,1,1]], [6,[9,6,3,2]], [4,[8,5,2,3]] ], marimekkoLabels: ['John','Larry','Peter','Barry'], marimekkoLabelsIngraph: true, marimekkoLabelsIngraphUnitsPost: '%', marimekkoTooltips: '%{property:marimekkoLabels[%{dataset}]} on %{property:days[%{index}]}', days: ['Monday','Tuesday','Wednesday','Thursday'], marginLeft: 80, tooltipsCss: { fontSize: '20pt' }, xaxisScale: true, xaxisScaleUnitsPost: '%' } }).draw().responsive([ {maxWidth:null,width:700,height:350,options:{textSize: 20,marimekkoLabelsIngraphSize:14},parentCss:{'float':'right', textAlign: ''}}, {maxWidth:750,width:400,height:200,options:{textSize: 10, marimekkoLabelsIngraphSize:10},parentCss:{'float':'none', textAlign: 'center'}} ]); </script>
The coordinates properties
As well as coordinates for regular Scatter charts
there also arrays
that hold information
about bubbles on Bubble charts
and the
rectangles when you're showing
Marimekkocharts
.
-
obj.coords
Like other chart types thisarray
is a record of all the points and their coordinates on the chart but inlike other charts it is NOT a sequentially indexedarray
- it's indexed by dataset and then by index - just like theobj.coords2
array
on theBar chart
. Each entry conatins:x
coordinatey
coordinate- Tooltip
-
obj.coordsBubble
If you're showing aBubble chart
then this will containarrays
for each bubble and thosearrays
will contain:x
coordinatey
coordinateradius
- color (a
canvas
gradient by default)
-
obj.coordsMarimekko
The Marimekko chart is made up of rectangles and so each "coordinate" is actually made up ofx
y
width
andheight
values. Theobj.coordsMarimekko
variable maintains a record of these values. This variable is a two-dimensionedarray
and each value is anarray
which contains the four dimensions. So you could, for example, have these values:obj.coordsMarimekko[0][0][0]
obj.coordsMarimekko[0][0][1]
obj.coordsMarimekko[0][0][2]
obj.coordsMarimekko[0][0][3]
obj.coordsMarimekko[0][1][0]
obj.coordsMarimekko[0][1][1]
obj.coordsMarimekko[0][1][2]
obj.coordsMarimekko[0][1][3]
obj.coordsMarimekko[1][0][0]
obj.coordsMarimekko[1][0][1]
obj.coordsMarimekko[1][0][2]
obj.coordsMarimekko[1][0][3]
obj.coordsMarimekko[1][1][0]
obj.coordsMarimekko[1][1][1]
obj.coordsMarimekko[1][1][2]
obj.coordsMarimekko[1][1][3]
-
obj.coordsText
This holds the coordinates of all of the text that has been added to the chart. Even if the text is blank (ie no text) then the coordinates will be added to this variable.
How to make trendline/dual-color Scatter charts
This type of chart has been made far easier thanks to
the clip
property which was introduced in version 6.17
It was perfectly possible before this feature was
introduced - it's just been made easier. Also, it's made
easy to implement because all of the necessary
configuration is hidden away in a new function which
does the hard parts for you. Here's some example code
for the canvas
Scatter chart
.
You can see this code in the download archive in a demo
called scatter-trendline.html
<script> // Data for the Scatter chart (lots of it) data = [ [6347.82,0.69], [8956,0.51], [5620,0.34], [8092,0.34], [5069,0.8], [5924,0.05], [7851,0.2], [2065,0.72], [3872,0.29], [6521.73,0.50], [28501,0.37], [18344,0.37], [26561,0.39], [21391.30,0.33],[24628,0.4], [24670,0.46], [15689,0.76], [8000,0.70], [23921,0.43], [30434.78,0.56],[18809,0.96], [24695.65,0.18],[16000,0.33], [27445,0.59], [11926,0.21], [16819,0.78], [21739.13,0.69],[8956.52,0.74], [28059,0.61], [20458,0.19], [23079,0.2], [20762,0.48], [17547,0.54], [28706,0.72], [22361,0.48], [8956.52,0.79], [21696,0.59], [17026,0.65], [12766,0.67], [22618,0.5], [23902,0.59], [24539,0.54], [23700,0.6], [22334,0.29], [24830,0.66], [10086.95,0.39],[12263,0.4], [26057,0.22], [28744,0.94], [12151,0.16], [22528,0.37], [18521.73,0.22],[32173.91,0.36], [29355,0.87], [17036,0.52], [32000,0.44], [24312,0.58], [29227,0.71], [24173,0.29], [18070,0.66], [13321,0.34], [25660,0.47], [23860,0.26], [17391.30,0.16],[25217.39,0.74], [20115,0.53], [18988,0.19], [28591,0.68], [8956.52,0.26], [26695.65,0.78],[13234,0.18], [20197,0.73], [20187,0.77], [20888,0.29], [21652.17,0.22],[29348,0.77], [14869.56,0.63], [10909,0.55], [18173.91,0.30],[12372,0.5], [24173.91,0.8], [28173.91,0.28],[16521,0.22], [16905,0.87], [24099,0.36], [15210,0.18], [24069,0.44], [15062,0.49], [22162,0.17], [30521.73,0.37],[24838,0.42], [19236,0.2], [12402,0.51], [29949,0.88], [24314,0.3], [29584,0.84], [21705,0.6], [11651,0.32], [15174,0.85], [26007,0.92], [26603,0.22], [21484,0.87], [24855,0.37], [15524,0.91], [16521.73,0.37], [28304,0.82], [17427,0.45], [27818,0.81], [17215,0.75], [11935,0.79], [12761,0.51], [11185,0.31], [12103,0.62], [17421,0.63], [21176,0.77], [17941,0.4], [18080,0.84], [32173.91,0.51],[22556,0.85], [22592,0.24], [29128,0.79], [32260.86,0.76],[26192,0.28], [22912,0.34], [18429,0.54], [23469,0.36], [19356,0.38], [15321,0.43], [23020,0.73], [17212,0.23], [28172,0.49], [24610,0.26], [28472,0.59], [19744,0.66], [15460,0.5], [28877,0.37], [29870,0.39], [23475,0.47], [25629,0.7], [10521.73,0.14],[27358,0.75], [28036,0.97], [19552,0.86], [25319,0.6], [29466,0.95], [18861,0.88], [29852,0.88], [28877,0.89], [27523,0.56], [13435,0.12], [29399,0.58], [21698,0.9], [14347.82,0.26], [28909,0.36], [20870,0.25], [26751,0.76], [24434.78,0.87], [12079,0.15], [16765,0.1], [11674,0.6], [11058,0.78], [11844,0.3], [14777,0.36], [20823,0.91], [15992,0.23], [26171,0.85], [19652.17,0.11],[22841,0.62], [21527,0.52], [27084,0.32], [28173.91,0.87],[20249,0.95], [12818,0.24], [13924,0.14], [22007,0.4], [12560,0.71], [17194,0.75], [14173.91,0.70],[11808,0.34], [29015,0.82], [10000,0.23], [23854,0.76], [10260.86,0.65],[25037,0.29], [17254,0.25], [20473,0.85], [23831,0.3], [19478.26,0.28],[15871,0.81], [21073,0.15], [8869.56,0.16], [13192,0.8], [24882,0.56], [27202,0.68], [24327,0.29], [7826.08,0.63], [29565.21,0.473], [17058,0.82], [19212,0.53], [16224,0.6], [11975,0.85], [18575,0.8], [26226,0.58], [17591,0.1], [23667,0.63], [18782.60,0.14],[16372,0.77], [30173.91,0.26],[21435,0.84], [25027,0.31], [36356,0.5], [36284,0.53], [44203,0.76], [44869.56,0.86],[33485,0.73], [38798,0.75], [34666,0.85], [39210,0.63], [45565.21,0.63],[42947,0.91] ]; // Configuration options that are given to both Scatter charts options = { trendline: true, trendlineMargin: 15, trendlineDashed: true, xaxisLabels: RGraph.MONTHS_SHORT, linewidth: 1, spline: true, shadow: false, marginInner: 25, tickmarksStyle: 'cross', tickmarksStyle: 'dot', tickmarksSize: 6, backgroundGridVlines: false, backgroundGridBorder: false, backgroundColor: 'white', xaxisLinewidth: 2, yaxisLinewidth: 2, xaxisTickmarksLength: 5, yaxisTickmarksLength: 5, yaxisTickmarksLastBottom: true, xaxisTickmarksLastLeft: true, textSize: 16, colors: ['black'] }; // // This is all the code that's necessary to produce the // dual-color Scatter chart // [scatter1, scatter2] = RGraph.Scatter.dualColorTrendline({ id: 'cvs', data: data, options: config, // The configuration options for both of the charts optionsTop: {colorsDefault: 'black'}, // Configuration options for just the top chart optionsBottom: {colorsDefault: 'red'}, // Configuration options for just the bottom chart animationEffect: 'trace', // The animation effect to use (for both charts) animationEffectOptions: {frames: 120}, // Any options to give to the animation effect animationEffectCallback: function () {alert('Finished!');} // Optional callback function }); </script>
Events
RGraph supports custom events that allow you to easily add interactivity to your charts if required. The following events are available:
annotatebegin
This event fires at the start of annotating - like the standardmousedown
event.annotate
This event fires (repeatedly) during annotating - like the standardmousemove
event.annotateend
This event fires at the end of annotating - like the standardmouseup
event.annotateclear
This event fires at the end of theRGraph.clearAnnotations
function.beforeclear
This event fires at the start of theRGraph.clear
function.clear
This event fires at the end of theRGraph.clear
function.click
This is similar to the standardcanvas
click
event but this only fires when you click on a bar - not the wholecanvas
.beforecontextmenu
This event fires when you have the contextmenu enabled and it is about to appear.contextmenu
This event fires when you have the contextmenu enabled and it has been displayed.beforedraw
This event fires at the start of thedraw
method before anything has been done.firstdraw
This event fires at the end of thedraw
function - but only the first time that thedraw
function is called.draw
This event fires at the end of thedraw
function.beforeinteractivekey
When you're using the interactive key this event fires just before the key and chart are highlighted.afterinteractivekey
When you're using the interactive key this event fires just after the key and chart are highlighted.keyclick
This event fires when you click on the key - you don't have to be using the interactive key however.mousemove
This event is similar to the standardmousemove
event but only fires when you move the mouse over a bar on the chart.mouseover
This event is similar to the standardmouseover
event but only fires when you move the mouse over a bar on the chart.mouseout
This event is similar to the standardmouseout
event but only fires when you move the mouse away from a bar on the chart that you've previously hovered over.beforetooltip
This event fires at the start of the tooltip showing process.tooltip
This event fires after a tooltip has been shown.beforebackground
This event fires before the background (grid, image, bars etc) has been drawn.background
This event fires after the background (grid, image, bars etc) has been drawn.
new RGraph.Scatter({ id: 'cvs', data: [[5,3],[6,5],[4,8]], options: { } }).on('draw', function (obj) { console.log('The draw event has fired'); }).draw();
Effects
These effects are available and can be used instead of thedraw
function. There are also generic effects available which
you can see here: Generic effects and transitions
There's a stopAnimation()
function that you can
use to stop an animation immediately if you need to.
There's a line chart demo called
demos/line-effects-stop-animation.html
in
the download archive
that demonstrates the use of this function.
- The
trace
effect (effects-scatter-trace2.html
in the download archive) -
The
explode
effect (effects-scatter-explode.html
in the download archive). With this effect you can set the origin of the explosion by using theoriginx
andoriginy
options like this:myScatter.explode({frames: 60, originx: 'center', originy: 'center'})
The possible values for theoriginx
option are:left
center
right
and the possible values for theoriginy
option are:bottom
center
top
<script> // Optional callback function that's called when the effect is complete function myCallback (obj) { // ... } new RGraph.Scatter({ id: 'cvs', data: [[5,5],[10,10],[15,15],[20,20]], options: { xaxisScaleMax: 90 } }).trace({frames: 60}, myCallback) </script>