Perl Programming Page 2 - Basic Charting with Perl |
In order for the graph to be created, it needs some real data. We'll be working with average monthly temperatures. Let's use data from Portland, Oregon, and let's just use the high values for now. (This data will be taken from The Weather Channel). As has already been said, data is stored in an array. The array is actually a multidimensional array, however. The first element of the array should be a reference to an array of labels. In our case, the labels would be the month names. Subsequent elements should contain references to arrays containing the actual values corresponding with those labels. Each of these data elements is called a dataset. So, if we want to graph the average monthly high temperatures for Portland, @data should be defined like this:
my @data = ( ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug','Sep', 'Oct', 'Nov',
If we call the png method now, then an image will be created named temps.png, containing the resulting chart. The image should look like this:
Now we should plot the average monthly low temperatures. If we do this, though, then the @data definition is going to start looking really messy. Fortunately, there is another way to add data which, in some cases, may make things easier and neater. Using the add_dataset method, it is possible to add datasets directly, without the need to create arrays that will only be used once. You just need to pass in the values as arguments. Let's go ahead and get rid of @data by using the add_dataset method, and then add data for low temperatures:
$chart->add_dataset('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul','Aug', 'Sep', 'Oct', 'Nov', 'Dec');$chart->add_dataset(46, 50, 56, 61, 67, 73, 79, 79, 74, 63, 51, 46);$chart->add_dataset(37, 39, 41, 44, 49, 53, 57, 58, 55, 48, 42, 37);$chart->png('temps.png');
Note how the add_dataset method works for adding labels too. Also, when we call the png method, we only pass one argument. The resulting graph looks like this:
The advantage of this approach is that datasets can easily be added as needed, without the complexities of manipulating a multidimensional array.
blog comments powered by Disqus |
|
|
|
|
|
|
|