Intro To Visualization API (Part 2): Highcharts And Code

In the first part of this two part series, we looked at how to install the Visualization API module and created a simple chart with just using Views and the Google Visualization API (GVA). We also saw how easy it is to create a chart without having to write any custom code.

In this tutorial, we’ll look at integrating Highcharts library with Visualization API and we’ll create charts programmatically. Just a heads up we’ll look at how to render charts using code, so some PHP knowledge is required for this tutorial.

Highcharts

Highcharts is an amazing charting library written in JavaScript. It is free for non-commercial use if you want to run the library on a commercial website you’ll need a license.

One of the benefits of using Highcharts over GVA is that the data used for the chart stays on your servers. When you use GVA, you have to send data to Google.
If you work with private data that you want full control of, then use Highcharts. If you’re going to use GVA, then understand that your data will be sent over the internet to Google’s servers.
UPDATE: GVA charts are rendered in the browser and no data is sent to Google. Read comment for more details.

Currently Visualization API only supports line, column and pie chart types for Highcharts.

How To Install Highcharts

1. Download and install the Libraries API module.

2. Go to the Highcharts download page, download and extract the zip file into sites/all/libraries/highcharts. Make sure you rename the folder to highcharts (all lower case). The path to highcharts.js should be sites/all/libraries/highcharts/js/highcharts.js.

How To Use Highcharts With Views

In the part one of this tutorial, we created a view called “Comment Chart” which displays a list of articles with the most comments sorted from highest to lowest. We’ll continue using this existing view for this tutorial. If you’re following along with this tutorial and haven’t created the view, go back to the last tutorial and create it.

We need to configure Visualization API to use Highcharts as the preferred charting library.

It is important to understand that you can only use a single charting library at a time.

1. Go to Configuration -> Visualization (admin/config/system/visualization).

2. Change the “Preferred charting library” drop-down list to Highcharts and click on “Save configuration”.

Fig 1.0

3. Now, test the chart by going to the view that we created in the last tutorial. Go to /comment-chart and if everything is setup properly you should see a chart like the one below.

Fig 1.1

If you get a “page not found” error when you go to /comment-chart. This means you have not created the view from the last tutorial. We’ll be using the same view across both tutorials.

In the configuration page for the module, we set Highcharts as the “Preferred charting library”. You can’t use two different charting tools in two separate views. For example, you can’t use GVA in a block view and Highcharts in a page view.

How To Programmatically Create Charts

At this point, we know how to create a simple chart using Visualization API and Views. Now let’s look at creating a few charts with code. For most complex charts it’ll be easier to create them with code and expose the chart as a block using Drupal’s Block API for example.

Here is some example code that shows you how to create charts programmatically.

/**
 * Implements hook_menu().
 */
function example_menu() {
  $items['example-charts'] = array(
    'title' => 'Example',
    'page callback' => 'example_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Callback function for menu item.
 */
function example_page() {
  $data = array(
    array('fruit' => 'apple', 'votes' => 16),
    array('fruit' => 'mango', 'votes' => 10),
    array('fruit' => 'banana', 'votes' => 34),
    array('fruit' => 'peach', 'votes' => 20),
    array('fruit' => 'orange', 'votes' => 15),
  );

  $options_pie = array(
    'title' => 'Favourite fruits',
    'fields' => array(
      'votes' => array(
        'label' => t('Votes'),
        'enabled' => TRUE,
      ),
    ),
    'xAxis' => array(
      'labelField' => 'fruit',
    ),
    'data' => $data,
    'type' => 'pie',
  );

  $options_column = array(
    'title' => 'Favourite fruits',
    'fields' => array(
      'votes' => array(
        'label' => t('Votes'),
        'enabled' => TRUE,
      ),
    ),
    'xAxis' => array(
      'labelField' => 'fruit',
    ),
    'data' => $data,
    'type' => 'column',
  );

  $build['pie'] =  array(
    '#theme' => 'visualization',
    '#options' => $options_pie,
  );

  $build['column'] =  array(
    '#theme' => 'visualization',
    '#options' => $options_column,
  );

  return $build;
}

If everything is working properly you should see two charts, one pie chart and the other should be a column chart.

Fig 1.2

Let’s now go through each part of the code. We’ll first start with the $data array. The array holds the data that will be used in the chart.

  $data = array(
    array('fruit' => 'apple', 'votes' => 16),
    // ...
  );

The $options_* array is used to define the chart settings. In this array you define the type, data, xAxis and fields.

  $options_pie = array(
    'title' => 'Favourite fruits',
    'fields' => array(
      'votes' => array(
        'label' => t('Votes'),
        'enabled' => TRUE,
      ),
    ),
    'xAxis' => array(
      'labelField' => 'fruit',
    ),
    'data' => $data,
    'type' => 'pie',
  );

Finally, we pass everything over to the visualization theme so the chart is rendered.

 $build['pie'] =  array(
    '#theme' => 'visualization',
    '#options' => $options_pie,
  );

If you have any questions, please leave a comment.

54 thoughts on “Intro To Visualization API (Part 2): Highcharts And Code”

  1. Hi, thanks again for this nice and useful tutorial. Everything worked great (views etc) The programmatic options however shows a page (or block on page) with empty contents (no errors, just no chart)
    Wonder where it went wrong….

    1. Try the following.

      – Install Visualization API and setup highcharts
      – Copy the example code into a module.
      – Change the “example_”. For example, “example_menu” to “custom_menu”.
      – Make sure `’page callback’ => ‘example_page’,` is pointing to a callback function.
      – Last but not least, flush the site cache.

      Let me know how you go.

      1. Hi !, Letting you know that the menu is working now. Thanks for the tips!. The only issue I still have is that it only displays a single chart and not 2 as in the tutorial example. . I can move the Build inputs around in my .menu script and it will change the chart type but it never shows both. In other words, it only displays the first chart defined. A bit confused now since the Viz-api module documentation says that each chart is unique ….so may be the behavior is as designed?? I use jQ 1.7, HC 2.3.5 and Viz-api 7.1alpha. … Thanks again !

        1. Hmmm.

          Do you have Views installed? While just testing out the code, I had an issue where the chart was only displaying if Views was installed. Even if I was loading the chart programmatically, weird. 🙁

  2. hey nice tutorials i think one can do much more with this :)i hav couple of question
    1)can it b made dynamic so when ever there is a change in the values its reflected n the chart?
    2) how scalable is this in large website?

    1. Sorry, I have not tested the charts with a lot of data.

      If you want to do some type of dynamic loading, look at loading the charts directly using JavaScript.

  3. Do you have any tips on using highcharts in a custom node.tpl to chart custom field values? Many thanks for this article.

      1. Interesting. I am not familiar with custom formatters. I have each node with all of the points for multiple charts included in fields. With fusioncharts I’ve been able to create swf charts from the points in the node–type.tpl.php. I’d love to do the same thing with highcharts, but haven’t figured it out.

  4. Nice tutorial. I have tried it and it works but I am stuck with the following codition;
    I want to plot a line chart of the below:
    Date: 05/02/2013 Apple sale: 5
    Date: 06/02/2013 Apple sale: 7
    Date: 07/02/2013 Apple sale: 4
    Date: 08/02/2013 Apple sale: 8

    Can you please help me to plot a chart of the above. Date as x-axis and apple sale as line.

    Thanks in advance.

    1. Try this:

        $data = array(
          array('date' => '05/02/2013', 'sales' => 5),
          array('date' => '06/02/2013', 'sales' => 7),
          array('date' => '07/02/2013', 'sales' => 4),
          array('date' => '08/02/201', 'sales' => 8),
      
        );
        $options_pie = array(
          'title' => 'Favourite fruits',
          'fields' => array(
            'sales' => array(
              'label' => t('Sales'),
              'enabled' => TRUE,
            ),
          ),
          'xAxis' => array(
            'labelField' => 'date',
          ),
          'data' => $data,
          'type' => 'pie',
        );
      
        $options_column = array(
          'title' => 'Favourite fruits',
          'fields' => array(
            'sales' => array(
              'label' => t('sales'),
              'enabled' => TRUE,
            ),
          ),
          'xAxis' => array(
            'labelField' => 'date',
          ),
          'data' => $data,
          'type' => 'column',
        );
      
      1. Thanks! it works. I need your help again. I have tried to plot a line chart of below but the dates repeat. I am not able to group the fruits by date. Please help me plot a line chart of the below:

        date : 05/02/2013 Apple : 5
        date : 05/02/2013 Banana : 9
        date : 05/02/2013 Orange : 4
        date : 06/02/2013 Apple : 8
        date : 06/02/2013 Banana : 7
        date : 06/02/2013 Orange : 3
        date : 07/02/2013 Apple : 6
        date : 07/02/2013 Banana : 4
        date : 07/02/2013 Orange : 7

        Date as x-axis. apple, banana and orange as three colored lines.

        1. Hmm, I’m not sure how to do that. You’ll have to play around with different chart types. I’m not sure if a column chart can have multiple y-axis values.

  5. Hi Ivan,

    Another excellent tutorial – well done! I’ve benefited so much from your blog and please continue writing.

    Best regards

    Mohammed

  6. Hi

    Thanks for this module. It’s working well for me.

    I’m trying to get views to aggregate by month. i.e. return the numbers of nodes created every month and display a bar graph monthly. I can get the information with views but it doesn’t aggregate correctly so i want to do it programmatically.

    Do you know how you could get the views data into your example code and manipulate the $view before sending it to be visualised. I’d rather avoid cusom queries if i can.

    Many thanks
    Tim

  7. Hello

    how can i display 2 data in a one chart

    $data = array(
    array(‘fruit’ => ‘apple’, ‘votes’ => 16),
    array(‘fruit’ => ‘mango’, ‘votes’ => 10),
    array(‘fruit’ => ‘banana’, ‘votes’ => 34.45),
    array(‘fruit’ => ‘peach’, ‘votes’ => 20),
    array(‘fruit’ => ‘orange’, ‘votes’ => 15),
    );
    $data1 = array(
    array(‘fruit’ => ‘apple’, ‘votes’ => 2),
    array(‘fruit’ => ‘mango’, ‘votes’ => 4),
    array(‘fruit’ => ‘banana’, ‘votes’ => 12),
    array(‘fruit’ => ‘peach’, ‘votes’ => 24),
    array(‘fruit’ => ‘orange’, ‘votes’ => 15),
    );

    how can i pass the options of each data inside $build array

    thank you in advance for your help

    1. It really depends on the charting library. You’ll have to find a chart type that support two datasets. Remember, Visualization API is just a wrapper for the libraries.

      You’ll have to go directly to the Highcharts API.

  8. Hello, congratulations for the excellent tutorials, (they are very, very good, thanks)

    For months Higcharts work, now I have a couple of weeks with Drupal7, I’m trying to implement my graphics to Highcharts in Drupal, and obviously I can not, I have now given a big step forward found “Webwash”.

    I get to see the graph of google and also the Hightcharts, but am not able to see part of “favorite fruits”

    I only see one block and code. Probably not this by placing the code correctly, (full html) or I need some javascript library

    All this is localhost.

    regards

    1. If you’re placing the code into a text area, the full HTML text format “could” be breaking it. Try loading the chart from a menu callback.

  9. The best soluccion that I found in my case has been colorbox. To open the graph in an emergent window. Also it gave to me result to stick the code in an article or in basic page, but I have more than twenty graph and content is too much.

  10. When you say “When you use GVA, you have to send data to Google.”, I’m not so sure. The way I read the specs on the Google site (the Google Visualization API), at the bottom of each chart’s specs, there is a Data Policy section. For the “area chart” it states:
    “All code and data are processed and rendered in the browser. No data is sent to any server.”

    It seems that all of the charts have this same statement, except for the Geo chart, which involves Google’s map data.

    The older graphical-based Google Charts API solution DID send the data to the Google servers and back, but no longer.

  11. Hi Webwash. – Good work!
    Im wonder how to modify/create a view, which allow to both have column and line y-axis. What would the settings need to be, for creating a ‘raw’-view, so I could alter the options-array along with the x-axis title. (the title gets really messy with lot of data).

  12. Thanks for these excellent tuitorials.
    I was wondering whether it is possible to change the colors of the chart to the theme colours of the theme I am using. The colors are preety but not so good with my theme. Any help?

    1. Unfortunately, you can not change the chart colours directly within Views. If you need this level of customisation, then it’ll be best to implement the charts manually using JavaScript.

      Or, look at the Charts module. (https://drupal.org/project/charts) I haven’t used the Charts module but it recently got an upgrade.

  13. I can get a chart doing step by step,
    I want to know more, example,in tutorials the “pie” config is

    $options_line = array(
    ‘title’ => ‘Heart Rate Average / Month’,
    ‘fields’ => array(
    ‘average’ => array(
    ‘label’ => t(‘average rate’),
    ‘enabled’ => TRUE,
    ),
    ),
    ‘xAxis’ => array(
    ‘labelField’ => ‘month’,
    ),
    ‘data’ => $data,
    ‘type’ => ‘pie’,
    …..

    Is there have other parameter like “yAxis”,where can I found it?
    (Apologize of my poor English).
    Thanks for your answer.

  14. Sorry ivan,
    I try to code a new highcharts in the block by your methode, but I don’t find my block in the liste of blocks (structures/block) ?
    Do you have any iedas where is my error ?
    Drupal: 7.28, views 3

  15. Hi,
    Thanks for this nice tutorial. I have programmatically created some column charts using visualization API as you have explained and everything is working fine. But now I have a new requirement of exporting the charts in a report.

    Please suggest how can I export the charts

  16. Hello,

    I have just gone throw your tutorial and found it very useful. I am going to develop one module with Graphs and Charts where i don’t have data in my database. Data resides in another website and i need to play with that data using API (provides the data in XML format). Also i need to provide the feature to print the chart in PDF and also need to provide the feature to print the Graph data in tabular format where it would be in PDF or in csv file.
    I need to develop Map based on the data inside the API also some of the charts are bar chart with horizontal and vertical view. I planned to use Hightchart but i need some guidance from an expert do we have any better package in drupal to build such system.

    Thanks,
    Nikki

    1. Using Highcharts is the right choice. It offers print functionality, and if you’re willing to write custom code, you can consume any type of endpoint: xml or JSON.

  17. Hey ,

    Could you please tell use from where you got the syntax of the configuration of the chart i spent two days looking without sucess.

    —-
    $options_pie = array(
    ‘title’ => ‘Favourite fruits’,
    ‘fields’ => array(
    ‘votes’ => array(
    ‘label’ => t(‘Votes’),
    ‘enabled’ => TRUE,
    ),
    ),
    ‘xAxis’ => array(
    ‘labelField’ => ‘fruit’,
    ),
    ‘data’ => $data,
    ‘type’ => ‘pie’,
    );
    ——

    I would like to understand each parameters in the array that i can customize it to my needs.

    and thanks in advance.

  18. Hello Sir,
    This tutorial is very useful for basic understanding.
    Can you pleas explain how to use decimal values in this chart, now when i updated your value with decimal value result remains integer value in tooltip box. see below array for your reference.
    $data = array(
    array(‘fruit’ => ‘apple’, ‘votes’ => 16.456),
    array(‘fruit’ => ‘mango’, ‘votes’ => 10.899),
    array(‘fruit’ => ‘banana’, ‘votes’ => 34.425),
    array(‘fruit’ => ‘peach’, ‘votes’ => 20.127),
    array(‘fruit’ => ‘orange’, ‘votes’ => 15.978),
    );

Leave a Comment

You have to agree to the comment policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.