- HTML5 Data and Services Cookbook
- Gorgi Kosev Mite Mitreski
- 903字
- 2021-08-06 16:50:00
Making a motion chart
When working with a time-based data often you want to have a view, where the time changes will be visualized. One way of doing this is by using a motion chart that updates over time and that is what we will be creating with this recipe.

Getting ready
We will be using a toolkit for creating an interactive graph named Rickshaw that can be retrieved from http://code.shutterstock.com/rickshaw/, and is part of the example code as well. Besides that we also need D3.js
to be included, because Rickshaw is built on top of it.
How to do it...
To create the recipe, we will add JavaScript code that will randomly generate data and create an interactive graph using Rickshaw.
- First, we add the external JavaScript and CSS in the head section. By convention, we can put the vendor libraries in a separate folder
js/vendor/ and css/vendor/
.<!doctype html> <head> <link type="text/css" rel="stylesheet"href="css/vendor/graph.css"> <title>Motion chart</title> <script src="http://d3js.org/d3.v2.js"></script> <script src="js/vendor/rickshaw.js"></script> </head>
- We add the placeholders for the chart in the body section.
<div id="content"> <div id="chart"></div> </div>
- We continue with the main part, the
js/example.js
file, where we first create a color palette, and then the refresh rate.(function () { //create a color palette var palette = new Rickshaw.Color.Palette({scheme: 'munin' }); // we set the refresh rate in milliseconds var refreshRate = 500;
- The next step is to create
Rickshaw.Graph
with SVG of size900px
by600px
and of theline
type. We use the refresh rate we previously selected and the specified color palette.// create graph var graph = new Rickshaw.Graph({ element: document.getElementById("chart"), width: 900, height: 600, renderer: 'line', series: new Rickshaw.Series.FixedDuration( [ { name : 'one' }, { name : 'two' }, { name : 'three' } ], palette, { timeInterval: refreshRate, maxDataPoints: 50 } ) });
- Following this we can add a Y axis to the created graph.
var yAxis = new Rickshaw.Graph.Axis.Y({ graph: graph });
Because we created the required objects, they can get rendered to the screen by calling
.render
on them.graph.render(); yAxis.render();
- We need data to display, so we will generate some random data, and add it to the graph. In order to add the data with a delay, use setInterval on a refreshRate period.
//random util function getRandomInRange(n){ return Math.floor(Math.random() * n); } // generate random data and add it to the graph setInterval( function() { var data = { one: getRandomInRange(50) + 100, two: Math.abs(Math.sin(getRandomInRange(30)+1) ) *(getRandomInRange(100) + 100), three: 400 + getRandomInRange(110)*2 }; graph.series.addData(data); //update graph.render(); yAxis.render(); }, refreshRate );
At this point, we should be seeing something similar to the figure shown in the beginning of the recipe.
How it works...
The Rickshaw.Color.Palette
we picked is with the scheme munin
. There are also other palettes from which we can choose, such as spectrum14
or cool
. The palette is used in order to simplify and automate the picking of the colors for the graph. For example, if we manually call the .color()
method multiple times.
palette.color() "#00cc00" palette.color() "#0066b3" palette.color() "#ff8000"
It will always return the next color. Palette is a set of predefined colors that can be picked between given set of rules. For example, the original Nintendo Game Boy had four shades of green that could be used to display all the games. If we take a look at the implementation of the palettes in Rickshaw, we can notice that they are just a list of colors. The following is a snippet from Rickshaw source code definition of the palette cool
:
this.schemes.cool = [ '#5e9d2f', '#73c03a', '#4682b4', '#7bc3b8', '#a9884e', '#c1b266', '#a47493', '#c09fb5' ];
If we take a look at the Rickshaw.Graph
creation, besides the SVG size, we picked the element with the ID chart
, where the graph will get rendered.
element: document.getElementById("chart")
Additionally, we set the renderer
type to line
, but it can also be set to area
, stack
, bar
, or scatterplot
, depending on the result.
For the series
property we use the following code snippet:
series: new Rickshaw.Series.FixedDuration([ {name: 'one'}, {name: 'two'}, {name: 'three'} ], palette, { timeInterval: refreshRate, maxDataPoints: 50 })
The first argument is the array with data names, after that comes the palette, and last is the options object where we set the update timeInterval
. Additionally, maxDataPoints
was set to 50
, and that one designates how many samples of data are currently displayed, meaning that we would display the last 50 objects.
Later on, we called the .render()
method on the graph
and yAxis
objects for the first time, and afterwards, in the setInterval()
method we called for re-rendering of them on every data change. The data for rendering we constructed had the following format:
var data = { one: someNumber, two: someNumber, three: someNumber };
The preceding format represents a value for the three lines at the specific point of time.
This data object is passed into the series using the addData()
method defined for Rickshaw.Series.FixedDuration
that sets the latest update for the series
property.
graph.series.addData(data);
If we need to get the current data for all the displayed frames, we could call the graph.series.dump()
method.
That for example will return the following result:
Object: color: "#00cc00" data: Array[50] name: "one"
There's more...
There are various ways to customize the chart
ID: filter information, add controls, or feed the data from a remote server. If we want to attach a legend, we can simply create such an object before the graph is rendered, and attach it to our graph object.
var legend = new Rickshaw.Graph.Legend({ element: document.getElementById('legend'), graph: myGraph });
- Flask Blueprints
- 數據庫系統教程(第2版)
- Instant Zepto.js
- Python自動化運維快速入門
- Visual C++串口通信技術詳解(第2版)
- Nexus規模化Scrum框架
- C語言程序設計同步訓練與上機指導(第三版)
- Learning Vaadin 7(Second Edition)
- HTML5與CSS3基礎教程(第8版)
- Learning Laravel's Eloquent
- Raspberry Pi Home Automation with Arduino(Second Edition)
- Cocos2d-x Game Development Blueprints
- Java Web從入門到精通(第3版)
- Advanced UFT 12 for Test Engineers Cookbook
- 零基礎學HTML+CSS第2版