ChartDirector Ver 3.0 (Perl Edition)

Simple Clickable Charts


In this example, we will create a bar chart that displays annual revenue for a company for the last 10 years. When a bar is clicked, the browser will load a line chart showning 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 data in detail in an HTML page.

The capability is often called "drill-down", because the user can "zoom-in" to get more details by clicking on the chart.

Clickable Bar Chart



[The following is available as "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; # #For demo purpose, we use hard coded data. In real life, the following data #could come from a database. # my $revenue = [4500, 5600, 6300, 8000, 12000, 14000, 16000, 20000, 24000, 28000] ; my $labels = ["1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", "2000", "2001"]; #Create a XYChart object of size 450 x 200 pixels my $c = new XYChart(450, 200); #Add a title to the chart using Times Bold Italic font $c->addTitle("Annual Revenue for Star Tech", "timesbi.ttf"); #Set the plotarea at (60, 25) and of size 350 x 150 pixels $c->setPlotArea(60, 25, 350, 150); #Add a blue (0x3333cc) bar chart layer using the given data. Set the bar border #to 1 pixel 3D style. $c->addBarLayer($revenue, 0x3333cc, "Revenue")->setBorderColor(-1, 1); #Set x axis labels using the given labels $c->xAxis()->setLabels($labels); #Add a title to the y axis $c->yAxis()->setTitle("USD (K)"); #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}: USD {value|0}K'"); print "Content-type: text/html\n\n"; print <<EndOfHTML <html> <body> <h1>Simple Clickable Bar Chart</h1> <p><a href="viewsource.pl?file=$ENV{"SCRIPT_NAME"}"> View Source Code </a></p> <img src="myimage.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 "myimage.pl?img=/tmp/tmpcharts/$chart1URL" as the URL. "myimage.pl" is a simple utility that comes with ChartDirector for retrieving images files. The "myimage.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 "myimage.pl".

The image map for the chart is created using the following code:

my $imageMap = $c->getHTMLImageMap("clickline.pl", "", "title='{xLabel}: USD {value|0}K'");

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 the user clicks on the bars.

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="65,152,90,175" title='1992: USD 4500K' href="clickline.pl?x=0&xLabel=1992&dataSet=0&dataSetName=Revenue&value=4500"> <area shape="rect" coords="100,147,125,175" title='1993: USD 5600K' href="clickline.pl?x=1&xLabel=1993&dataSet=0&dataSetName=Revenue&value=5600"> <area shape="rect" coords="135,143,160,175" title='1994: USD 6300K' href="clickline.pl?x=2&xLabel=1994&dataSet=0&dataSetName=Revenue&value=6300"> <area shape="rect" coords="169,135,194,175" title='1995: USD 8000K' href="clickline.pl?x=3&xLabel=1995&dataSet=0&dataSetName=Revenue&value=8000"> ...... (one <area> tag for each bar) ......

The image map generated by ChartDirector will contain one area tag for each of the bars. The "href" attribute of the tag will invoke "clickline.pl" with a some query parameters to describe the bar. In this way, the "clickline.pl" will know which bar the user has clicked.

The tag also includes the "title" attribute, which will become the "tool tip" text when the mouse moves over the bar. In this particular example, the "tool tip" text is in the format:

"title='{xLabel}: USD {value|0}K'"

which is specified as the third argument of BaseChart.getHTMLImageMap.

As mentioned above, the "myimage.pl" is a simply utility used to retrieve the image from a file and returns it to the browser.

[The following is available as "perldemo_cgi/myimage.pl".]
#!/usr/bin/perl #standard code to parse HTTP query parameters %query = map {my($k,$v) = split(/=/)} split(/&/, $ENV{"QUERY_STRING"}); open(FILE, $query{"img"}); binmode(FILE); binmode(STDOUT); print "Content-type: image/png\n\n"; while (!eof(FILE)) { read(FILE, $data, 64000); print $data; } close(FILE);

Clickable Line Chart



In the last example Clickable Bar Chart, when a bar is clicked, the handler "clickline.pl" will be invoked.

The code for the image map handler "clickline.pl" is listed below. The "clickline.pl" determines which year the user has clicked from the query parameters. It then draws a line chart based on 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.

[The following is available as "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; #standard code to parse HTTP query parameters %query = map {my($k,$v) = split(/=/)} split(/&/, $ENV{"QUERY_STRING"}); #Get the selected year. my $selectedYear = $query{"xLabel"}; #Get the total revenue my $totalRevenue = $query{"value"}; # # In this demo, we just split the total revenue into 12 months using random # numbers. In real life, the data can come from a database. # srand($selectedYear); my @temp = (0) x 12; my $data = \@temp; for($i = 0; $i < 11; ++$i) { $data->[$i] = $totalRevenue * (rand() * 0.6 + 0.6) / (12 - $i); $totalRevenue = $totalRevenue - $data->[$i]; } $data->[11] = $totalRevenue; # # Now we obtain the data into arrays, we can start to draw the chart using # ChartDirector # #Create a XYChart object of size 450 x 200 pixels my $c = new XYChart(450, 200); #Add a title to the chart $c->addTitle("Month Revenue for Star Tech for $selectedYear", "timesbi.ttf"); #Set the plotarea at (60, 5) and of size 350 x 150 pixels. Enable both #horizontal and vertical grids by setting their colors to grey (0xc0c0c0) $c->setPlotArea(60, 25, 350, 150)->setGridColor(0xc0c0c0, 0xc0c0c0); #Add a line chart layer using the data my $dataSet = $c->addLineLayer()->addDataSet($data, 0x993399); #Set the line width to 3 pixels $dataSet->setLineWidth(3); #Use a 11 point triangle symbol to plot the data points $dataSet->setDataSymbol($perlchartdir::TriangleSymbol, 11); #Set the x axis labels. 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); #Add a title to the x axis to reflect the selected year $c->xAxis()->setTitle("Year $selectedYear"); #Add a title to the y axis $c->yAxis()->setTitle("USD (K)"); #Reserve 10% margin at the top of the plot area just to make sure the line does #not go too near the top of the plot area $c->yAxis()->setAutoScale(0.1); #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}: USD {value|0}K'"); print "Content-type: text/html\n\n"; print <<EndOfHTML <html> <body> <h1>Simple Clickable Line Chart</h1> <p><a href="viewsource.pl?file=$ENV{"SCRIPT_NAME"}"> View Source Code </a></p> <img src="myimage.pl?img=/tmp/tmpcharts/$chart1URL" border="0" usemap="#map1"> <map name="map1"> $imageMap </map> </body> </html> EndOfHTML ;

Clickable Pie Chart



In the last example Clickable Line Chart, 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 the 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. method, 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.

[The following is available as "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; #standard code to parse HTTP query parameters %query = map {my($k,$v) = split(/=/)} split(/&/, $ENV{"QUERY_STRING"}); #Get the selected year and month my $selectedYear = $query{"year"}; my $selectedMonth = $query{"x"} + 1; #Get the monthly revenue my $monthlyRevenue = $query{"value"}; # # In this demo, we just split the total revenue into 3 parts using random # numbers. In real life, the data probably can come from a database. # srand($selectedMonth * 2000 + $selectedYear); my @temp = (0) x 3; my $data = \@temp; $data->[0] = (rand() * 0.1 + 0.5) * $monthlyRevenue; $data->[1] = (rand() * 0.1 + 0.2) * $monthlyRevenue; $data->[2] = $monthlyRevenue - $data->[0] - $data->[1]; #The labels for the pie chart my $labels = ["Services", "Hardware", "Software"]; #Create a PieChart object of size 360 x 260 pixels my $c = new PieChart(360, 260); #Set the center of the pie at (180, 140) and the radius to 100 pixels $c->setPieSize(180, 130, 100); #Add a title to the pie chart using 13 pts Times Bold Italic font $c->addTitle("Revenue Breakdown for $selectedMonth/$selectedYear", "timesbi.ttf", 13); #Draw the pie in 3D $c->set3D(); #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}:USD {value|0}K'"); print "Content-type: text/html\n\n"; print <<EndOfHTML <html> <body> <h1>Simple Clickable Pie Chart</h1> <p><a href="viewsource.pl?file=$ENV{"SCRIPT_NAME"}"> View Source Code </a></p> <img src="myimage.pl?img=/tmp/tmpcharts/$chart1URL" border="0" usemap="#map1"> <map name="map1"> $imageMap </map> </body> </html> EndOfHTML ;

Clickable Pie Handler



In the last example Clickable Pie Chart, when a sector is clicked, the handler "piestub.pl" will be invoked. Its code is listed below. In this example, for demo purposes the "piestub.pl" simply displays data about the sector clicked.

[The following is available as "perldemo_cgi/piestub.pl".]
#!/usr/bin/perl #standard code to parse HTTP query parameters my %query = map {my($k,$v) = split(/=/)} split(/&/, $ENV{"QUERY_STRING"}); print "Content-type: text/html\n\n"; print <<EndOfHTML <html> <body> <h1>Simple Clickable Pie Chart Handler</h1> <p><a href="viewsource.pl?file=$ENV{"SCRIPT_NAME"}"> View Source Code </a></p> <p><b>You have clicked on the following sector :</b></p> <ul> <li>Sector Number : $query{"sector"}</li> <li>Sector Name : $query{"label"}</li> <li>Sector Value : $query{"value"}</li> <li>Sector Percentage : $query{"percent"}%</li> </ul> </body> </html> EndOfHTML ;