search
HomeBackend DevelopmentPHP TutorialPHP code example for drawing pie chart

  1. //Variable definition, the angle size when drawing an elliptical arc
  2. define("ANGLELENGTH",3);
  3. /**
  4. * Draw the picture
  5. * @param $title The title of the 3D picture
  6. * @param $dataArr The displayed data array
  7. * @param $labelArr The label classification array corresponding to the data
  8. * @param $colorArr The array corresponding to the drawing color
  9. * @ param $a The base width of the canvas
  10. * @param $b The base height of the canvas
  11. * @param $v The height of the 3D column
  12. * @param $font The font size
  13. * @return The image access path for successful drawing
  14. */
  15. function drawPieImg($title, $dataArr , $labelArr, $colorArr, $a=250, $b=120, $v=20, $font=10){
  16. $ox = 5+$a;
  17. $oy = 5+$b;
  18. $fw = imagefontwidth($font);
  19. $fh = imagefontheight($font);
  20. $n = count($dataArr);//Calculate the array length
  21. $w = 10+$a*2;
  22. $h = 10+$b *2+$v+($fh+2)*$n;
  23. //Create artboard
  24. $img = imagecreate($w, $h);
  25. //Convert RGB to index color
  26. for($i=0; $ i$colorArr[$i] = drawIndexColor($img,$colorArr[$i]);//Assign color to image $img
  27. $clrbk = imagecolorallocate($img, 0xff, 0xff, 0xff);
  28. $clrt = imagecolorallocate($img, 0x00, 0x00, 0x00);
  29. //Fill the background color
  30. imagefill($img, 0, 0, $clrbk);
  31. //Sum
  32. $tot = 0;
  33. for($i=0; $i$tot += $dataArr[$i];
  34. //The starting angle size of each category
  35. $sd = 0;
  36. //Every The angle occupied by each category
  37. $ed = 0;
  38. $ly = 10+$b*2+$v;
  39. for($i=0; $i$sd = $ ed;
  40. $ed += $dataArr[$i]/$tot*360;
  41. //Draw 3D sector
  42. draw3DSector($img, $ox, $oy+20, $a, $b, $v, $sd , $ed, $colorArr[$i]);
  43. //Draw label
  44. imagefilledrectangle($img, 5, $ly, 5+$fw, $ly+$fh, $colorArr[$i]);
  45. imagerectangle($ img, 5, $ly, 5+$fw, $ly+$fh, $clrt);
  46. //Chinese transcoding
  47. $str = iconv("GB2312", "UTF-8", $labelArr[$i]) ;
  48. imagettftext($img, $font, 0, 5+2*$fw, $ly+13, $clrt, "D:/wamp/www/source/font/simhei.ttf", $str.":" .$dataArr[$i]."(".(round(10000*($dataArr[$i]/$tot))/100)."%)");
  49. $ly += $fh+2;
  50. }
  51. //Draw the picture title
  52. imagettftext($img, 15, 0, 5, 15, $clrt, "D:/wamp/www/source/font/simhei.ttf", iconv("GB2312", "UTF- 8",$title));
  53. //Output graphics
  54. header("Content-type: image/png");
  55. //Output the generated image
  56. $imgFileName = "./".time().".png ";
  57. imagepng($img,$imgFileName);
  58. return $imgFileName;
  59. }
  60. /**
  61. * Draw 3d sector
  62. */
  63. function draw3DSector($img, $ox, $oy, $a, $b, $v, $sd, $ed, $clr) {
  64. drawSector($img, $ox, $oy, $a, $b, $sd, $ed, $clr);
  65. if($sdlist( $red, $green, $blue) = drawDarkColor($img, $clr);
  66. //Assign color to the image
  67. $clr=imagecolorallocate($img, $red, $green, $blue);
  68. if($ed> ;180)
  69. $ed = 180;
  70. list($sx, $sy) = getExy($a,$b,$sd);
  71. $sx += $ox;
  72. $sy += $oy;
  73. list( $ex, $ey) = getExy($a, $b, $ed);
  74. $ex += $ox;
  75. $ey += $oy;
  76. imageline($img, $sx, $sy, $sx, $sy+$v, $clr);
  77. imageline($img, $ex, $ey, $ex, $ey+$v, $clr);
  78. drawArc($img, $ox, $oy+$v, $a, $b, $sd, $ed, $clr);
  79. list($sx, $sy) = getExy($a, $b, ($sd+$ed)/2);
  80. $sy += $oy+$v /2;
  81. $sx += $ox;
  82. imagefill($img, $sx, $sy, $clr);
  83. }
  84. }
  85. /**
  86. * Draw elliptical arc
  87. */
  88. function drawArc($img,$ox, $oy,$a,$b,$sd,$ed,$clr){
  89. $n = ANGLELENGTH >0 ? ceil(($ed-$sd)/ANGLELENGTH) : -1;
  90. $d = $sd ;
  91. list($x0,$y0) = getExy($a,$b,$d);
  92. for($i=0; $i$d = ($d+ANGLELENGTH )>$ed?$ed:($d+ANGLELENGTH);
  93. list($x, $y) = getExy($a, $b, $d);
  94. imageline($img, $x0+$ox, $ y0+$oy, $x+$ox, $y+$oy, $clr);
  95. $x0 = $x;
  96. $y0 = $y;
  97. }
  98. }
  99. /**
  100. * Draw a fan
  101. */
  102. function drawSector($ img, $ox, $oy, $a, $b, $sd, $ed, $clr) {
  103. $n = ANGLELENGTH > 0 ? ceil(($ed-$sd)/ANGLELENGTH) : -1;
  104. $d = $sd;
  105. list($x0,$y0) = getExy($a, $b, $d);
  106. imageline($img, $x0+$ox, $y0+$oy, $ox, $oy, $clr);
  107. for($i=0; $i$d = ($d+ANGLELENGTH)>$ed?$ed:($d+ANGLELENGTH);
  108. list( $x, $y) = getExy($a, $b, $d);
  109. imageline($img, $x0+$ox, $y0+$oy, $x+$ox, $y+$oy, $clr);
  110. $x0 = $x;
  111. $y0 = $y;
  112. }
  113. imageline($img, $x0+$ox, $y0+$oy, $ox, $oy, $clr);
  114. list($x, $y) = getExy($a/2, $b/2, ($d+$sd)/2);
  115. imagefill($img, $x+$ox, $y+$oy, $clr);
  116. }
  117. /**
  118. * Get the shadow color of the corresponding column based on $clr color
  119. * @param $img image
  120. * @param $clr color
  121. * @return rgb color array
  122. */
  123. function drawDarkColor($img,$clr){
  124. $rgb = imagecolorsforindex($img,$clr);
  125. return array($rgb["red"]/2,$rgb["green"]/ 2,$rgb["blue"]/2);
  126. }
  127. /**
  128. * Find the coordinates of the point on the ellipse corresponding to angle $d
  129. *
  130. * @param $a Abscissa coordinate
  131. * @param $b Vertical coordinate
  132. * @param $d Angle
  133. * @return Corresponding ellipse point coordinate
  134. */
  135. function getExy($a, $b, $d){
  136. $d = deg2rad($d);
  137. return array(round($a*cos($d)), round($b*sin($d)));
  138. }
  139. /**
  140. * Assign RGB indexed color to image
  141. */
  142. function drawIndexColor($img, $clr){
  143. $red = ($clr>>16) & 0xff;
  144. $green = ($clr>>8)& 0xff;
  145. $blue = ($clr) & 0xff;
  146. return imagecolorallocate($img, $red, $green, $blue);
  147. }
  148. //Test example
  149. $title = "Zoo Animal Type Distribution";
  150. $dataArr = array(20, 10, 20, 20, 10, 20, 30, 10); //Test data array
  151. $labelArr = array("elephant", "giraffe", "crocodile", "ostrich", "tiger" ", "Lion", "Monkey", "Zebra"); //Tag
  152. $colorArr = array(0x99ff00, 0xff6666, 0x0099ff, 0xff99ff, 0xffff99, 0x99ffff, 0xff3333, 0x009999); //Corresponding color array
  153. $result = drawPieImg($title, $dataArr,$labelArr,$colorArr);
  154. echo "PHP code example for drawing pie chart";
  155. ?>
Copy code

Code description: The drawPieImg() function contains 8 parameters. $title is the title of the pie chart; $dataArr is the data array that needs to be displayed; $labelArr is the label classification array of the corresponding data; $colorArr is the drawing color array of the corresponding data. These 4 Parameters are required, just pass the corresponding parameters for different system applications.

The remaining 4 parameters are responsible for setting the size of the pie chart to be generated. If not set, the system default value will be used. The program starts drawing from 0 degrees according to the size of the array data at the bottom of the bed, and draws the sector size occupied by the corresponding data in a clockwise direction.

For those who are interested, please try the above code and see how the pie chart looks like? !



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)