Learning jqPlot

5 (2 reviews total)
By Scott Gottreu
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting Started

About this book

jqPlot is a charting and plotting plugin for the jQuery framework with numerous chart style options, and is a great tool to build data visualizations. Using jqPlot, you can create bar charts, pie charts, and even stock market charts. It is more than just a plugin for jQuery; you can design, build, and integrate graphs in a far more straightforward manner than popular feature-rich options such as Highcharts.

This book empowers you to create highly-customized charts and graphs that present your data in a visually appealing and analytic manner. Starting with a basic line graph, you'll cover the other standard charts as well as some of the not-so-standard ones. If you want to be leaps and bounds ahead of your colleagues when it comes to developing graphs and charts for your web applications, this book is the answer.

Publication date:
August 2014
Publisher
Packt
Pages
240
ISBN
9781783981168

 

Chapter 1. Getting Started

As we begin this journey, we will look at the advantages of jqPlot over other web-based charting tools. We will look at the basic options available to us in jqPlot as we hit the ground running and create charts based on our company's data. In this chapter, we will cover the following topics:

  • Review the components of a chart

  • Learn the different ways of creating a chart in jqPlot

  • Create arrays that contain values for our x and y axes and pass these into jqPlot

  • Use a plugin that allows us to use dates for our x axis

  • Create multiple lines on our chart

  • Add multiple y axes to our chart

  • Add a legend to one of our charts

  • Set different options for our lines and use different marker options

 

Reviewing the components of a chart


Let's think back to our high school Math class where our teacher discussed charts and graphs. You might have been like me and wondered how you would apply this in real life. Fast forward to today and your boss dropping a stack of files on your desk just made it real.

We will use line charts as a basis for our review of the parts of a chart. Line charts are one of the most popular charts to use, while also being the simplest to understand and implement with jqPlot. Line charts are mainly used to show how data changes over time, but they can also be used to show how one dataset impacts another. For example, we can show how the number of social media shares affect revenue or how sales in different divisions affect the gross profit margin.

With this in mind, we need to look at the components of a chart. There are two axes, the x axis and the y axis. Some might think of these as independent variables and dependent variables, but they are more scientific labels. An easier way to think of the two axes would be cause and effect. Our y axis generally represents the dependent variable or effect, which for instance, can be the amount of profit generated during a given time period, or the total revenue generated by a sales associate.

Our x axis generally represents the independent variable or cause. Most line charts show trending data over time, where our x axis covers certain time frames such as days, weeks, or years. Usually, we have a set range of data points on our x axis, as a result of which our y axis will have data points that may vary greatly. If we had a chart showing the revenue generated by sales associates, their names would be on the x axis. The sales associates interact with the customers and generate the sales that provide the revenue.

A few other pieces of a chart to keep in mind are the grid and ticks. The ticks denote certain values along the axis. The grid represents the lines running vertically and horizontally, connecting the ticks on both axes. The grid makes it easier to decipher the value of each point of a line on the chart. The following diagram shows how each of these pieces composes a chart:

 

Getting a promotion


Calvin, our boss, stops by our office and informs us that all the regional managers will be coming to the corporate offices for a quarterly meeting on Friday. Since it is Monday, we should be able to meet this goal. He wants us to create a few pages for our intranet, showing things such as profit, revenue, and expenses.

"We've got to impress them," he says as he leaves. We stare at each other, simply bewildered. You mention that we just became business analysts as well as developers.

We start to work in our newfound roles. You begin to find the data that will be required. Since we are creating prototypes, we need to manually compile the data for now.

I start researching web-based charting tools and come across three main contenders: Highcharts, D3.js, and jqPlot. We will have to pay a licensing fee to use Highcharts for our company. D3.js has a beautiful gallery of available charts, and it looks like it has a very high learning curve. It appears that jqPlot has a lower learning curve and we will be building charts faster with jqPlot than with D3.js. The other benefit of jqPlot is that it does not require a commercial license.

 

Creating a jqPlot chart


Download the current version of jqPlot and extract the files to your web server. We'll create the most basic chart we can, as shown in the following steps:

  1. We start by building our HTML file, including jQuery. We also include the jqPlot JavaScript and CSS files from the downloaded ZIP file. We must include jQuery because jqPlot is a plugin for jQuery, which means that it needs jQuery to function properly:

    <!doctype html>
        <head>
          <title>Learning jqPlot</title>
          <meta charset="utf-8">
          <link rel="stylesheet" href="/css/jquery.jqplot.min.css">
         <script src="../js/jquery.min.js"></script>
          <script src="../js/jquery.jqplot.min.js"></script>
        </head>
        <body>

    Note

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you

  2. Next, we create the div element that will contain our chart. We set id to firstChart so that jqPlot will know where to build our chart. Since we are just creating prototypes, we will set the width of our div inline, as shown in the following code.

       <div id="firstChart" style="width:600px"></div>
  3. Finally, we create our jqPlot object and store it in the plot variable. Then, we pass the id attribute of the div, which is firstChart. Finally, we include an array of numbers inside another array, which will be our data points. This is the simplest way to pass in the data:

        <script>
        $(document).ready(function(){
          var plot = $.jqplot ('firstChart', [[1,9,4,3,8,5]]);
        });
        </script>
    </body>
    </html>

Note

We can also create our chart by chaining the jqPlot plugin to the jQuery selector of our div. It will look like the following:

$("#firstChart").jqplot ([[1,9,4,3,8,5]]);

In our examples, we will store our objects in variables so that they are available globally in our JavaScript if required.

jqPlot will interpret each number as a point on the y axis, and it will assign a value for the x axis, starting with 1. We can see the result of our effort in the following screenshot:

 

Passing in both x and y values


The next option to pass in data to the chart is to use a two-dimensional array. Our inner array contains individual arrays, which in turn contain the value for x axis followed by the value for y axis. When we include both x and y values, our data points may not increment at a constant interval, as was the case in our previous chart:

   <script>
   $(document).ready(function(){
     var secondPlot = $.jqplot ('secondChart', [[[5,4],[10,7],[15,6],[20,9]]]);
   });
   </script>
   <div id="secondChart" style="width:400px;"></div>

We load this new chart in our web browser, and the results are as shown in the following figure:

 

Using dates for the x axis


As we finish our first experiment, you mention that you've found the revenue numbers for the last 7 days. We decide that it will be best if we can show the dates on the x axis and not use arbitrary numbers.

We will need to make use of one of the renderers available in jqPlot. A renderer extends the basic functionality of jqPlot. Some renderers take the data and render it in different chart types. Other renderers format text in different ways. For our next chart, we will use dateAxisRenderer, which will take our human-readable dates and convert them into values for jqPlot to render:

  1. We start by including the dateAxisRenderer.js file in our HTML, as shown in the following code:

    <script src="../js/jqplot.dateAxisRenderer.min.js"></script>
  2. To make it easier to keep track of our data, we will store it in an array and then pass that variable into our plot. Our array contains arrays with the x and y values for each data point. The date is the x value, and the second number is our y value:

    <script>
    $(document).ready(function(){
        var revenue = [['2012-10-25',258142], ['2012-10-26',267924],['2012-10-27',239140], ['2012-10-28',230107], ['2012-10-29',264397], ['2012-10-30',276369], ['2012-10-31',285050]];
  3. Next, we declare the variable for our chart. We pass in the ID of the div, and then pass in the revenue array. No matter how many data arrays we create, they will all be housed inside another array. We also want to set some options for our chart. This is accomplished by passing a jQuery object as the third parameter:

      var revenuePlot = $.jqplot ('revenueChart', [revenue],
         {
  4. After creating the object, we set the title option and then create an object for our axes:

      title:'Daily Revenue',
      axes:{
  5. We set the renderer option for the x axis. We will pass in the DateAxisRenderer class. Since it is a class, we will not place it inside quotes. Also, we will not add parentheses to the end of the class name. This will instantiate our class:

      xaxis:{
        renderer:$.jqplot.DateAxisRenderer,
        label: 'Days of the Month'
      },
  6. For the yaxis option, we set our label and use the formatString option to format our values as currency. The dollar sign in formatString adds a dollar sign to the beginning of the tick. The apostrophe states we want a thousands place separator. Finally, the d expression tells jqPlot to treat the tick as a number. We complete the page by including the div element to contain our chart:

          yaxis:{
            label: 'Revenue in Dollars',
            tickOptions: { formatString: "$%'d" } 
          }
        }
      });
    });
    </script>
    <div id="revenueChart" style="width:600px;"></div>

    Note

    Because of issues with time zones and how browsers calculate dates, it's best to include a time along with the date. The date renderer will also accept epoch timestamps. We need to keep in mind that if a time zone is not included in our date string, JavaScript will default to the time zone of the browser.

With our new chart complete, we load the page in our browser and see the result in the following figure:

 

Adding multiple data series


This is a nice start, but we both agree that the leadership is going to want more than just a couple of days of revenue on a chart. Our next chart will display the profit and revenue numbers for the last 12 months. We will only need to make a few adjustments to our previous chart:

  1. We include both arrays containing our revenue and profit figures:

    <script src="../js/jqplot.dateAxisRenderer.min.js"></script>
    
    <script>
    $(document).ready(function(){
    
      var revenue = [['2011-11-20', 800538], ['2011-12-20', 804879], ['2012-01-20', 847732], ['2012-02-20', 795758], ['2012-03-20', 835554], ['2012-04-20', 844379], ['2012-05-20', 828510], ['2012-06-20', 753984], ['2012-07-20', 807403], ['2012-08-20', 755840], ['2012-09-20', 775304], ['2012-10-20', 781322]];
    
      var profit = [['2011-11-20', 192049.56], ['2011-12-20', 188744.75], ['2012-01-20', 197352.54], ['2012-02-20', 190106.74], ['2012-03-20', 193453.07], ['2012-04-20', 197249.69], ['2012-05-20', 205480.18], ['2012-06-20', 177648.78], ['2012-07-20', 193793.82], ['2012-08-20', 183221.56], ['2012-09-20', 192797.31], ['2012-10-20', 182451.68]];
  2. We modify the variable name for our object and create a new ID attribute. Next, we combine both arrays into a container array and pass it into jqPlot. Within jqPlot, each array containing data is called a series and both series will appear on the same y axis:

      var rev_profit = $.jqplot ('revenueProfitChart', [revenue, profit],
      {
  3. We modify the title and the labels for our axes. We also update the ID of our div element:

        title:'Monthly Revenue & Profit',
        axes:{
          xaxis:{
            renderer:$.jqplot.DateAxisRenderer,
            label: 'Months'
          },
          yaxis:{
            label: 'Totals Dollars',
            tickOptions: { formatString: "$%'d" } 
          }
        }
      });
    });
    </script>
    <div id="revenueProfitChart" style="width:600px;"></div>

We load the page in the browser and smile. The changes to the chart get us closer to what the management is looking for. We can see the results of our efforts in the following figure.

Adding multiple y axes

The two data series are really far apart in their values. It's hard to decipher the value of each point by just looking at the chart. We'll put each series on its own y axis. This will make it easier to see interactions between our revenue and profit. We revisit the code and begin to alter it to separate the y axes.

  1. We start by adding the series option. It is an array containing an object for each data series. For the first series, we can leave the default settings in place. So, we simply pass in an empty object. The second series will be on the second y axis, which means that we enter y2axis for the yaxis option. The ticks and label for this axis will appear on the right-hand side of our chart:

      var rev_profit = $.jqplot ('revenueProfitChart', [revenue, profit],
      {
        title:'Monthly Revenue & Profit',
        series:[
          {},
          {yaxis:'y2axis'}
        ],
    
  2. We change the label for yaxis to Revenue. We copy all these options for y2axis. We then change the axis option and the label:

        axes:{
          xaxis:{
            renderer:$.jqplot.DateAxisRenderer,
            label: 'Months'
          },
          yaxis:{
            label: 'Revenue',
            tickOptions: { formatString: "$%'d" } 
          },
          y2axis:{
            label: 'Profit',
            tickOptions: { formatString: "$%'d" } 
          }
        }
      });

We load this new chart in our browser. The fruit of our labors can be seen in the following figure:

We begin to study the chart. It appears that profit as a part of revenue is better in some months when compared to other months, but we can't draw any clear conclusions from this chart. However, this can be a springboard to try to track down some correlations.

 

Adding a legend


As we study the chart, we lose track of which line represents revenue and which represents profit. We'll need a legend to solve this problem:

  1. We start by adding labels to each of our series objects. We add a label object to our empty object for the first data series. For the second series, we add the label option alongside the existing yaxis option.

    title:'Monthly Revenue & Profit',
    series:[
      { label: 'Revenue' },
      { label: 'Profit', yaxis:'y2axis' }
    ], 
  2. Next, we add a legend option. In order for the legend to appear, we must set the show option to true. We also set placement to outsideGrid. The other two options available to us are insideGrid and outside. The outsideGrid option will place the legend outside the grid, but inside the plot object. Hence, the grid will be resized to accommodate the legend:

    legend: {
      show: true,
      placement: 'outsideGrid'
    },

We finish the updates to our new chart and open our web browser again. We now have a legend that will help us decipher our chart, which can be seen in the following figure:

Note

The insideGrid option will place the legend inside the grid. If we want the legend outside the grid, but we don't want our grid to shrink, we can use the outside option instead. Be aware that with the outside option, our legend can flow outside the plot and overlap other elements on our page.

We finally have a nice report. We call Calvin and ask him to come by and take a look at what we've got so far. We also need some direction on how to proceed. A few minutes later, he swings by our office.

"This is great," he says, "but we're going to need to expand on some of this data. How about we get a report that has last quarter's revenue and break out the profit by each division? Also, can you change the styles on those lines? Add a little flair or something." Calvin walks out and we stare at each other, trying to figure out how to add some "flair" to our report.

Adding line and marker options

We'll keep the first two data series as they are and put all the divisional data on y3axis. You mention that we can use different marker styles to set off the different divisions. We will turn off the line for the revenue and overall profit data series and just show the markers. As for the divisional series, we've got seven different styles to use for our markers, which are the following:

  • circle and filledCircle

  • diamond and filledDiamond

  • square and filledSquare

  • x

This works out well because we've got three major divisions in our data. You find the profit numbers that we will need, and we set to work updating our chart.

  1. We start by including the profit numbers for each division. We also pass the following three data series arrays in to jqPlot:

    <script src="../js/jqplot.dateAxisRenderer.min.js"></script>
    <script>
    $(document).ready(function(){
    
      var revenue = [['2012-07-20', 807403], ['2012-08-20', 755840], ['2012-09-20', 775304]];
      var profit = [['2012-07-20', 193793.82], ['2012-08-20', 183221.56], ['2012-09-20', 192797.31]];
      var electronics = [['2012-07-20', 116276.29], ['2012-08-20', 95867.97], ['2012-09-20', 120591.27]];
      var media = [['2012-07-20', 27596.25], ['2012-08-20', 32396.47], ['2012-09-20', 26709.06]];
      var nerd_corral = [['2012-07-20', 49921.28], ['2012-08-20', 54957.12], ['2012-09-20', 45496.98]];
    
      var rev_profit = $.jqplot ('division_profit', [revenue, profit, electronics, media, nerd_corral],
      {
  2. Now that we have five series across three different axes, we will make use of the seriesDefaults option. By setting yaxis to y3axis, every data series will appear on this axis unless we override this option on the individual series. We also set the style option to filledCircle:

          title:'Q3 Revenue, Profit & Divisional Profits',
          seriesDefaults: {
            yaxis:'y3axis',
            markerOptions: {
              style: 'filledCircle',
              size: 10
            }
          },
  3. Next, we create the series objects for revenue and profit. We set the showLine option to false along with style for markerOptions. Since we set the default axis in seriesDefaults, we also need to override this option:

          series:[
            {    
              label: 'Revenue',
              yaxis:'yaxis',
              showLine: false,
              markerOptions: { style: 'x' }
            },
            {
              label: 'Profit', 
              yaxis:'y2axis',
              showLine: false,
              markerOptions: { style: 'diamond' }
            },
  4. For the Electronics division data series, we use the defaults. For the two remaining series, we set the style option to different values:

            { label: 'Electronics' },
            {
              label: 'Media & Software', 
              markerOptions: { style: 'filledSquare' }
            },
            {
              label: 'Nerd Corral',
              markerOptions: { style: 'filledDiamond' }
            }
          ],
  5. Our next step is to set the default options under axesDefaults. We set the default formatString for currency, but this will cause problems for our x axis:

          axesDefaults: {
            tickOptions: { formatString: "$%'d" }
          },
  6. Since we use the date renderer, we set the formatString option of the x axis to %B, which will output the full month name as the tick. jqPlot automatically calculates how many ticks it thinks we need for our axes. However, jqPlot sometimes creates more than we need. Since this chart deals with quarterly data, we set numberTicks to 3:

          axes:{
            xaxis:{
              label: 'Months',
              renderer:$.jqplot.DateAxisRenderer,
              numberTicks: 3,
              tickOptions: { formatString: "%B" }
            },
            yaxis: { label: 'Revenue' },
            y2axis: { label: 'Profit' }
          }
      }); 
    });
    </script>
  7. With the added axis for our chart, we need to increase the width of our div.

    <div id="division_profit" style="width:650px;"></div>

It was hard keeping track of all these options. We open our web browser, hoping we did everything correctly. We can see the result in the following figure. All the axes have different values. The lines for revenue and profit are missing, just as we wanted, and each data series has a different marker.

Everything worked as we intended, but the chart is hard to read. With the different axes, data points are overlapping. As we continue our research, we might find a better way to represent the same data.

Note

Since our data points are in the middle of the month, jqPlot will add a month to the end of the x axis to keep everything in bounds. If we only want the three months on the graph, we can change the dates to the first of the month.

Calvin stops by later and loves what we have. "This is a great first step. We will need some charts that pull in data from other sources, especially our social media accounts. We will also need to start showing trend lines."

Calvin walks out again without warning, leaving us to stare at each other. We decide we've done what we can for the morning, so we head off to lunch, preparing ourselves to tackle social media and trend lines upon our return.

 

Learning questions


  1. What are the three main parts of a chart discussed in the chapter?

  2. What are the two ways we can create a jqPlot object?

  3. How do we enable a data series to appear on the second y axis?

  4. What are the three placement options for our legend?

  5. What are the four main marker styles?

  6. What values do we set for the formatString option to get a dollar sign and the thousands place separator?

 

Summary


We started the chapter by taking a refresher course on the parts of a chart. Next, we learned the advantages of jqPlot and created our first chart with just a few lines of code. Later, we looked at the different ways to pass in data to jqPlot. We made use of DateAxisRenderer to use dates on the x axis of our charts.

We learned about options such as y2axis, which allowed us to plot our lines on different y axes. We also made use of the legend and markerOptions options to make it easier to discern which line goes with which data series.

In the next chapter, we will look at pulling data from remote sources. We will also create area charts and scatterplots. Along with all of this, we will look at how trend lines work and how to create them.

About the Author

  • Scott Gottreu

    Scott Gottreu has worked across a range of industries; academic, medical, advertising, nonprofit, and private sector organizations. Each time, he expanded his knowledge base while solving problems specific to that sector. He started off in classic ASP and moved on to PHP, and is now using Rails as well. He learned JavaScript and jQuery along the way.

    He currently works for Warren Douglas Advertising in Fort Worth, Texas, where he creates solutions for his company's various clients.

    Browse publications by this author

Latest Reviews

(2 reviews total)
Excellent
Just what I need. useful for practice in work.
Book Title
Unlock this book and the full library for FREE
Start free trial