pchart_用pChart绘制图表

pchart

Created and maintained by Jean-Damien Pogolotti, a systems engineer based in Toulouse, France, pChart is a library that creates anti-aliased charts and graphs using PHP. It’s object-oriented code has been recently redesigned and makes it easy to add beautiful, eye-catching data. The library is free for non-profit use and for inclusion in GPL distributed software; licensing plans for other uses start at just 50€. In this article I’ll take you through installing pChart and using it to generate a basic chart, line chart and plot graph.

pChart由法国图卢兹的系统工程师Jean-Damien Pogolotti创建和维护，pChart是一个使用PHP创建抗锯齿图和图形的库。 它的面向对象代码最近经过了重新设计，可以轻松添加漂亮的，引人注目的数据。 该库可免费用于非营利用途，也可以包含在GPL分布式软件中； 其他用途的许可计划起价仅为50欧元。 在本文中，我将指导您安装pChart并使用它生成基本的图表，折线图和绘图图。

安装 (Installation)

pChart likes PHP 5+ and requires the GD and FreeType extensions. These should be installed and enabled by default with version 5, but it’s a good idea to double check using the phpinfo() function. The function generates a full description of your PHP installation. If you see a “gd” section which reports both GD and Free Type support are enabled in its output, you should be able to use pChart.

pChart喜欢PHP 5+，并且需要GD和FreeType扩展。 默认情况下，应在版本5中安装并启用这些功能，但是最好使用phpinfo()函数进行仔细检查。 该函数生成您PHP安装的完整描述。 如果看到“ gd”部分报告在其输出中启用了GD和自由类型支持，则您应该能够使用pChart。

If you are working on a local development system, don’t forget to check your hosting server before deploying your application. A shared hosting scheme shouldn’t pose any problems, but if you are using a VPS then you may have to ask the administrator to recompile PHP with GD and FreeType support if it’s lacking.

pChart can be download from www.pchart.net/download. As of this writing, the latest version of the library is 2.1.3. Download the library and make note of the MD5 checksum listed alongside it on the webpage; it’s a good idea to verify the checksum of the file you download to make sure they match. On unix systems you can verify the checksum like this:

jajeronymo@web1:~$md5sum pChart2.1.3.zip 7895f71126638cbfb73b69c987418107 pChart2.1.3.zip  Then unzip the package. In my case the contents are automatically put into a folder pChart2.1.3. Read the readme.txt file which explains what pChart is, what it’s requirements are, and perhaps most importantly what the various files in code base are. Then either move the folder or create a symbolic link to it (or both), depending on the needs of your application. 然后解压缩包。 在我的情况下，内容自动放入文件夹pChart2.1.3 。 阅读readme.txt文件，该文件说明什么是pChart，它的要求是什么，也许最重要的是，代码库中的各种文件是什么。 然后，根据应用程序的需要，移动文件夹或创建指向该文件夹的符号链接(或两者)。 jajeronymo@web1:~$ unzip pChart2.1.3.zip
jajeronymo@web1:~$sudo -i [sudo] password for jajeronymo: ******** root@web1:~# mv /home/jajeronymo/pChart2.1.3 /srv/www/lib/ root@web1:~# cd /srv/www/lib root@web1:/srv/www/lib# ln -s pChart2.1.3 pChart  Did you read the readme.txt file yet? No!? Do it now, please. It’s a healthy habit. 您读过readme.txt文件了吗？ 没有！？ 请现在就做。 这是一个健康的习惯。 Now you can use require_once statements to make the various pChart classes available to your PHP scripts. The documentation offers a reminder that they should be included after the session has been started (if you’re using them) and before anything is sent to the browser, otherwise PHP may throw the infamous “headers already sent” error. 现在，您可以使用require_once语句使各种pChart类可用于您PHP脚本。 该文档提醒您，应在会话开始后(如果您正在使用它们)并且在将任何内容发送到浏览器之前将其包括在内，否则PHP可能会抛出臭名昭著的“已发送标头”错误。 <?php session_start(); require_once "../lib/pChart/class/pDraw.class.php"; require_once "../lib/pChart/class/pImage.class.php"; require_once "../lib/pChart/class/pData.class.php"; Above I used full relative paths because PHP will look for included files only in a few select default directories, like the current working directory, /usr/share/php, and /usr/share/pear. You can use set_include_path() if you’d like to have PHP search other directories: 上面我使用了完整的相对路径，因为PHP仅在少数几个默认目录中查找包含的文件，例如当前工作目录/usr/share/php/usr/share/pear 。 如果您想让PHP搜索其他目录，则可以使用set_include_path() <?php define("PCHART_PATH", /srv/www/lib/pChart"); set_include_path(get_include_path() . PATH_SEPARATOR . PCHART_PATH); require_once "class/pDraw.class.php"; ... 创建单个系列图 (Create a Single Series Chart) No matter how complex the chart, a pChart chart is created by a three-step process: define the data, create the image file, and output the file. We start with data definition. 无论图表多么复杂，pChart图表都是通过三步过程创建的：定义数据，创建图像文件并输出文件。 我们从数据定义开始。 Data usually come from a database in real world applications, but in this tutorial it’ll be defined in the script itself as an array. Let’s use the first eight values of the Fibonacci numbers as the dataset: 数据通常来自现实应用程序中的数据库，但是在本教程中，它将在脚本本身中定义为数组。 让我们使用斐波那契数的前八个值作为数据集： <?php$myDataset = array(0, 1, 1, 2, 3, 5, 8, 13);

pChart is object-oriented. You simply create a data object which is an instance of the pData class and assign your dataset to it with addPoints():

pChart是面向对象的。 您只需创建一个数据对象，它是pData类的实例，并使用addPoints()将数据集分配给它：

<?php
$myData = new pData();$myData->addPoints($myDataset); You’re done with step one. Now you need to define an image object to express $myData as a chart. This object is a 500×300 pixel instance of the class pImage:

"FontName" => PCHART_PATH . "/fonts/GeosansLight.ttf",
"FontSize" => 15));

It’s crucial to define the correct path to the font! Here I’ve used one of the fonts that come with pChart which is located in the pChart/fonts directory. Because my root script is outside pChart/, the latter had to be included in the path. If the path is incorrect, you will get a “Could not find/open font” warning and the chart will fail to display text.

Though the image is 500×300 pixels in size, the actual chart area must be less than that to accommodate the both the X and Y axis labels. The setGraphArea() method defines the top-left and bottom-right corners of the chart area as points X1,Y1 and X2,Y2:

<?php
$myImage->setGraphArea(25,25, 475,275); Also, some charts need different horizontal and vertical scales for maximum legibility. pChart has dozens of parameters for scale customization, but for the sake of simplicity let’s just use the defaults: 此外，某些图表需要使用不同的水平和垂直比例，以最大程度地提高可读性。 pChart有许多用于比例尺定制的参数，但是为了简单起见，我们只使用默认值： <?php$myImage->drawScale();

Some charts require you to call the drawScale() method even if with no parameters.

Now it’s time to create the chart proper. pChart currently offers 14 different types of basic charts, each with lots of customizable options. I just want a simple bar chart with default parameters:

<?php
$myImage->drawBarChart(); At this point $myImage is an image object with which you can create and output an image file. Calling the Render() method with null as an argument will send the image to the browser, but before you do this make sure you’ve sent an appropriate Content-Type header. Or, you can provide a file location as an argument and Render() will save the image file to that location on your server:

When you run the PHP script, your browser should show you a chart similar to this:

三系列图表 (Three-Series Chart)

I’ll now show you a more advanced example with line and plot graphs to show three series: the square, cube and fourth-powers of integers from 0 to 4. Start by creating the series as programmatically populated arrays:

<?php
$squareSeries = array();$cubeSeries = array();
$fourthSeries = array(); for ($i = 0; $i <= 4;$i++) {
$squareSeries[$i] = pow($i, 2);$cubeSeries[$i] = pow($i, 3);
$fourthSeries[$i] = pow($i, 4); } Create a new data object and add the series to it with addPoints(): 创建一个新的数据对象，并使用addPoints()将系列添加到其中： <?php$myPowersData = new pData();
$myPowersData->addPoints($squareSeries,"Square");
$myPowersData->addPoints($cubeSeries,"Cube");
$myPowersData->addPoints($fourthSeries,"Fourth");

Using different colors for each series will help make the chart easier to read. You can set the colors for each series using the setPalette() method. It uses an array specifying the desired color in RGBa notation. Here I’ll set the color for the squares series dark red, cubed series green, and fourth series blue:

<?php
$myPowersData->setPalette("Square", array("R" => 240,"G" => 16, "B" =>16, "Alpha" => 100));$myPowersData->setPalette("Cube",
array("R" => 16, "G" => 240, "B" => 16, "Alpha" => 100));
$myPowersData->setPalette("Fourth", array("R" => 16, "G" => 16, "B" => 240, "Alpha" => 100)); For the image object, I’ll use the same size as before but I’ll specify a different font family and font size: 对于图像对象，我将使用与以前相同的大小，但将指定不同的字体系列和字体大小： <?php$myPowersImage = new pImage(500,300, $myPowersData);$myPowersImage->setFontProperties(array(
"FontName" => PCHART_PATH . "/fonts/MankSans.ttf",
"FontSize" => 12));

Then, increase the borders to accommodate the larger figures and use the default scaling:

<?php
$myPowersImage->setGraphArea(40,40, 460,260);$myPowersImage->drawScale();

Finally, tell pChart to draw a line chart using the drawLineChart() method and output the image:

<?php
$myPowersImage->drawLineChart(); header("Content-Type: image/png");$myPowersImage->Render(null);

A plot chart is like a line chart with points to mark the exact coordinates. To draw a plot chart for the same datasets, all you have to do is to invoke drawPlotChart() instead. You do not have to redefine either the datasets or the image object:

<?php
$myPowersImage->drawPlotChart(); header("Content-Type: image/png");$myPowersImage->Render(null);

Again run the script and inspect the charts in your browser.

It’s a good idea to add descriptive labels and a legend to your charts to identify the series. The drawText() and drawLegend() methods let you do just this.

The method drawText() requires at least the text box’s upper-left corner position and the text to be displayed. Though there are a lot of customization parameters available, I’ll specify just the font color and size. Add this line before the the call to drawPlotChart().

<?php
$myPowersImage->drawText(150,50, "The First Three Powers", array("R" => 0, "G" => 64, "B" => 255, "FontSize" => 20)); Likewise, drawLegend() has a lot of customizable parameters, too. I’ll create one with colored circles (LEGEND_FAMILY_CIRCLE), a light background, and a darker border. The font is the same as used for text, and I’ll place the legend at 70,100 to stay clear of the plot lines. Add this line below the call to drawText() and reload: 同样， drawLegend()也有很多可自定义的参数。 我将用彩色圆圈(LEGEND_FAMILY_CIRCLE)，浅色背景和深色边框创建一个。 字体与文本所用的字体相同，我将图例放置在70,100处以避开绘图线。 将此行添加到对drawText()的调用下方并重新加载： <?php$myPowersImage->drawLegend(70,100,
array("R" => 220, "G" => 220, "B" => 220,
"FontR" => 0, "FontG" => 64, "FontB" => 255,
"BorderR" => 80, "BorderG" => 80, "BorderB" => 80,
"FontSize" => 12, "Family" => LEGEND_FAMILY_CIRCLE));

结论 (Conclusion)

Eh ben dis donc! pChart is a surprisingly simple library to use for professional graphs and charts. I only scratched the surface of what its capable of in the article; it has hundreds of customization options and tweaks. And even for non-free applications, pChart is fairly priced. Merci beaucoup, Jean-Damien!

If you’re interested in viewing the full source code that was used to generate the graphics in this article, you can find it on GitHub.

Image via ungureanu / Shutterstock

pchart

• 0
点赞
• 0
评论
• 1
收藏
• 扫一扫，分享海报

10-15
07-13 111

12-14
06-24 2609
05-23 1609
10-16 3013
05-12 4236
08-10 3333
04-19
02-16 932
07-09 1万+
01-02 2061
10-23 57
12-29 324