官术网_书友最值得收藏!

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.

  1. 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>
  2. We add the placeholders for the chart in the body section.
    <div id="content">
      <div id="chart"></div>
    </div>
  3. 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;
  4. The next step is to create Rickshaw.Graph with SVG of size 900px by 600px and of the line 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
          }
        )
      });
  5. 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();
  6. 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
  });
主站蜘蛛池模板: 正镶白旗| 久治县| 林甸县| 朝阳县| 松溪县| 师宗县| 潞西市| 西畴县| 葫芦岛市| 西城区| 教育| 清丰县| 高阳县| 政和县| 巴马| 聂荣县| 珲春市| 南丰县| 自治县| 察雅县| 繁峙县| 湘西| 旺苍县| 墨江| 班戈县| 晋州市| 垣曲县| 政和县| 溧阳市| 开封市| 昭觉县| 金塔县| 合阳县| 牟定县| 思茅市| 罗山县| 阿尔山市| 错那县| 凌海市| 化州市| 伊金霍洛旗|