In this example, we will create a bar chart that displays the annual revenue of a company for the last 10 years. When a bar is clicked, the browser will load a line chart showing the monthly revenue for the selected year. When the line chart is clicked, the browser will load a pie chart showing the breakdown of the revenue for the selected month. When the pie chart is clicked, it will show the sector details in a web page.
The capability is often called "drill-down", because the user can "zoom-in" to get more details by clicking on the chart.
[CGI Version] perldemo_cgi\clickbar.pl
#!/usr/bin/perl
# Include current script directory in the module path (needed on Microsoft IIS).
# This allows this script to work by copying ChartDirector to the same directory
# as the script (as an alternative to installation in Perl module directory)
use File::Basename;
use lib dirname($0);
use perlchartdir;
# The data for the bar chart
my $data = [450, 560, 630, 800, 1100, 1350, 1600, 1950, 2300, 2700];
# The labels for the bar chart
my $labels = ["1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004",
"2005"];
# Create a XYChart object of size 600 x 360 pixels
my $c = new XYChart(600, 360);
# Add a title to the chart using 18pts Times Bold Italic font
$c->addTitle("Annual Revenue for Star Tech", "timesbi.ttf", 18);
# Set the plotarea at (60, 40) and of size 500 x 280 pixels. Use a vertical gradient
# color from light blue (eeeeff) to deep blue (0000cc) as background. Set border and
# grid lines to white (ffffff).
$c->setPlotArea(60, 40, 500, 280, $c->linearGradientColor(60, 40, 60, 280, 0xeeeeff,
0x0000cc), -1, 0xffffff, 0xffffff);
# Add a multi-color bar chart layer using the supplied data. Use soft lighting effect
# with light direction from top.
$c->addBarLayer3($data)->setBorderColor($perlchartdir::Transparent,
perlchartdir::softLighting($perlchartdir::Top));
# Set x axis labels using the given labels
$c->xAxis()->setLabels($labels);
# Draw the ticks between label positions (instead of at label positions)
$c->xAxis()->setTickOffset(0.5);
# When auto-scaling, use tick spacing of 40 pixels as a guideline
$c->yAxis()->setTickDensity(40);
# Add a title to the y axis with 12pts Times Bold Italic font
$c->yAxis()->setTitle("USD (millions)", "timesbi.ttf", 12);
# Set axis label style to 8pts Arial Bold
$c->xAxis()->setLabelStyle("arialbd.ttf", 8);
$c->yAxis()->setLabelStyle("arialbd.ttf", 8);
# Set axis line width to 2 pixels
$c->xAxis()->setWidth(2);
$c->yAxis()->setWidth(2);
# Create the image and save it in a temporary location
my $chart1URL = $c->makeTmpFile("/tmp/tmpcharts");
# Create an image map for the chart
my $imageMap = $c->getHTMLImageMap("clickline.pl", "",
"title='{xLabel}: US\$ {value|0}M'");
print "Content-type: text/html\n\n";
print <<EndOfHTML
<html>
<body topmargin="5" leftmargin="5" rightmargin="0" marginwidth="5" marginheight="5">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
Simple Clickable Bar Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
<a href="viewsource.pl?file=$ENV{"SCRIPT_NAME"}">View Source Code</a>
</div>
<img src="getchart.pl?img=/tmp/tmpcharts/$chart1URL" border="0" usemap="#map1">
<map name="map1">
$imageMap
</map>
</body>
</html>
EndOfHTML
; |
In the above code, the chart is created and saved in a temporary file in the "/tmp/tmp_chart" directory using
BaseChart.makeTmpFile. This function also simultaneously removes old temporary files (default lifetime = 600 seconds) to avoid temporary files from building up.
Note: For the above code to run correctly, please verify the web server anonymous user has sufficient privileges to read and write to "/tmp/tmp_chart".
An <IMG> tag is used to retrieve the chart with "getchart.pl?img=/tmp/tmpcharts/$chart1URL" as the URL. "getchart.pl" is a simple utility that comes with ChartDirector for retrieving images files. The "getchart.pl" is needed because the "/tmp/tmp_chart" directory is not under the web server root directory. If your scripts use a temporary directory that is under the web server root directory, you may put the temporary file URL directly in the <IMG> tag instead of using "getchart.pl".
NOTE: This sample script uses "getchart.pl" and assumes it is in the same directory as the script. When developing your own script using this sample script as a template, please ensure you copy "getchart.pl" to the same directory as your script. If you put "getchart.pl" in other directory, please adjust the paths in your script accordingly.
The image map for the chart is created using the following code:
my $imageMap = $c->getHTMLImageMap("clickline.pl", "",
"title='{xLabel}: USD {value|0}M'");
As seen above, only one line of code is needed.
BaseChart.getHTMLImageMap will generate the image map for the entire chart. The image map will use "clickline.pl" as the handler when a bar is clicked.
If you right click on the browser and choose "View Source" to look at the HTML of the web page as received by the browser, you can see that the image map generated above will be something like:
<area shape="rect" coords="67,278,103,320" title='1996: US$ 450M'
href="clickline.asp?x=0&xLabel=1996&dataSet=0&dataSetName=&value=450">
<area shape="rect" coords="117,268,153,320" title='1997: US$ 560M'
href="clickline.asp?x=1&xLabel=1997&dataSet=1&dataSetName=&value=560">
<area shape="rect" coords="167,261,203,320" title='1998: US$ 630M'
href="clickline.asp?x=2&xLabel=1998&dataSet=2&dataSetName=&value=630">
<area shape="rect" coords="217,245,253,320" title='1999: US$ 800M'
href="clickline.asp?x=3&xLabel=1999&dataSet=3&dataSetName=&value=800">
...... (one <area> tag for each bar) ......
The image map generated by ChartDirector contains one <AREA> tag per bar. This defines the bars as hot spots. The "href" attributes of the <AREA> tags use "clickline.pl" as the URL, with query parameters appended to describe the bars. In this way, "clickline.pl" can distinguish which bar the user has clicked.
The <AREA> tags also include "title" attributes, which act as tool tips when the mouse pointer moves over the bars. In this example, the tool tips are in the format:
"title='{xLabel}: USD {value|0}M'"
which is specified as the third argument of
BaseChart.getHTMLImageMap.

In the previous Clickable Bar Chart sample code, when a bar is clicked, the handler "clickline.pl" will be invoked.
The code for the image map handler "clickline.pl" is listed below. It determines which year the user has clicked from query parameters. It then draws a line chart based on the selected year. To produce a clickable line chart, it generates and saves the chart in a temporary file using
BaseChart.makeTmpFile, and generates the image map using
BaseChart.getHTMLImageMap, with "clickpie.pl" as the handler.
As "clickline.pl" is very similar to "clickbar.pl", it will not be explained further here.
[CGI Version] perldemo_cgi\clickline.pl
#!/usr/bin/perl
# Include current script directory in the module path (needed on Microsoft IIS).
# This allows this script to work by copying ChartDirector to the same directory
# as the script (as an alternative to installation in Perl module directory)
use File::Basename;
use lib dirname($0);
use perlchartdir;
# Get HTTP query parameters
use CGI;
my $query = new CGI;
# Get the selected year.
my $selectedYear = $query->param("xLabel");
#
# In this demo, we just split the annual revenue into 12 months using random ratios.
# In real life, the data can come from a database based on selectedYear.
#
# Get the annual revenue
my $annualRevenue = $query->param("value");
# Split into 12 months
srand(int($selectedYear));
my $data = [(0) x 12];
for(my $i = 0; $i < 11; ++$i) {
$data->[$i] = $annualRevenue * (rand() * 0.6 + 0.6) / (12 - $i);
$annualRevenue = $annualRevenue - $data->[$i];
}
$data->[11] = $annualRevenue;
#
# Now we obtain the data into arrays, we can start to draw the chart using
# ChartDirector
#
# Create a XYChart object of size 600 x 320 pixels
my $c = new XYChart(600, 360);
# Add a title to the chart using 18pts Times Bold Italic font
$c->addTitle("Month Revenue for Star Tech for $selectedYear", "timesbi.ttf", 18);
# Set the plotarea at (60, 40) and of size 500 x 280 pixels. Use a vertical gradient
# color from light blue (eeeeff) to deep blue (0000cc) as background. Set border and
# grid lines to white (ffffff).
$c->setPlotArea(60, 40, 500, 280, $c->linearGradientColor(60, 40, 60, 280, 0xeeeeff,
0x0000cc), -1, 0xffffff, 0xffffff);
# Add a red line (ff0000) chart layer using the data
my $dataSet = $c->addLineLayer()->addDataSet($data, 0xff0000, "Revenue");
# Set the line width to 3 pixels
$dataSet->setLineWidth(3);
# Use a 13 point circle symbol to plot the data points
$dataSet->setDataSymbol($perlchartdir::CircleSymbol, 13);
# Set the labels on the x axis. In this example, the labels must be Jan - Dec.
my $labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct",
"Nov", "Dec"];
$c->xAxis()->setLabels($labels);
# When auto-scaling, use tick spacing of 40 pixels as a guideline
$c->yAxis()->setTickDensity(40);
# Add a title to the x axis to reflect the selected year
$c->xAxis()->setTitle("Year $selectedYear", "timesbi.ttf", 12);
# Add a title to the y axis
$c->yAxis()->setTitle("USD (millions)", "timesbi.ttf", 12);
# Set axis label style to 8pts Arial Bold
$c->xAxis()->setLabelStyle("arialbd.ttf", 8);
$c->yAxis()->setLabelStyle("arialbd.ttf", 8);
# Set axis line width to 2 pixels
$c->xAxis()->setWidth(2);
$c->yAxis()->setWidth(2);
# Create the image and save it in a temporary location
my $chart1URL = $c->makeTmpFile("/tmp/tmpcharts");
# Create an image map for the chart
my $imageMap = $c->getHTMLImageMap("clickpie.pl?year=$selectedYear", "",
"title='{xLabel}: US\$ {value|0}M'");
print "Content-type: text/html\n\n";
print <<EndOfHTML
<html>
<body topmargin="5" leftmargin="5" rightmargin="0" marginwidth="5" marginheight="5">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
Simple Clickable Line Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
<a href="viewsource.pl?file=$ENV{"SCRIPT_NAME"}">View Source Code</a>
</div>
<img src="getchart.pl?img=/tmp/tmpcharts/$chart1URL" border="0" usemap="#map1">
<map name="map1">
$imageMap
</map>
</body>
</html>
EndOfHTML
; |

In the previous Clickable Line Chart sample code, when a line is clicked, the handler "clickpie.pl" will be invoked.
The code for "clickpie.pl" is listed below. It determines which year and month the user has clicked from query parameters. It then draws a pie chart based on those parameters. To produce a clickable pie chart, it generates and saves the chart in a temporary file using
BaseChart.makeTmpFile, and generates the image map using
BaseChart.getHTMLImageMap, with "piestub.pl" as the handler.
As "clickpie.pl" is very similar to "clickbar.pl" and "clickline.pl", it will not be explained further here.
[CGI Version] perldemo_cgi\clickpie.pl
#!/usr/bin/perl
# Include current script directory in the module path (needed on Microsoft IIS).
# This allows this script to work by copying ChartDirector to the same directory
# as the script (as an alternative to installation in Perl module directory)
use File::Basename;
use lib dirname($0);
use perlchartdir;
# Get HTTP query parameters
use CGI;
my $query = new CGI;
# Get the selected year and month
my $selectedYear = int($query->param("year"));
my $selectedMonth = int($query->param("x")) + 1;
#
# In this demo, we just split the monthly revenue into 3 parts using random ratios.
# In real life, the data probably can come from a database based on selectedYear and
# selectedMonth.
#
# Get the monthly revenue
my $monthlyRevenue = $query->param("value");
# Split into 3 parts
srand($selectedMonth * 2000 + $selectedYear);
my $data = [(0) x 4];
$data->[0] = (rand() * 0.1 + 0.3) * $monthlyRevenue;
$data->[1] = (rand() * 0.1 + 0.2) * ($monthlyRevenue - $data->[0]);
$data->[2] = (rand() * 0.4 + 0.3) * ($monthlyRevenue - $data->[0] - $data->[1]);
$data->[3] = $monthlyRevenue - $data->[0] - $data->[1] - $data->[2];
# The labels for the pie chart
my $labels = ["Services", "Hardware", "Software", "Others"];
# Create a PieChart object of size 600 x 240 pixels
my $c = new PieChart(600, 280);
# Set the center of the pie at (300, 140) and the radius to 120 pixels
$c->setPieSize(300, 140, 120);
# Add a title to the pie chart using 18 pts Times Bold Italic font
$c->addTitle("Revenue Breakdown for $selectedMonth/$selectedYear", "timesbi.ttf", 18)
;
# Draw the pie in 3D with 20 pixels 3D depth
$c->set3D(20);
# Set label format to display sector label, value and percentage in two lines
$c->setLabelFormat("{label}<*br*>\${value|2}M ({percent}%)");
# Set label style to 10 pts Arial Bold Italic font. Set background color to the same
# as the sector color, with reduced-glare glass effect and rounded corners.
my $t = $c->setLabelStyle("arialbi.ttf", 10);
$t->setBackground($perlchartdir::SameAsMainColor, $perlchartdir::Transparent,
perlchartdir::glassEffect($perlchartdir::ReducedGlare));
$t->setRoundedCorners();
# Use side label layout method
$c->setLabelLayout($perlchartdir::SideLayout);
# Set the pie data and the pie labels
$c->setData($data, $labels);
# Create the image and save it in a temporary location
my $chart1URL = $c->makeTmpFile("/tmp/tmpcharts");
# Create an image map for the chart
my $imageMap = $c->getHTMLImageMap("piestub.pl", "",
"title='{label}:US\$ {value|2}M'");
print "Content-type: text/html\n\n";
print <<EndOfHTML
<html>
<body topmargin="5" leftmargin="5" rightmargin="0" marginwidth="5" marginheight="5">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
Simple Clickable Pie Chart
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
<a href="viewsource.pl?file=$ENV{"SCRIPT_NAME"}">View Source Code</a>
</div>
<img src="getchart.pl?img=/tmp/tmpcharts/$chart1URL" border="0" usemap="#map1">
<map name="map1">
$imageMap
</map>
</body>
</html>
EndOfHTML
; |

In the previous Clickable Pie Chart sample code, when a sector is clicked, the handler "piestub.pl" will be invoked. Its code is listed below. In this example, "piestub.pl" simply displays some data about the sector clicked.
[CGI Version] perldemo_cgi\piestub.pl
#!/usr/bin/perl
# Get HTTP query parameters
use CGI;
my $query = new CGI;
print "Content-type: text/html\n\n";
print <<EndOfHTML
<html>
<body topmargin="5" leftmargin="5" rightmargin="0" marginwidth="5" marginheight="5">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
Simple Clickable Pie Chart Handler
</div>
<hr color="#000080">
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
<a href="viewsource.pl?file=$ENV{"SCRIPT_NAME"}">View Source Code</a>
</div>
<div style="font-size:10pt; font-family:verdana;">
<b>You have clicked on the following sector :</b><br>
<ul>
<li>Sector Number : @{[$query->param("sector")]}</li>
<li>Sector Name : @{[$query->param("label")]}</li>
<li>Sector Value : @{[$query->param("value")]}</li>
<li>Sector Percentage : @{[$query->param("percent")]}%</li>
</ul>
</body>
</html>
EndOfHTML
; |
© 2006 Advanced Software Engineering Limited. All rights reserved.