1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
|
<?php
/* $Id: phplot.php,v 1.224 2011/05/27 18:05:16 lbayuk Exp $ */
/*
* PHPLOT Version 5.4.0
*
* A PHP class for creating scientific and business charts
* Visit http://sourceforge.net/projects/phplot/
* for PHPlot documentation, downloads, and discussions.
* ---------------------------------------------------------------------
* Copyright (C) 1998-2011 Afan Ottenheimer
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ---------------------------------------------------------------------
*
* Co-author and maintainer (2003-2005)
* Miguel de Benito Delgado <nonick AT vodafone DOT es>
*
* Maintainer (2006-present)
* <lbayuk AT users DOT sourceforge DOT net>
*
* Requires PHP 5.2.x or later. (PHP 4 is unsupported as of Jan 2008)
*/
class PHPlot
{
const version = '5.4.0';
/* Declare class variables which are initialized to static values. Many more class variables
* are used, defined as needed, but are unset by default.
* All these are declared as public. While it is tempting to make them private or protected, this
* is avoided for two reasons. First, it will break existing code, since all member variables
* were public in PHP4 and who knows what internal variables people used. Second, it makes
* testing harder and less effective. Nevertheless, your code should not modify these.
*/
public $is_inline = FALSE; // FALSE = Sends headers, TRUE = sends just raw image data
public $browser_cache = FALSE; // FALSE = Sends headers for browser to not cache the image,
// (only if is_inline = FALSE also)
public $print_image = TRUE; // DrawGraph calls PrintImage. See SetPrintImage
public $safe_margin = 5; // Extra margin used in several places, in pixels
public $x_axis_position = ''; // X axis position in Y world coordinates, blank for default.
public $y_axis_position = ''; // Y axis position in X world coordinates, blank for default.
public $xscale_type = 'linear'; // linear, log
public $yscale_type = 'linear';
//Fonts
public $use_ttf = FALSE; // Use True Type Fonts by default?
public $ttf_path = '.'; // Default path to look in for TT Fonts.
// public $default_ttfont; // Initialized in GetDefaultTTFont
public $line_spacing = 4; // Controls line spacing of multi-line labels
// Label angles: 0 or 90 degrees for fixed fonts, any for TTF
public $x_label_angle = 0; // For X tick labels
// public $x_data_label_angle; // For X data labels; defaults to x_label_angle - see CheckLabels()
public $y_label_angle = 0; // For Y tick labels
public $y_data_label_angle = 0; // For Y data labels
//Formats
public $file_format = 'png';
public $output_file = ''; // For output to a file instead of stdout
//Data
public $data_type = 'text-data'; // Structure of the data array
public $plot_type = 'linepoints'; // See $plots[] below
public $label_scale_position = 0.5; // Shifts data labels in pie charts. 1 = top, 0 = bottom
public $group_frac_width = 0.7; // Bars use this fraction (0 to 1) of a group's space
public $bar_extra_space = 0.5; // Number of extra bar's worth of space in a group
public $bar_width_adjust = 1; // 1 = bars of normal width, must be > 0
// Titles
public $title_txt = '';
public $x_title_txt = '';
public $x_title_pos = 'none'; // plotdown, plotup, both, none
public $y_title_txt = '';
public $y_title_pos = 'none'; // plotleft, plotright, both, none
//Labels
// There are two types of labels in PHPlot:
// Tick labels: Follow the grid, next to ticks in axis.
// Are drawn at grid drawing time, by DrawXTicks() and DrawYTicks()
// Data labels: Follow the data points, and can be placed on the axis or the plot (x/y)
// Are drawn at graph plotting time, by Draw*DataLabel(), called by DrawLines(), etc.
// DrawXDataLabel() also draws vertical lines to data points, depending on
// draw_x_data_label_lines.
// Tick Labels
// Tick and Data label positions are not initialized, because PHPlot needs to tell if they
// defaulted or are set by the user. See CheckLabels() for details. The variables and
// effective defaults are shown here in comments (but CheckLabels adjusts the defaults).
// public $x_tick_label_pos = 'plotdown'; // X tick label position
// public $y_tick_label_pos = 'plotleft'; // Y tick label position
// public $x_data_label_pos = 'plotdown'; // X data label position
// public $y_data_label_pos = 'none'; // Y data label position
public $draw_x_data_label_lines = FALSE; // Draw a line from the data point to the axis?
// Label format controls: (for tick, data and plot labels)
// Unset by default, these array members are used as needed for 'x' (x tick labels), 'xd' (x data
// labels), 'y' (y tick labels), and 'yd' (y data labels).
// type, precision, prefix, suffix, time_format, printf_format, custom_callback, custom_arg.
// These replace the former: x_label_type, x_time_format, x_precision (similar for y), data_units_text.
public $label_format = array('x' => array(), 'xd' => array(), 'y' => array(), 'yd' => array());
// data_units_text is retained for backward compatibility, because there was never a function
// to set it. Use the 'suffix' argument to Set[XY]LabelType instead.
public $data_units_text = ''; // Units text for 'data' labels (i.e: '¤', '$', etc.)
// Legend
public $legend = ''; // An array with legend titles
// Other legend_* variables are set as needed, unset for default values.
//Ticks
public $x_tick_length = 5; // tick length in pixels for upper/lower axis
public $y_tick_length = 5; // tick length in pixels for left/right axis
public $x_tick_cross = 3; // ticks cross x axis this many pixels
public $y_tick_cross = 3; // ticks cross y axis this many pixels
public $x_tick_pos = 'plotdown'; // plotdown, plotup, both, xaxis, none
public $y_tick_pos = 'plotleft'; // plotright, plotleft, both, yaxis, none
public $num_x_ticks = '';
public $num_y_ticks = '';
public $x_tick_inc = ''; // Set num_x_ticks or x_tick_inc, not both.
public $y_tick_inc = ''; // Set num_y_ticks or y_tick_inc, not both.
public $skip_top_tick = FALSE;
public $skip_bottom_tick = FALSE;
public $skip_left_tick = FALSE;
public $skip_right_tick = FALSE;
//Grid Formatting
// public $draw_x_grid = FALSE; // Default is False except for swapped data type
// public $draw_y_grid = TRUE; // Default is True except for swapped data type
public $dashed_grid = TRUE;
public $grid_at_foreground = FALSE; // Chooses whether to draw the grid below or above the graph
//Colors and styles (all colors can be array (R,G,B) or named color)
public $color_array = 'small'; // 'small', 'large' or array (define your own colors)
// See rgb.inc.php and SetRGBArray()
public $default_colors = array( // The default colors for data and error bars
'SkyBlue', 'green', 'orange', 'blue', 'red', 'DarkGreen', 'purple', 'peru',
'cyan', 'salmon', 'SlateBlue', 'YellowGreen', 'magenta', 'aquamarine1', 'gold', 'violet');
// See SetDefaultStyles() for default colors for PHPlot elements.
public $line_widths = 1; // single value or array
public $line_styles = array('solid', 'solid', 'dashed'); // single value or array
public $dashed_style = '2-4'; // colored dots-transparent dots
public $point_sizes = array(6); // Array of sizes for points. See CheckPointParams()
public $point_shapes = array( // Array of point shapes. See SetPointShapes() and DrawDot()
'diamond', 'dot', 'delta', 'home', 'yield', 'box', 'circle', 'up', 'down', 'cross'
);
public $error_bar_size = 5; // right and left size of tee
public $error_bar_shape = 'tee'; // 'tee' or 'line'
public $error_bar_line_width = 1; // single value (or array TODO)
public $plot_border_type = 'sides'; // left, right, top, bottom, sides, none, full; or array
public $image_border_type = 'none'; // 'raised', 'plain', 'none'
// public $image_border_width; // NULL, 0, or unset for default. Default depends on type.
public $shading = 5; // 0 for no shading, > 0 is size of shadows in pixels
public $draw_plot_area_background = FALSE;
public $draw_broken_lines = FALSE; // Tells not to draw lines for missing Y data.
//Miscellaneous
public $callbacks = array( // Valid callback reasons (see SetCallBack)
'draw_setup' => NULL,
'draw_image_background' => NULL,
'draw_plotarea_background' => NULL,
'draw_titles' => NULL,
'draw_axes' => NULL,
'draw_graph' => NULL,
'draw_border' => NULL,
'draw_legend' => NULL,
'draw_all' => NULL,
'data_color' => NULL,
'debug_textbox' => NULL, // For testing/debugging text box alignment
'debug_scale' => NULL, // For testing/debugging scale setup
);
// Defined plot types static array:
// Array key is the plot type. (Upper case letters are not allowed due to CheckOption)
// Value is an array with these keys:
// draw_method (required) : Class method to call to draw the plot.
// draw_arg : Optional array of arguments to pass to draw_method.
// draw_axes : If FALSE, do not draw X/Y axis lines, labels, ticks, grid, titles.
// abs_vals, sum_vals : Data array processing flags. See FindDataLimits().
static protected $plots = array(
'area' => array(
'draw_method' => 'DrawArea',
'abs_vals' => TRUE,
),
'bars' => array(
'draw_method' => 'DrawBars',
),
'candlesticks' => array(
'draw_method' => 'DrawOHLC',
'draw_arg' => array(TRUE, FALSE), // Draw candlesticks, only fill if "closed down"
),
'candlesticks2' => array(
'draw_method' => 'DrawOHLC',
'draw_arg' => array(TRUE, TRUE), // Draw candlesticks, fill always
),
'linepoints' => array(
'draw_method' => 'DrawLinePoints',
),
'lines' => array(
'draw_method' => 'DrawLines',
),
'ohlc' => array(
'draw_method' => 'DrawOHLC',
'draw_arg' => array(FALSE), // Don't draw candlesticks
),
'pie' => array(
'draw_method' => 'DrawPieChart',
'draw_axes' => FALSE,
'abs_vals' => TRUE,
),
'points' => array(
'draw_method' => 'DrawDots',
),
'squared' => array(
'draw_method' => 'DrawSquared',
),
'stackedarea' => array(
'draw_method' => 'DrawArea',
'draw_arg' => array(TRUE), // Tells DrawArea to draw stacked area plot
'sum_vals' => TRUE,
'abs_vals' => TRUE,
),
'stackedbars' => array(
'draw_method' => 'DrawStackedBars',
'sum_vals' => TRUE,
),
'thinbarline' => array(
'draw_method' => 'DrawThinBarLines',
),
);
//////////////////////////////////////////////////////
//BEGIN CODE
//////////////////////////////////////////////////////
/*
* Constructor: Setup img resource, colors and size of the image, and font sizes.
*
* $which_width : Image width in pixels.
* $which_height : Image height in pixels.
* $which_output_file : Filename for output.
* $which_input_file : Path to a file to be used as background.
*/
function PHPlot($which_width=600, $which_height=400, $which_output_file=NULL, $which_input_file=NULL)
{
$this->SetRGBArray($this->color_array);
if ($which_output_file)
$this->SetOutputFile($which_output_file);
if ($which_input_file) {
$this->SetInputFile($which_input_file);
} else {
$this->image_width = $which_width;
$this->image_height = $which_height;
$this->img = ImageCreate($this->image_width, $this->image_height);
if (! $this->img)
return $this->PrintError('PHPlot(): Could not create image resource.');
}
$this->SetDefaultStyles();
$this->SetDefaultFonts();
}
/*
* Reads an image file. Stores width and height, and returns the image
* resource. On error, calls PrintError and returns False.
* This is used by the constructor via SetInputFile, and by tile_img().
*/
protected function GetImage($image_filename, &$width, &$height)
{
$error = '';
$size = getimagesize($image_filename);
if (!$size) {
$error = "Unable to query image file $image_filename";
} else {
$image_type = $size[2];
switch ($image_type) {
case IMAGETYPE_GIF:
$img = @ ImageCreateFromGIF ($image_filename);
break;
case IMAGETYPE_PNG:
$img = @ ImageCreateFromPNG ($image_filename);
break;
case IMAGETYPE_JPEG:
$img = @ ImageCreateFromJPEG ($image_filename);
break;
default:
$error = "Unknown image type ($image_type) for image file $image_filename";
break;
}
}
if (empty($error) && !$img) {
// getimagesize is OK, but GD won't read it. Maybe unsupported format.
$error = "Failed to read image file $image_filename";
}
if (!empty($error)) {
return $this->PrintError("GetImage(): $error");
}
$width = $size[0];
$height = $size[1];
return $img;
}
/*
* Selects an input file to be used as background for the whole graph.
* This resets the graph size to the image's size.
* Note: This is used by the constructor. It is deprecated for direct use.
*/
function SetInputFile($which_input_file)
{
$im = $this->GetImage($which_input_file, $this->image_width, $this->image_height);
if (!$im)
return FALSE; // GetImage already produced an error message.
// Deallocate any resources previously allocated
if (isset($this->img))
imagedestroy($this->img);
$this->img = $im;
// Do not overwrite the input file with the background color.
$this->done['background'] = TRUE;
return TRUE;
}
/////////////////////////////////////////////
////////////// COLORS
/////////////////////////////////////////////
/*
* Allocate a GD color index for a color specified by a 4 component array.
* When a color is requested, it is parsed and checked by SetRGBColor, and then saved as an array
* of (R,G,B,A) components. At graph drawing time, this function is used to allocate the color.
* $color : The color specification as a 4 component array: R, G, B, A.
* Returns: A GD color index that can be used when drawing.
*/
protected function GetColorIndex($color)
{
list($r, $g, $b, $a) = $color;
return imagecolorresolvealpha($this->img, $r, $g, $b, $a);
}
/*
* Allocate an array of GD color indexes for an array of color specifications.
* This is used for the data_colors array, for example.
* $color_array : Array of color specifications, each an array of R,G,B,A components.
* This must use 0-based sequential integer indexes.
* $max_colors : Limit color allocation to no more than this.
* Returns an array of GD color indexes.
*/
protected function GetColorIndexArray($color_array, $max_colors)
{
$n = min(count($color_array), $max_colors);
$result = array();
for ($i = 0; $i < $n; $i++)
$result[] = $this->GetColorIndex($color_array[$i]);
return $result;
}
/*
* Allocate an array of GD color indexes for darker shades of an array of color specifications.
* $color_array : Array of color specifications, each an array of R,G,B,A components.
* $max_colors : Limit color allocation to this many colors from the array.
* Returns an array of GD color indexes.
*/
protected function GetDarkColorIndexArray($color_array, $max_colors)
{
$n = min(count($color_array), $max_colors);
$result = array();
for ($i = 0; $i < $n; $i++)
$result[] = $this->GetDarkColorIndex($color_array[$i]);
return $result;
}
/*
* Allocate a GD color index for a darker shade of a color specified by a 4 component array.
* See notes for GetColorIndex() above.
* $color : The color specification as a 4 component array: R, G, B, A.
* Returns: A GD color index that can be used when drawing.
*/
protected function GetDarkColorIndex($color)
{
list ($r, $g, $b, $a) = $color;
$r = max(0, $r - 0x30);
$g = max(0, $g - 0x30);
$b = max(0, $b - 0x30);
return imagecolorresolvealpha($this->img, $r, $g, $b, $a);
}
/*
* Sets/reverts all colors and styles to their defaults.
*/
protected function SetDefaultStyles()
{
$this->SetDefaultDashedStyle($this->dashed_style);
$this->SetImageBorderColor(array(194, 194, 194));
$this->SetPlotBgColor('white');
$this->SetBackgroundColor('white');
$this->SetTextColor('black');
$this->SetGridColor('black');
$this->SetLightGridColor('gray');
$this->SetTickColor('black');
$this->SetTitleColor('black');
// These functions set up the default colors when called without parameters
$this->SetDataColors();
$this->SetErrorBarColors();
$this->SetDataBorderColors();
return TRUE;
}
/*
* Set the image background color to $which_color.
*/
function SetBackgroundColor($which_color)
{
return (bool)($this->bg_color = $this->SetRGBColor($which_color));
}
/*
* Set the plot area background color (if enabled) to $which_color.
*/
function SetPlotBgColor($which_color)
{
return (bool)($this->plot_bg_color = $this->SetRGBColor($which_color));
}
/*
* Set the color of the titles (main, X, and Y) to $which_color.
* See also SetXTitleColor and SetYTitleColor.
*/
function SetTitleColor($which_color)
{
return (bool)($this->title_color = $this->SetRGBColor($which_color));
}
/*
* Set the color of the X title to $which_color.
* This overrides the color set with SetTitleColor.
*/
function SetXTitleColor($which_color)
{
return (bool)($this->x_title_color = $this->SetRGBColor($which_color));
}
/*
* Set the color of the Y title to $which_color.
* This overrides the color set with SetTitleColor.
*/
function SetYTitleColor($which_color)
{
return (bool)($this->y_title_color = $this->SetRGBColor($which_color));
}
/*
* Set the color of the axis tick marks to $which_color.
*/
function SetTickColor($which_color)
{
return (bool)($this->tick_color = $this->SetRGBColor($which_color));
}
/*
* Deprecated. Use SetTitleColor()
*/
function SetLabelColor($which_color)
{
return $this->SetTitleColor($which_color);
}
/*
* Set the general text color (tick and data labels, legend, etc) to $which_color.
*/
function SetTextColor($which_color)
{
return (bool)($this->text_color = $this->SetRGBColor($which_color));
}
/*
* Set the X and Y grid colors to $which_color. Also sets the data label line color.
*/
function SetLightGridColor($which_color)
{
return (bool)($this->light_grid_color = $this->SetRGBColor($which_color));
}
/*
* Set the color used for the X and Y axis, plot border, legend border to $which_color.
* Note: This has nothing to do with the grid, and we don't recall where this name came from.
*/
function SetGridColor($which_color)
{
return (bool)($this->grid_color = $this->SetRGBColor($which_color));
}
/*
* Set the color used for the image border to $which_color.
*/
function SetImageBorderColor($which_color)
{
return (bool)($this->i_border = $this->SetRGBColor($which_color));
}
/*
* Designate color $which_color to be transparent, if supported by the image format.
*/
function SetTransparentColor($which_color)
{
return (bool)($this->transparent_color = $this->SetRGBColor($which_color));
}
/*
* Sets the array of colors to be used. It can be user defined, a small predefined one
* or a large one included from 'rgb.inc.php'.
*
* $which_color_array : A color array, or 'small' or 'large'.
* Color arrays map color names into arrays of R, G, B and optionally A values.
*/
function SetRGBArray($which_color_array)
{
if (is_array($which_color_array)) { // User defined array
$this->rgb_array = $which_color_array;
} elseif ($which_color_array == 'small') { // Small predefined color array
$this->rgb_array = array(
'white' => array(255, 255, 255),
'snow' => array(255, 250, 250),
'PeachPuff' => array(255, 218, 185),
'ivory' => array(255, 255, 240),
'lavender' => array(230, 230, 250),
'black' => array( 0, 0, 0),
'DimGrey' => array(105, 105, 105),
'gray' => array(190, 190, 190),
'grey' => array(190, 190, 190),
'navy' => array( 0, 0, 128),
'SlateBlue' => array(106, 90, 205),
'blue' => array( 0, 0, 255),
'SkyBlue' => array(135, 206, 235),
'cyan' => array( 0, 255, 255),
'DarkGreen' => array( 0, 100, 0),
'green' => array( 0, 255, 0),
'YellowGreen' => array(154, 205, 50),
'yellow' => array(255, 255, 0),
'orange' => array(255, 165, 0),
'gold' => array(255, 215, 0),
'peru' => array(205, 133, 63),
'beige' => array(245, 245, 220),
'wheat' => array(245, 222, 179),
'tan' => array(210, 180, 140),
'brown' => array(165, 42, 42),
'salmon' => array(250, 128, 114),
'red' => array(255, 0, 0),
'pink' => array(255, 192, 203),
'maroon' => array(176, 48, 96),
'magenta' => array(255, 0, 255),
'violet' => array(238, 130, 238),
'plum' => array(221, 160, 221),
'orchid' => array(218, 112, 214),
'purple' => array(160, 32, 240),
'azure1' => array(240, 255, 255),
'aquamarine1' => array(127, 255, 212)
);
} elseif ($which_color_array == 'large') { // Large color array
if (!@include('rgb.inc.php')) {
return $this->PrintError("SetRGBArray(): Large color map could not be loaded\n"
. "from 'rgb.inc.php'.");
}
$this->rgb_array = $ColorArray;
} else { // Default to black and white only.
$this->rgb_array = array('white' => array(255, 255, 255), 'black' => array(0, 0, 0));
}
return TRUE;
}
/*
* Parse a color description and return the color component values.
* Arguments:
* $color_asked : The desired color description, in one of these forms:
* Component notation: array(R, G, B) or array(R, G, B, A) with each
* in the range described below for the return value.
* Examples: (255,255,0) (204,0,0,30)
* Hex notation: "#RRGGBB" or "#RRGGBBAA" where each pair is a 2 digit hex number.
* Examples: #FF00FF (magenta) #0000FF40 (Blue with alpha=64/127)
* Named color in the current colormap, with optional suffix ":alpha" for alpha value.
* Examples: blue red:60 yellow:20
* $alpha : optional default alpha value. This is applied to the color if it doesn't
* already have an alpha value. If not supplied, colors are opaque (alpha=0) by default.
*
* Returns an array describing a color as (R, G, B, Alpha).
* R, G, and B are integers 0-255, and Alpha is 0 (opaque) to 127 (transparent).
* Note: This function should be considered 'protected', and is not documented for public use.
*/
function SetRGBColor($color_asked, $alpha = 0)
{
if (empty($color_asked)) {
$ret_val = array(0, 0, 0);
} elseif (is_array($color_asked) && (($n = count($color_asked)) == 3 || $n == 4) ) {
// Already an array of 3 or 4 elements:
$ret_val = $color_asked;
} elseif (preg_match('/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i',
$color_asked, $ss)) {
// #RRGGBB or #RRGGBBAA notation:
$ret_val = array(hexdec($ss[1]), hexdec($ss[2]), hexdec($ss[3]));
if (isset($ss[4])) $ret_val[] = hexdec($ss[4]);
} elseif (isset($this->rgb_array[$color_asked])) {
// Color by name:
$ret_val = $this->rgb_array[$color_asked];
} elseif (preg_match('/(.+):([\d]+)$/', $color_asked, $ss)
&& isset($this->rgb_array[$ss[1]])) {
// Color by name with ":alpha" suffix, alpha is a decimal number:
$ret_val = $this->rgb_array[$ss[1]];
$ret_val[3] = (int)$ss[2];
} else {
return $this->PrintError("SetRGBColor(): Color '$color_asked' is not valid.");
}
// Append alpha if not already provided for:
if (count($ret_val) == 3)
$ret_val[] = $alpha;
return $ret_val;
}
/*
* Sets the colors for the data, with optional default alpha value
* Cases are:
* SetDataColors(array(...)) : Use the supplied array as the color map.
* SetDataColors(colorname) : Use an array of just colorname as the color map.
* SetDataColors() or SetDataColors(NULL) : Load default color map if no color map is already set.
* SetDataColors('') or SetDataColors(False) : Load default color map (even if one is already set).
* $which_border is passed to SetDataBorderColors, for backward compatibility.
* $alpha is a default Alpha to apply to all data colors that do not have alpha.
* The default for this is NULL, not 0, so we can tell if it was defaulted. But the effective
* default value is 0 (opaque).
*/
function SetDataColors($which_data = NULL, $which_border = NULL, $alpha = NULL)
{
if (is_array($which_data)) {
$colors = $which_data; // Use supplied array
} elseif (!empty($which_data)) {
$colors = array($which_data); // Use supplied single color
} elseif (empty($this->data_colors) || !is_null($which_data)) {
$colors = $this->default_colors; // Use default color array
} else {
// which_data is NULL or missing and a color array is already set.
// The existing color array is left alone, except that if $alpha is
// given this will replace the alpha value of each existing color.
// This makes SetDataColors(NULL, NULL, $alpha) work.
if (isset($alpha)) {
$n_colors = count($this->data_colors);
for ($i = 0; $i < $n_colors; $i++) {
$this->data_colors[$i][3] = $alpha; // Component 3 = alpha value
}
}
// No need to reparse the colors or anything else.
return TRUE;
}
if (!isset($alpha))
$alpha = 0; // Actual default is opaque colors.
// Check each color and convert to array (r,g,b,a) form.
// Use the $alpha argument as a default for the alpha value of each color.
$this->data_colors = array();
foreach ($colors as $color) {
$color_array = $this->SetRGBColor($color, $alpha);
if (!$color_array) return FALSE; // SetRGBColor already did an error message.
$this->data_colors[] = $color_array;
}
// For past compatibility:
return $this->SetDataBorderColors($which_border);
}
/*
* Set the colors for the bars and stacked bars outlines.
* Argument usage is similar to SetDataColors(), except the default is just black.
*/
function SetDataBorderColors($which_br = NULL)
{
if (is_array($which_br)) {
$colors = $which_br; // Use supplied array
} elseif (!empty($which_br)) {
$colors = array($which_br); // Use supplied single color
} elseif (empty($this->data_border_colors) || !is_null($which_br)) {
$colors = array('black'); // Use default
} else {
return TRUE; // Do nothing: which_br is NULL or missing and a color array is already set.
}
// Check each color and convert to array (r,g,b,a) form.
$this->data_border_colors = array();
foreach ($colors as $color) {
$color_array = $this->SetRGBColor($color);
if (!$color_array) return FALSE; // SetRGBColor already did an error message.
$this->data_border_colors[] = $color_array;
}
return TRUE;
}
/*
* Sets the colors for the data error bars.
* Argument usage is the same as SetDataColors().
*/
function SetErrorBarColors($which_err = NULL)
{
if (is_array($which_err)) {
$colors = $which_err; // Use supplied array
} elseif (!empty($which_err)) {
$colors = array($which_err); // Use supplied single color
} elseif (empty($this->error_bar_colors) || !is_null($which_err)) {
$colors = $this->default_colors; // Use default color array
} else {
return TRUE; // Do nothing: which_err is NULL or missing and a color array is already set.
}
// Check each color and convert to array (r,g,b,a) form.
$this->error_bar_colors = array();
foreach ($colors as $color) {
$color_array = $this->SetRGBColor($color);
if (!$color_array) return FALSE; // SetRGBColor already did an error message.
$this->error_bar_colors[] = $color_array;
}
return TRUE;
}
/*
* Sets the default dashed line style.
* $which_style : A string specifying the dashed line style, as alternating numbers
* of the length (in pixels) of lines and spaces, separated by dashes.
* For example: '2-3-1-2' means 2 dots of color, 3 transparent, 1 color, then 2 transparent.
* This builds a string which will evaluate to an array of integers. Each colored dot
* is '$which_ndxcol' and each transparent dot is 'IMG_COLOR_TRANSPARENT'. When SetDashedStyle()
* eval's this with $which_ndxcol set, the result is a GD line style array.
*/
function SetDefaultDashedStyle($which_style)
{
// Explode "numcol-numtrans-numcol-numtrans..." into segment counts:
$asked = explode('-', $which_style);
if (count($asked) < 2) {
return $this->PrintError("SetDefaultDashedStyle(): Wrong parameter '$which_style'.");
}
// Build the string to be evaluated later by SetDashedStyle() with $which_ndxcolor set.
$result = '';
$vals = array('$which_ndxcol,', 'IMG_COLOR_TRANSPARENT,');
$index = 0;
foreach ($asked as $n) {
$result .= str_repeat($vals[$index], $n);
$index = 1 - $index;
}
$this->default_dashed_style = "array($result)";
return TRUE;
}
/*
* Sets the style before drawing a dashed line. Defaults to $this->default_dashed_style
* $which_ndxcol : Color index to be used.
*/
protected function SetDashedStyle($which_ndxcol)
{
// See SetDefaultDashedStyle() to understand this.
eval ("\$style = $this->default_dashed_style;");
return imagesetstyle($this->img, $style);
}
/*
* Set line widths for each data set.
* $which_lw : Array of line widths in pixels, or a single value to use for all data sets.
*/
function SetLineWidths($which_lw=NULL)
{
if (is_array($which_lw)) {
$this->line_widths = $which_lw; // Use provided array
} elseif (!is_null($which_lw)) {
$this->line_widths = array($which_lw); // Convert value to array
}
return TRUE;
}
/*
* Set line style ('solid' or 'dashed') for each data set.
* $which_ls : Array of keywords, or a single keyword to use for all data sets.
*/
function SetLineStyles($which_ls=NULL)
{
if (is_array($which_ls)) {
$this->line_styles = $which_ls; // Use provided array
} elseif (!is_null($which_ls)) {
$this->line_styles = ($which_ls) ? array($which_ls) : array('solid');
}
return TRUE;
}
/////////////////////////////////////////////
////////////// TEXT and FONTS
/////////////////////////////////////////////
/*
* Controls the line spacing of multi-line labels.
* $which_spc : Line spacing factor for text
* For GD text, this is the number of pixels between lines.
* For TTF text, it controls line spacing in proportion to the normal
* spacing defined by the font.
*/
function SetLineSpacing($which_spc)
{
$this->line_spacing = $which_spc;
return TRUE;
}
/*
* Select the default font type to use.
* $which_ttf : True to default to TrueType, False to default to GD (fixed) fonts.
* This also resets all font settings to the defaults.
*/
function SetUseTTF($which_ttf)
{
$this->use_ttf = $which_ttf;
return $this->SetDefaultFonts();
}
/*
* Sets the directory name to look into for TrueType fonts.
*/
function SetTTFPath($which_path)
{
if (!is_dir($which_path) || !is_readable($which_path)) {
return $this->PrintError("SetTTFPath(): $which_path is not a valid path.");
}
$this->ttf_path = $which_path;
return TRUE;
}
/*
* Sets the default TrueType font and updates all fonts to that.
* The default font might be a full path, or relative to the TTFPath,
* so let SetFont check that it exists.
* Side effects: Enables use of TrueType fonts as the default font type,
* and resets all font settings.
*/
function SetDefaultTTFont($which_font)
{
$this->default_ttfont = $which_font;
return $this->SetUseTTF(TRUE);
}
/*
* Return the default TrueType font name. If no default has been set,
* this tries some likely candidates for a font which can be loaded.
* If it finds one that works, that becomes the default TT font.
* If there is no default and it cannot find a working font, it falls
* back to the original PHPlot default (which will not likely work either).
*/
protected function GetDefaultTTFont()
{
if (!isset($this->default_ttfont)) {
// No default font yet. Try some common sans-serif fonts.
$fonts = array('LiberationSans-Regular.ttf', // For Linux with a correct GD font search path
'Verdana.ttf', 'Arial.ttf', 'Helvetica.ttf', // For Windows, maybe others
'ttf-liberation/LiberationSans-Regular.ttf', // For Debian, Ubuntu, and friends
'benjamingothic.ttf', // Original PHPlot default
);
foreach ($fonts as $font) {
// First try the font name alone, to see if GD can find and load it.
if (@imagettfbbox(10, 0, $font, "1") !== False)
break;
// If the font wasn't found, try it with the default TTF path in front.
$font_with_path = $this->ttf_path . DIRECTORY_SEPARATOR . $font;
if (@imagettfbbox(10, 0, $font_with_path, "1") !== False) {
$font = $font_with_path;
break;
}
}
// We either have a working font, or are using the last one regardless.
$this->default_ttfont = $font;
}
return $this->default_ttfont;
}
/*
* Sets fonts to their defaults
*/
protected function SetDefaultFonts()
{
// TTF:
if ($this->use_ttf) {
return $this->SetFont('generic', '', 8)
&& $this->SetFont('title', '', 14)
&& $this->SetFont('legend', '', 8)
&& $this->SetFont('x_label', '', 6)
&& $this->SetFont('y_label', '', 6)
&& $this->SetFont('x_title', '', 10)
&& $this->SetFont('y_title', '', 10);
}
// Fixed GD Fonts:
return $this->SetFont('generic', 2)
&& $this->SetFont('title', 5)
&& $this->SetFont('legend', 2)
&& $this->SetFont('x_label', 1)
&& $this->SetFont('y_label', 1)
&& $this->SetFont('x_title', 3)
&& $this->SetFont('y_title', 3);
}
/*
* Select a fixed (GD) font for an element.
* This allows using a fixed font, even with SetUseTTF(True).
* $which_elem : The element whose font is to be changed.
* One of: title legend generic x_label y_label x_title y_title
* $which_font : A GD font number 1-5
* $which_spacing (optional) : Line spacing factor
*/
function SetFontGD($which_elem, $which_font, $which_spacing = NULL)
{
if ($which_font < 1 || 5 < $which_font) {
return $this->PrintError(__FUNCTION__ . ': Font size must be 1, 2, 3, 4 or 5');
}
if (!$this->CheckOption($which_elem,
'generic, title, legend, x_label, y_label, x_title, y_title',
__FUNCTION__)) {
return FALSE;
}
// Store the font parameters: name/size, char cell height and width.
$this->fonts[$which_elem] = array('ttf' => FALSE,
'font' => $which_font,
'height' => ImageFontHeight($which_font),
'width' => ImageFontWidth($which_font),
'line_spacing' => $which_spacing);
return TRUE;
}
/*
* Select a TrueType font for an element.
* This allows using a TrueType font, even with SetUseTTF(False).
* $which_elem : The element whose font is to be changed.
* One of: title legend generic x_label y_label x_title y_title
* $which_font : A TrueType font filename or pathname.
* $which_size : Font point size.
* $which_spacing (optional) : Line spacing factor
*/
function SetFontTTF($which_elem, $which_font, $which_size = 12, $which_spacing = NULL)
{
if (!$this->CheckOption($which_elem,
'generic, title, legend, x_label, y_label, x_title, y_title',
__FUNCTION__)) {
return FALSE;
}
// Empty font name means use the default font.
if (empty($which_font))
$which_font = $this->GetDefaultTTFont();
$path = $which_font;
// First try the font name directly, if not then try with path.
// Use GD imagettfbbox() to determine if this is a valid font.
// The return $bbox is used below, if valid.
if (($bbox = @imagettfbbox($which_size, 0, $path, "E")) === False) {
$path = $this->ttf_path . DIRECTORY_SEPARATOR . $which_font;
if (($bbox = @imagettfbbox($which_size, 0, $path, "E")) === False) {
return $this->PrintError(__FUNCTION__ . ": Can't find TrueType font $which_font");
}
}
// Calculate the font height and inherent line spacing. TrueType fonts have this information
// internally, but PHP/GD has no way to directly access it. So get the bounding box size of
// an upper-case character without descenders, and the baseline-to-baseline height.
// Note: In practice, $which_size = $height, maybe +/-1 . But which_size is in points,
// and height is in pixels, and someday GD may be able to tell the difference.
// The character width is saved too, but not used by the normal text drawing routines - it
// isn't necessarily a fixed-space font. It is used in DrawLegend.
$height = $bbox[1] - $bbox[5];
$width = $bbox[2] - $bbox[0];
$bbox = ImageTTFBBox($which_size, 0, $path, "E\nE");
$spacing = $bbox[1] - $bbox[5] - 2 * $height;
// Store the font parameters:
$this->fonts[$which_elem] = array('ttf' => TRUE,
'font' => $path,
'size' => $which_size,
'height' => $height,
'width' => $width,
'spacing' => $spacing,
'line_spacing' => $which_spacing);
return TRUE;
}
/*
* Select Fixed/TrueType font for an element. Which type of font is
* selected depends on the $use_ttf class variable (see SetUseTTF()).
* Before PHPlot supported mixing font types, only this function and
* SetUseTTF were available to select an overall font type, but now
* SetFontGD() and SetFontTTF() can be used for mixing font types.
* $which_elem : The element whose font is to be changed.
* One of: title legend generic x_label y_label x_title y_title
* $which_font : A number 1-5 for fixed fonts, or a TrueType font.
* $which_size : Ignored for Fixed fonts, point size for TrueType.
* $which_spacing (optional) : Line spacing factor
*/
function SetFont($which_elem, $which_font, $which_size = 12, $line_spacing = NULL)
{
if ($this->use_ttf)
return $this->SetFontTTF($which_elem, $which_font, $which_size, $line_spacing);
return $this->SetFontGD($which_elem, $which_font, $line_spacing);
}
/*
* Return the inter-line spacing for a font.
* This is an internal function, used by ProcessText* and DrawLegend.
* $font : A font array variable.
* Returns: Spacing, in pixels, between text lines.
*/
protected function GetLineSpacing($font)
{
// Use the per-font line spacing preference, if set, else the global value:
if (isset($font['line_spacing']))
$line_spacing = $font['line_spacing'];
else
$line_spacing = $this->line_spacing;
// For GD fonts, that is the spacing in pixels.
// For TTF, adjust based on the 'natural' font spacing (see SetFontTTF):
if ($font['ttf']) {
$line_spacing = (int)($line_spacing * $font['spacing'] / 6.0);
}
return $line_spacing;
}
/*
* Text drawing and sizing functions:
* ProcessText is meant for use only by DrawText and SizeText.
* ProcessText(True, ...) - Draw a block of text
* ProcessText(False, ...) - Just return ($width, $height) of
* the orthogonal bounding box containing the text.
* ProcessText is further split into separate functions for GD and TTF
* text, due to the size of the code.
*
* Horizontal and vertical alignment are relative to the drawing. That is:
* vertical text (90 deg) gets centered along Y position with
* v_align = 'center', and adjusted to the right of X position with
* h_align = 'right'. Another way to look at this is to say
* that text rotation happens first, then alignment.
*
* Original multiple lines code submitted by Remi Ricard.
* Original vertical code submitted by Marlin Viss.
*
* Text routines rewritten by ljb to fix alignment and position problems.
* Here is my explanation and notes. More information and pictures will be
* placed in the PHPlot Reference Manual.
*
* + Process TTF text one line at a time, not as a block. (See below)
* + Flipped top vs bottom vertical alignment. The usual interpretation
* is: bottom align means bottom of the text is at the specified Y
* coordinate. For some reason, PHPlot did left/right the correct way,
* but had top/bottom reversed. I fixed it, and left the default valign
* argument as bottom, but the meaning of the default value changed.
*
* For GD font text, only single-line text is handled by GD, and the
* basepoint is the upper left corner of each text line.
* For TTF text, multi-line text could be handled by GD, with the text
* basepoint at the lower left corner of the first line of text.
* (Behavior of TTF drawing routines on multi-line text is not documented.)
* But you cannot do left/center/right alignment on each line that way,
* or proper line spacing.
* Therefore, for either text type, we have to break up the text into
* lines and position each line independently.
*
* There are 9 alignment modes: Horizontal = left, center, or right, and
* Vertical = top, center, or bottom. Alignment is interpreted relative to
* the image, not as the text is read. This makes sense when you consider
* for example X axis labels. They need to be centered below the marks
* (center, top alignment) regardless of the text angle.
* 'Bottom' alignment really means baseline alignment.
*
* GD font text is supported (by libgd) at 0 degrees and 90 degrees only.
* Multi-line or single line text works with any of the 9 alignment modes.
*
* TTF text can be at any angle. The 9 alignment modes work for all angles,
* but the results might not be what you expect for multi-line text. See
* the PHPlot Reference Manual for pictures and details. In short, alignment
* applies to the orthogonal (aligned with X and Y axes) bounding box that
* contains the text, and to each line in the multi-line text box. Since
* alignment is relative to the image, 45 degree multi-line text aligns
* differently from 46 degree text.
*
* Note that PHPlot allows multi-line text for the 3 titles, and they
* are only drawn at 0 degrees (main and X titles) or 90 degrees (Y title).
* Data labels can also be multi-line, and they can be drawn at any angle.
* -ljb 2007-11-03
*
*/
/*
* ProcessTextGD() - Draw or size GD fixed-font text.
* This is intended for use only by ProcessText().
* $draw_it : True to draw the text, False to just return the orthogonal width and height.
* $font : PHPlot font array (with 'ttf' = False) - see SetFontGD()
* $angle : Text angle in degrees. GD only supports 0 and 90. We treat >= 45 as 90, else 0.
* $x, $y : Reference point for the text (ignored if !$draw_it)
* $color : GD color index to use for drawing the text (ignored if !$draw_it)
* $text : The text to draw or size. Put a newline between lines.
* $h_factor : Horizontal alignment factor: 0(left), .5(center), or 1(right) (ignored if !$draw_it)
* $v_factor : Vertical alignment factor: 0(top), .5(center), or 1(bottom) (ignored if !$draw_it)
* Returns: True, if drawing text, or an array of ($width, $height) if not.
*/
protected function ProcessTextGD($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor)
{
// Extract font parameters:
$font_number = $font['font'];
$font_width = $font['width'];
$font_height = $font['height'];
$line_spacing = $this->GetLineSpacing($font);
// Break up the text into lines, trim whitespace, find longest line.
// Save the lines and length for drawing below.
$longest = 0;
foreach (explode("\n", $text) as $each_line) {
$lines[] = $line = trim($each_line);
$line_lens[] = $line_len = strlen($line);
if ($line_len > $longest) $longest = $line_len;
}
$n_lines = count($lines);
// Width, height are based on font size and longest line, line count respectively.
// These are relative to the text angle.
$total_width = $longest * $font_width;
$total_height = $n_lines * $font_height + ($n_lines - 1) * $line_spacing;
if (!$draw_it) {
if ($angle < 45) return array($total_width, $total_height);
return array($total_height, $total_width);
}
$interline_step = $font_height + $line_spacing; // Line-to-line step
if ($angle >= 45) {
// Vertical text (90 degrees):
// (Remember the alignment convention with vertical text)
// For 90 degree text, alignment factors change like this:
$temp = $v_factor;
$v_factor = $h_factor;
$h_factor = 1 - $temp;
$draw_func = 'ImageStringUp';
// Rotation matrix "R" for 90 degrees (with Y pointing down):
$r00 = 0; $r01 = 1;
$r10 = -1; $r11 = 0;
} else {
// Horizontal text (0 degrees):
$draw_func = 'ImageString';
// Rotation matrix "R" for 0 degrees:
$r00 = 1; $r01 = 0;
$r10 = 0; $r11 = 1;
}
// Adjust for vertical alignment (horizontal text) or horizontal alignment (vertical text):
$factor = (int)($total_height * $v_factor);
$xpos = $x - $r01 * $factor;
$ypos = $y - $r11 * $factor;
// Debug callback provides the bounding box:
if ($this->GetCallback('debug_textbox')) {
if ($angle >= 45) {
$bbox_width = $total_height;
$bbox_height = $total_width;
$px = $xpos;
$py = $ypos - (1 - $h_factor) * $total_width;
} else {
$bbox_width = $total_width;
$bbox_height = $total_height;
$px = $xpos - $h_factor * $total_width;
$py = $ypos;
}
$this->DoCallback('debug_textbox', $px, $py, $bbox_width, $bbox_height);
}
for ($i = 0; $i < $n_lines; $i++) {
// Adjust for alignment of this line within the text block:
$factor = (int)($line_lens[$i] * $font_width * $h_factor);
$x = $xpos - $r00 * $factor;
$y = $ypos - $r10 * $factor;
// Call ImageString or ImageStringUp:
$draw_func($this->img, $font_number, $x, $y, $lines[$i], $color);
// Step to the next line of text. This is a rotation of (x=0, y=interline_spacing)
$xpos += $r01 * $interline_step;
$ypos += $r11 * $interline_step;
}
return TRUE;
}
/*
* ProcessTextTTF() - Draw or size TTF text.
* This is intended for use only by ProcessText().
* $draw_it : True to draw the text, False to just return the orthogonal width and height.
* $font : PHPlot font array (with 'ttf' = True) - see SetFontTTF()
* $angle : Text angle in degrees.
* $x, $y : Reference point for the text (ignored if !$draw_it)
* $color : GD color index to use for drawing the text (ignored if !$draw_it)
* $text : The text to draw or size. Put a newline between lines.
* $h_factor : Horizontal alignment factor: 0(left), .5(center), or 1(right) (ignored if !$draw_it)
* $v_factor : Vertical alignment factor: 0(top), .5(center), or 1(bottom) (ignored if !$draw_it)
* Returns: True, if drawing text, or an array of ($width, $height) if not.
*/
protected function ProcessTextTTF($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor)
{
// Extract font parameters (see SetFontTTF):
$font_file = $font['font'];
$font_size = $font['size'];
$font_height = $font['height'];
$line_spacing = $this->GetLineSpacing($font);
// Break up the text into lines, trim whitespace.
// Calculate the total width and height of the text box at 0 degrees.
// Save the trimmed lines and their widths for later when drawing.
// To get uniform spacing, don't use the actual line heights.
// Total height = Font-specific line heights plus inter-line spacing.
// Total width = width of widest line.
// Last Line Descent is the offset from the bottom to the text baseline.
// Note: For some reason, ImageTTFBBox uses (-1,-1) as the reference point.
// So 1+bbox[1] is the baseline to bottom distance.
$total_width = 0;
$lastline_descent = 0;
foreach (explode("\n", $text) as $each_line) {
$lines[] = $line = trim($each_line);
$bbox = ImageTTFBBox($font_size, 0, $font_file, $line);
$line_widths[] = $width = $bbox[2] - $bbox[0];
if ($width > $total_width) $total_width = $width;
$lastline_descent = 1 + $bbox[1];
}
$n_lines = count($lines);
$total_height = $n_lines * $font_height + ($n_lines - 1) * $line_spacing;
// Calculate the rotation matrix for the text's angle. Remember that GD points Y down,
// so the sin() terms change sign.
$theta = deg2rad($angle);
$cos_t = cos($theta);
$sin_t = sin($theta);
$r00 = $cos_t; $r01 = $sin_t;
$r10 = -$sin_t; $r11 = $cos_t;
// Make a bounding box of the right size, with upper left corner at (0,0).
// By convention, the point order is: LL, LR, UR, UL.
// Note this is still working with the text at 0 degrees.
// When sizing text (SizeText), use the overall size with descenders.
// This tells the caller how much room to leave for the text.
// When drawing text (DrawText), use the size without descenders - that
// is, down to the baseline. This is for accurate positioning.
$b[0] = 0;
if ($draw_it) {
$b[1] = $total_height;
} else {
$b[1] = $total_height + $lastline_descent;
}
$b[2] = $total_width; $b[3] = $b[1];
$b[4] = $total_width; $b[5] = 0;
$b[6] = 0; $b[7] = 0;
// Rotate the bounding box, then offset to the reference point:
for ($i = 0; $i < 8; $i += 2) {
$x_b = $b[$i];
$y_b = $b[$i+1];
$c[$i] = $x + $r00 * $x_b + $r01 * $y_b;
$c[$i+1] = $y + $r10 * $x_b + $r11 * $y_b;
}
// Get an orthogonal (aligned with X and Y axes) bounding box around it, by
// finding the min and max X and Y:
$bbox_ref_x = $bbox_max_x = $c[0];
$bbox_ref_y = $bbox_max_y = $c[1];
for ($i = 2; $i < 8; $i += 2) {
$x_b = $c[$i];
if ($x_b < $bbox_ref_x) $bbox_ref_x = $x_b;
elseif ($bbox_max_x < $x_b) $bbox_max_x = $x_b;
$y_b = $c[$i+1];
if ($y_b < $bbox_ref_y) $bbox_ref_y = $y_b;
elseif ($bbox_max_y < $y_b) $bbox_max_y = $y_b;
}
$bbox_width = $bbox_max_x - $bbox_ref_x;
$bbox_height = $bbox_max_y - $bbox_ref_y;
if (!$draw_it) {
// Return the bounding box, rounded up (so it always contains the text):
return array((int)ceil($bbox_width), (int)ceil($bbox_height));
}
$interline_step = $font_height + $line_spacing; // Line-to-line step
// Calculate the offsets from the supplied reference point to the
// upper-left corner of the text.
// Start at the reference point at the upper left corner of the bounding
// box (bbox_ref_x, bbox_ref_y) then adjust it for the 9 point alignment.
// h,v_factor are 0,0 for top,left, .5,.5 for center,center, 1,1 for bottom,right.
// $off_x = $bbox_ref_x + $bbox_width * $h_factor - $x;
// $off_y = $bbox_ref_y + $bbox_height * $v_factor - $y;
// Then use that offset to calculate back to the supplied reference point x, y
// to get the text base point.
// $qx = $x - $off_x;
// $qy = $y - $off_y;
// Reduces to:
$qx = 2 * $x - $bbox_ref_x - $bbox_width * $h_factor;
$qy = 2 * $y - $bbox_ref_y - $bbox_height * $v_factor;
// Check for debug callback. Don't calculate bounding box unless it is wanted.
if ($this->GetCallback('debug_textbox')) {
// Calculate the orthogonal bounding box coordinates for debug testing.
// qx, qy is upper left corner relative to the text.
// Calculate px,py: upper left corner (absolute) of the bounding box.
// There are 4 equation sets for this, depending on the quadrant:
if ($sin_t > 0) {
if ($cos_t > 0) {
// Quadrant: 0d - 90d:
$px = $qx; $py = $qy - $total_width * $sin_t;
} else {
// Quadrant: 90d - 180d:
$px = $qx + $total_width * $cos_t; $py = $qy - $bbox_height;
}
} else {
if ($cos_t < 0) {
// Quadrant: 180d - 270d:
$px = $qx - $bbox_width; $py = $qy + $total_height * $cos_t;
} else {
// Quadrant: 270d - 360d:
$px = $qx + $total_height * $sin_t; $py = $qy;
}
}
$this->DoCallback('debug_textbox', $px, $py, $bbox_width, $bbox_height);
}
// Since alignment is applied after rotation, which parameter is used
// to control alignment of each line within the text box varies with
// the angle.
// Angle (degrees): Line alignment controlled by:
// -45 < angle <= 45 h_align
// 45 < angle <= 135 reversed v_align
// 135 < angle <= 225 reversed h_align
// 225 < angle <= 315 v_align
if ($cos_t >= $sin_t) {
if ($cos_t >= -$sin_t) $line_align_factor = $h_factor;
else $line_align_factor = $v_factor;
} else {
if ($cos_t >= -$sin_t) $line_align_factor = 1-$v_factor;
else $line_align_factor = 1-$h_factor;
}
// Now we have the start point, spacing and in-line alignment factor.
// We are finally ready to start drawing the text, line by line.
for ($i = 0; $i < $n_lines; $i++) {
// For drawing TTF text, the reference point is the left edge of the
// text baseline (not the lower left corner of the bounding box).
// The following also adjusts for horizontal (relative to
// the text) alignment of the current line within the box.
// What is happening is rotation of this vector by the text angle:
// (x = (total_width - line_width) * factor, y = font_height)
$width_factor = ($total_width - $line_widths[$i]) * $line_align_factor;
$rx = $qx + $r00 * $width_factor + $r01 * $font_height;
$ry = $qy + $r10 * $width_factor + $r11 * $font_height;
// Finally, draw the text:
ImageTTFText($this->img, $font_size, $angle, $rx, $ry, $color, $font_file, $lines[$i]);
// Step to position of next line.
// This is a rotation of (x=0,y=height+line_spacing) by $angle:
$qx += $r01 * $interline_step;
$qy += $r11 * $interline_step;
}
return TRUE;
}
/*
* ProcessText() - Wrapper for ProcessTextTTF() and ProcessTextGD(). See notes above.
* This is intended for use from within PHPlot only, and only by DrawText() and SizeText().
* $draw_it : True to draw the text, False to just return the orthogonal width and height.
* $font : PHPlot font array, or NULL or empty string to use 'generic'
* $angle : Text angle in degrees
* $x, $y : Reference point for the text (ignored if !$draw_it)
* $color : GD color index to use for drawing the text (ignored if !$draw_it)
* $text : The text to draw or size. Put a newline between lines.
* $halign : Horizontal alignment: left, center, or right (ignored if !$draw_it)
* $valign : Vertical alignment: top, center, or bottom (ignored if !$draw_it)
* Note: Alignment is relative to the image, not the text.
* Returns: True, if drawing text, or an array of ($width, $height) if not.
*/
protected function ProcessText($draw_it, $font, $angle, $x, $y, $color, $text, $halign, $valign)
{
// Empty text case:
if ($text === '') {
if ($draw_it) return TRUE;
return array(0, 0);
}
// Calculate width and height offset factors using the alignment args:
if ($valign == 'top') $v_factor = 0;
elseif ($valign == 'center') $v_factor = 0.5;
else $v_factor = 1.0; // 'bottom'
if ($halign == 'left') $h_factor = 0;
elseif ($halign == 'center') $h_factor = 0.5;
else $h_factor = 1.0; // 'right'
// Apply a default font. This is mostly for external (callback) users.
if (empty($font)) $font = $this->fonts['generic'];
if ($font['ttf']) {
return $this->ProcessTextTTF($draw_it, $font, $angle, $x, $y, $color, $text,
$h_factor, $v_factor);
}
return $this->ProcessTextGD($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor);
}
/*
* Draws a block of text. See comments above before ProcessText().
* $which_font : PHPlot font array, or NULL or empty string to use 'generic'
* $which_angle : Text angle in degrees
* $which_xpos, $which_ypos: Reference point for the text
* $which_color : GD color index to use for drawing the text
* $which_text : The text to draw, with newlines (\n) between lines.
* $which_halign : Horizontal (relative to the image) alignment: left, center, or right.
* $which_valign : Vertical (relative to the image) alignment: top, center, or bottom.
* Note: This function should be considered 'protected', and is not documented for public use.
*/
function DrawText($which_font, $which_angle, $which_xpos, $which_ypos, $which_color, $which_text,
$which_halign = 'left', $which_valign = 'bottom')
{
return $this->ProcessText(TRUE,
$which_font, $which_angle, $which_xpos, $which_ypos,
$which_color, $which_text, $which_halign, $which_valign);
}
/*
* Returns the size of block of text. This is the orthogonal width and height of a bounding
* box aligned with the X and Y axes of the text. Only for angle=0 is this the actual
* width and height of the text block, but for any angle it is the amount of space needed
* to contain the text.
* $which_font : PHPlot font array, or NULL or empty string to use 'generic'
* $which_angle : Text angle in degrees
* $which_text : The text to draw, with newlines (\n) between lines.
* Returns a two element array with: $width, $height.
* This is just a wrapper for ProcessText() - see above.
* Note: This function should be considered 'protected', and is not documented for public use.
*/
function SizeText($which_font, $which_angle, $which_text)
{
// Color, position, and alignment are not used when calculating the size.
return $this->ProcessText(FALSE,
$which_font, $which_angle, 0, 0, 1, $which_text, '', '');
}
/////////////////////////////////////////////
/////////// INPUT / OUTPUT CONTROL
/////////////////////////////////////////////
/*
* Sets output file format to $format (jpg, png, ...)
*/
function SetFileFormat($format)
{
$asked = $this->CheckOption($format, 'jpg, png, gif, wbmp', __FUNCTION__);
if (!$asked) return FALSE;
switch ($asked) {
case 'jpg':
$format_test = IMG_JPG;
break;
case 'png':
$format_test = IMG_PNG;
break;
case 'gif':
$format_test = IMG_GIF;
break;
case 'wbmp':
$format_test = IMG_WBMP;
break;
}
if (!(imagetypes() & $format_test)) {
return $this->PrintError("SetFileFormat(): File format '$format' not supported");
}
$this->file_format = $asked;
return TRUE;
}
/*
* Selects an input file to be used as graph background and scales or tiles this image
* to fit the sizes.
* $input_file : Path to the file to be used (jpeg, png and gif accepted)
* $mode : 'centeredtile', 'tile', or 'scale' (the image to the graph's size)
*/
function SetBgImage($input_file, $mode='centeredtile')
{
$this->bgmode = $this->CheckOption($mode, 'tile, centeredtile, scale', __FUNCTION__);
$this->bgimg = $input_file;
return (boolean)$this->bgmode;
}
/*
* Selects an input file to be used as plot area background and scales or tiles this image
* to fit the sizes.
* $input_file : Path to the file to be used (jpeg, png and gif accepted)
* $mode : 'centeredtile', 'tile', or 'scale' (the image to the graph's size)
*/
function SetPlotAreaBgImage($input_file, $mode='tile')
{
$this->plotbgmode = $this->CheckOption($mode, 'tile, centeredtile, scale', __FUNCTION__);
$this->plotbgimg = $input_file;
return (boolean)$this->plotbgmode;
}
/*
* Sets the name of the file to be used as output file.
*/
function SetOutputFile($which_output_file)
{
$this->output_file = $which_output_file;
return TRUE;
}
/*
* Sets the output image as 'inline', that is: no Content-Type headers are sent
* to the browser. Needed if you want to embed the images.
*/
function SetIsInline($which_ii)
{
$this->is_inline = (bool)$which_ii;
return TRUE;
}
/*
* Performs the actual outputting of the generated graph.
*/
function PrintImage()
{
// Browser cache stuff submitted by Thiemo Nagel
if ( (! $this->browser_cache) && (! $this->is_inline)) {
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
}
switch ($this->file_format) {
case 'png':
$mime_type = 'image/png';
$output_f = 'imagepng';
break;
case 'jpg':
$mime_type = 'image/jpeg';
$output_f = 'imagejpeg';
break;
case 'gif':
$mime_type = 'image/gif';
$output_f = 'imagegif';
break;
case 'wbmp':
$mime_type = 'image/wbmp';
$output_f = 'imagewbmp';
break;
default:
return $this->PrintError('PrintImage(): Please select an image type!');
}
if (!$this->is_inline) {
Header("Content-type: $mime_type");
}
if ($this->is_inline && $this->output_file != '') {
$output_f($this->img, $this->output_file);
} else {
$output_f($this->img);
}
return TRUE;
}
/*
* Error handling for 'fatal' errors:
* $error_message Text of the error message
* Standard output from PHPlot is expected to be an image file, such as
* when handling an <img> tag browser request. So it is not permitted to
* output text to standard output. (You should have display_errors=off)
* Here is how PHPlot handles fatal errors:
* + Write the error message into an image, and output the image.
* + If no image can be output, write nothing and produce an HTTP
* error header.
* + Trigger a user-level error containing the error message.
* If no error handler was set up, the script will log the
* error and exit with non-zero status.
*
* PrintError() and DrawError() are now equivalent. Both are provided for
* compatibility. (In earlier releases, PrintError sent the message to
* stdout only, and DrawError sent it in an image only.)
*
* This function does not return, unless the calling script has set up
* an error handler which does not exit. In that case, PrintError will
* return False. But not all of PHPlot will handle this correctly, so
* it is probably a bad idea for an error handler to return.
*/
protected function PrintError($error_message)
{
// Be sure not to loop recursively, e.g. PrintError - PrintImage - PrintError.
if (isset($this->in_error)) return FALSE;
$this->in_error = TRUE;
// Output an image containing the error message:
if (!empty($this->img)) {
$ypos = $this->image_height/2;
$xpos = $this->image_width/2;
$bgcolor = ImageColorResolve($this->img, 255, 255, 255);
$fgcolor = ImageColorResolve($this->img, 0, 0, 0);
ImageFilledRectangle($this->img, 0, 0, $this->image_width, $this->image_height, $bgcolor);
// Switch to built-in fonts, in case of error with TrueType fonts:
$this->SetUseTTF(FALSE);
$this->DrawText($this->fonts['generic'], 0, $xpos, $ypos, $fgcolor,
wordwrap($error_message), 'center', 'center');
$this->PrintImage();
} elseif (! $this->is_inline) {
Header('HTTP/1.0 500 Internal Server Error');
}
trigger_error($error_message, E_USER_ERROR);
unset($this->in_error);
return FALSE; // In case error handler returns, rather than doing exit().
}
/*
* Display an error message and exit.
* This is provided for backward compatibility only. Use PrintError() instead.
* $error_message Text of the error message
* $where_x, $where_y Ignored, provided for compatibility.
*/
protected function DrawError($error_message, $where_x = NULL, $where_y = NULL)
{
return $this->PrintError($error_message);
}
/////////////////////////////////////////////
/////////// LABELS
/////////////////////////////////////////////
/*
* Sets position for X data labels.
* For vertical plots, these are X axis data labels, showing label strings from the data array.
* Accepted positions are: plotdown, plotup, both, none.
* For horizontal plots (bar, stackedbar only), these are X data value labels, show the data values.
* Accepted positions are: plotin, plotstack, none.
*/
function SetXDataLabelPos($which_xdlp)
{
$which_xdlp = $this->CheckOption($which_xdlp, 'plotdown, plotup, both, none, plotin, plotstack',
__FUNCTION__);
if (!$which_xdlp) return FALSE;
$this->x_data_label_pos = $which_xdlp;
return TRUE;
}
/*
* Sets position for Y data labels.
* For vertical plots (where available), these are Y data value labels, showing the data values.
* Accepted positions are: plotin, plotstack, none.
* For horizontal plots, these are Y axis data labels, showing label strings from the data array.
* Accepted positions are: plotleft, plotright, both, none.
*/
function SetYDataLabelPos($which_ydlp)
{
$which_ydlp = $this->CheckOption($which_ydlp, 'plotleft, plotright, both, none, plotin, plotstack',
__FUNCTION__);
if (!$which_ydlp) return FALSE;
$this->y_data_label_pos = $which_ydlp;
return TRUE;
}
/*
* Set position for X tick labels.
*/
function SetXTickLabelPos($which_xtlp)
{
$which_xtlp = $this->CheckOption($which_xtlp, 'plotdown, plotup, both, xaxis, none',
__FUNCTION__);
if (!$which_xtlp) return FALSE;
$this->x_tick_label_pos = $which_xtlp;
return TRUE;
}
/*
* Set position for Y tick labels.
*/
function SetYTickLabelPos($which_ytlp)
{
$which_ytlp = $this->CheckOption($which_ytlp, 'plotleft, plotright, both, yaxis, none',
__FUNCTION__);
if (!$which_ytlp) return FALSE;
$this->y_tick_label_pos = $which_ytlp;
return TRUE;
}
/*
* Set formatting type for tick and data labels on X or Y axis.
* This implements the 4 functions Set[XY]LabelType() and Set[XY]DataLabelType().
* $mode : 'x', 'y', 'xd', or 'yd' - which type of label to configure.
* 'x' and 'y' set the type for tick labels, and the default type for data labels
* if they are not separately configured. 'xd' and 'yd' set the type for data labels.
* $args : Variable arguments, passed as an array.
* [0] = $type (required) : Label type. 'data', 'time', 'printf', or 'custom'.
* For type 'data':
* [1] = $precision (optional). Numeric precision. Can also be set by SetPrecision[XY]().
* [2] = $prefix (optional) - prefix string for labels.
* [3] = $suffix (optional) - suffix string for labels. This replaces data_units_text.
* For type 'time':
* [1] = $format for strftime (optional). Can also be set by Set[XY]TimeFormat().
* For type 'printf':
* [1] = $format (optional) for sprintf.
* For type 'custom':
* [1] = $callback (required) - Custom function or array of (instance,method) to call.
* [2] = $argument (optional) - Pass-through argument for the formatting function.
*/
protected function SetLabelType($mode, $args)
{
if (!$this->CheckOption($mode, 'x, y, xd, yd', __FUNCTION__))
return FALSE;
$type = isset($args[0]) ? $args[0] : '';
$format =& $this->label_format[$mode]; // Shorthand reference to format storage variables
switch ($type) {
case 'data':
if (isset($args[1]))
$format['precision'] = $args[1];
elseif (!isset($format['precision']))
$format['precision'] = 1;
$format['prefix'] = isset($args[2]) ? $args[2] : '';
$format['suffix'] = isset($args[3]) ? $args[3] : '';
break;
case 'time':
if (isset($args[1]))
$format['time_format'] = $args[1];
elseif (!isset($format['time_format']))
$format['time_format'] = '%H:%M:%S';
break;
case 'printf':
if (isset($args[1]))
$format['printf_format'] = $args[1];
elseif (!isset($format['printf_format']))
$format['printf_format'] = '%e';
break;
case 'custom':
if (isset($args[1])) {
$format['custom_callback'] = $args[1];
$format['custom_arg'] = isset($args[2]) ? $args[2] : NULL;
} else {
$type = ''; // Error, 'custom' without a function, set to no-format mode.
}
break;
case '':
case 'title': // Retained for backwards compatibility?
break;
default:
$this->CheckOption($type, 'data, time, printf, custom', __FUNCTION__);
$type = '';
}
$format['type'] = $type;
return (boolean)$type;
}
/*
* Select label formating for X tick labels, and for X data labels
* (unless SetXDataLabelType was called).
* See SetLabelType() for details.
*/
function SetXLabelType() // Variable arguments: $type, ...
{
$args = func_get_args();
return $this->SetLabelType('x', $args);
}
/*
* Select label formatting for X data labels, overriding SetXLabelType.
*/
function SetXDataLabelType() // Variable arguments: $type, ...
{
$args = func_get_args();
return $this->SetLabelType('xd', $args);
}
/*
* Select label formating for Y tick labels, and for Y data labels
* (unless SetYDataLabelType was called).
* See SetLabelType() for details.
*/
function SetYLabelType() // Variable arguments: $type, ...
{
$args = func_get_args();
return $this->SetLabelType('y', $args);
}
/*
* Select label formatting for Y data labels, overriding SetYLabelType.
*/
function SetYDataLabelType() // Variable arguments: $type, ...
{
$args = func_get_args();
return $this->SetLabelType('yd', $args);
}
/*
* Set the date/time format code for X labels.
* Note: Use of SetXLabelType('time', $which_xtf) is preferred, because
* SetXTimeFormat does not also enable date/time formatting.
*/
function SetXTimeFormat($which_xtf)
{
$this->label_format['x']['time_format'] = $which_xtf;
return TRUE;
}
/*
* Set the date/time format code for Y labels.
* Note: Use of SetYLabelType('time', $which_ytf) is preferred, because
* SetYTimeFormat does not also enable date/time formatting.
*/
function SetYTimeFormat($which_ytf)
{
$this->label_format['y']['time_format'] = $which_ytf;
return TRUE;
}
/*
* Set number format parameters (decimal point and thousands separator) for
* 'data' mode label formatting, overriding the locale-defaults.
*/
function SetNumberFormat($decimal_point, $thousands_sep)
{
$this->decimal_point = $decimal_point;
$this->thousands_sep = $thousands_sep;
return TRUE;
}
/*
* Set the text angle for X labels to $which_xla degrees.
*/
function SetXLabelAngle($which_xla)
{
$this->x_label_angle = $which_xla;
return TRUE;
}
/*
* Set the text angle for Y labels to $which_xla degrees.
*/
function SetYLabelAngle($which_yla)
{
$this->y_label_angle = $which_yla;
return TRUE;
}
/*
* Set the angle for X Data Labels to $which_xdla degrees.
* If not used, this defaults to the value set with SetXLabelAngle.
*/
function SetXDataLabelAngle($which_xdla)
{
$this->x_data_label_angle = $which_xdla;
return TRUE;
}
/*
* Set the angle for Y Data Labels to $which_ydla degrees.
* If not used, this defaults to zero (unlike X data labels).
*/
function SetYDataLabelAngle($which_ydla)
{
$this->y_data_label_angle = $which_ydla;
return TRUE;
}
/////////////////////////////////////////////
/////////// MISC
/////////////////////////////////////////////
/*
* Checks the validity of an option.
* $which_opt String to check, such as the provided value of a function argument.
* $which_acc String of accepted choices. Must be lower-case, and separated
* by exactly ', ' (comma, space).
* $which_func Name of the calling function, for error messages.
* Returns the supplied option value, downcased and trimmed, if it is valid.
* Reports an error if the supplied option is not valid.
*/
protected function CheckOption($which_opt, $which_acc, $which_func)
{
$asked = strtolower(trim($which_opt));
// Look for the supplied value in a comma/space separated list.
if (strpos(", $which_acc,", ", $asked,") !== FALSE)
return $asked;
$this->PrintError("$which_func(): '$which_opt' not in available choices: '$which_acc'.");
return NULL;
}
/*
* Checks the validity of an array of options.
* $opt Array or string to check.
* $acc String of accepted choices. Must be lower-case, and separated
* by exactly ', ' (comma, space).
* $func Name of the calling function, for error messages.
* Returns a array option value(s), downcased and trimmed, if all entries in $opt are valid.
* Reports an error if any supplied option is not valid. Returns NULL if the error handler returns.
*/
protected function CheckOptionArray($opt, $acc, $func)
{
$opt_array = (array)$opt;
$result = array();
foreach ($opt_array as $option) {
$choice = $this->CheckOption($option, $acc, $func);
if (is_null($choice)) return NULL; // In case CheckOption error handler returns
$result[] = $choice;
}
return $result;
}
/*
* Check compatibility of a plot type and data type.
* This is called by the plot-type-specific drawing functions.
* $valid_types String of supported data types. Multiple values must be
* separated by exactly ', ' (comma, space).
* Returns True if the type is valid for this plot.
* Reports an error if the data type is not value. If the error is handled and
* the handler returns, this returns False.
*/
protected function CheckDataType($valid_types)
{
if (strpos(", $valid_types,", ", $this->data_type,") !== FALSE)
return TRUE;
$this->PrintError("Data type '$this->data_type' is not valid for '$this->plot_type' plots."
. " Supported data type(s): '$valid_types'");
return FALSE;
}
/*
* Decode the data type into variables used to determine how to process a data array.
* The goal is minimize which functions understand the actual data type values.
* This sets the datatype_* variables for use by other member functions.
* datatype_implied : Implicit independent variable (e.g. text-data vs data-data)
* datatype_swapped_xy : Swapped X/Y (horizontal plot)
* datatype_error_bars : Data array has error bar data
* datatype_pie_single : Data array is for a pie chart with one row per slice
*/
protected function DecodeDataType()
{
$dt = $this->data_type;
$this->datatype_implied = ($dt == 'text-data' || $dt == 'text-data-single'
|| $dt == 'text-data-yx');
$this->datatype_swapped_xy = ($dt == 'text-data-yx' || $dt == 'data-data-yx');
$this->datatype_error_bars = ($dt == 'data-data-error');
$this->datatype_pie_single = ($dt == 'text-data-single');
}
/*
* Make sure the data array is populated, and calculate the number of columns.
* This is called from DrawGraph. Calculates data_columns, which is the
* maximum number of dependent variable values (usually Y) in the data array rows.
* (For pie charts, this is the number of slices.)
* This depends on the data_type, unlike records_per_group (which was
* previously used to pad style arrays, but is not accurate).
* Returns True if the data array is OK, else reports an error (and may return False).
* Note error messages refer to the caller, the public DrawGraph().
*/
protected function CheckDataArray()
{
// Test for missing image, which really should never happen.
if (!$this->img) {
return $this->PrintError('DrawGraph(): No image resource allocated');
}
// Test for missing or empty data array:
if (empty($this->data) || !is_array($this->data)) {
return $this->PrintError("DrawGraph(): No data array");
}
if ($this->total_records == 0) {
return $this->PrintError('DrawGraph(): Empty data set');
}
// Decode the data type into functional flags.
$this->DecodeDataType();
// Calculate the maximum number of dependent values per independent value
// (e.g. Y for each X), or the number of pie slices.
if ($this->datatype_pie_single) {
$this->data_columns = $this->num_data_rows; // Special case for 1 type of pie chart.
} else {
$skip = $this->datatype_implied ? 1 : 2; // Skip data label and independent variable if used
$this->data_columns = $this->records_per_group - $skip;
if ($this->datatype_error_bars) // Each Y has +err and -err along with it
$this->data_columns = (int)($this->data_columns / 3);
}
return TRUE;
}
/*
* Control headers for browser-side image caching.
* $which_browser_cache : True to allow browsers to cache the image.
*/
function SetBrowserCache($which_browser_cache)
{
$this->browser_cache = $which_browser_cache;
return TRUE;
}
/*
* Set whether DrawGraph automatically outputs the image too.
* $which_pi : True to have DrawGraph call PrintImage at the end.
*/
function SetPrintImage($which_pi)
{
$this->print_image = $which_pi;
return TRUE;
}
/*
* Set border for the plot area.
* Accepted values are: left, right, top, bottom, sides, none, full or an array of those.
*/
function SetPlotBorderType($pbt)
{
$this->plot_border_type = $this->CheckOptionArray($pbt, 'left, right, top, bottom, sides, none, full',
__FUNCTION__);
return !empty($this->plot_border_type);
}
/*
* Set border style for the image.
* Accepted values are: raised, plain, solid, none
* 'solid' is the same as 'plain' except it fixes the color (see DrawImageBorder)
*/
function SetImageBorderType($sibt)
{
$this->image_border_type = $this->CheckOption($sibt, 'raised, plain, solid, none', __FUNCTION__);
return (boolean)$this->image_border_type;
}
/*
* Set border width for the image to $width in pixels.
*/
function SetImageBorderWidth($width)
{
$this->image_border_width = $width;
return TRUE;
}
/*
* Enable or disable drawing of the plot area background color.
*/
function SetDrawPlotAreaBackground($dpab)
{
$this->draw_plot_area_background = (bool)$dpab;
return TRUE;
}
/*
* Enable or disable drawing of the X grid lines.
*/
function SetDrawXGrid($dxg)
{
$this->draw_x_grid = (bool)$dxg;
return TRUE;
}
/*
* Enable or disable drawing of the Y grid lines.
*/
function SetDrawYGrid($dyg)
{
$this->draw_y_grid = (bool)$dyg;
return TRUE;
}
/*
* Select dashed or solid grid lines.
* $ddg : True for dashed grid lines, false for solid grid lines.
*/
function SetDrawDashedGrid($ddg)
{
$this->dashed_grid = (bool)$ddg;
return TRUE;
}
/*
* Enable or disable drawing of X Data Label Lines.
*/
function SetDrawXDataLabelLines($dxdl)
{
$this->draw_x_data_label_lines = (bool)$dxdl;
return TRUE;
}
/*
* Set the main title text for the plot.
*/
function SetTitle($which_title)
{
$this->title_txt = $which_title;
return TRUE;
}
/*
* Set the X axis title and position.
*/
function SetXTitle($which_xtitle, $which_xpos = 'plotdown')
{
if ($which_xtitle == '')
$which_xpos = 'none';
$this->x_title_pos = $this->CheckOption($which_xpos, 'plotdown, plotup, both, none', __FUNCTION__);
if (!$this->x_title_pos) return FALSE;
$this->x_title_txt = $which_xtitle;
return TRUE;
}
/*
* Set the Y axis title and position.
*/
function SetYTitle($which_ytitle, $which_ypos = 'plotleft')
{
if ($which_ytitle == '')
$which_ypos = 'none';
$this->y_title_pos = $this->CheckOption($which_ypos, 'plotleft, plotright, both, none', __FUNCTION__);
if (!$this->y_title_pos) return FALSE;
$this->y_title_txt = $which_ytitle;
return TRUE;
}
/*
* Set the size of the drop shadow for bar and pie charts.
* $which_s : Size of the drop shadow in pixels.
*/
function SetShading($which_s)
{
$this->shading = (int)$which_s;
return TRUE;
}
/*
* Set the plot type (bars, points, ...)
*/
function SetPlotType($which_pt)
{
$avail_plot_types = implode(', ', array_keys(PHPlot::$plots)); // List of known plot types
$this->plot_type = $this->CheckOption($which_pt, $avail_plot_types, __FUNCTION__);
return (boolean)$this->plot_type;
}
/*
* Set the position of the X axis.
* $pos : Axis position in world coordinates (as an integer).
*/
function SetXAxisPosition($pos='')
{
$this->x_axis_position = ($pos === '') ? $pos : (int)$pos;
return TRUE;
}
/*
* Set the position of the Y axis.
* $pos : Axis position in world coordinates (as an integer).
*/
function SetYAxisPosition($pos='')
{
$this->y_axis_position = ($pos === '') ? $pos : (int)$pos;
return TRUE;
}
/*
* Enable or disable drawing of the X axis line.
* $draw : True to draw the axis (default if not called), False to suppress it.
* This controls drawing of the axis line only, and not the ticks, labels, or grid.
*/
function SetDrawXAxis($draw)
{
$this->suppress_x_axis = !$draw; // See DrawXAxis()
return TRUE;
}
/*
* Enable or disable drawing of the Y axis line.
* $draw : True to draw the axis (default if not called), False to suppress it.
* This controls drawing of the axis line only, and not the ticks, labels, or grid.
*/
function SetDrawYAxis($draw)
{
$this->suppress_y_axis = !$draw; // See DrawYAxis()
return TRUE;
}
/*
* Select linear or log scale for the X axis.
*/
function SetXScaleType($which_xst)
{
$this->xscale_type = $this->CheckOption($which_xst, 'linear, log', __FUNCTION__);
return (boolean)$this->xscale_type;
}
/*
* Select linear or log scale for the Y axis.
*/
function SetYScaleType($which_yst)
{
$this->yscale_type = $this->CheckOption($which_yst, 'linear, log', __FUNCTION__);
return (boolean)$this->yscale_type;
}
/*
* Set the precision for numerically formatted X labels.
* $which_prec : Number of digits to display.
* Note: This is equivalent to: SetXLabelType('data', $which_prec)
*/
function SetPrecisionX($which_prec)
{
return $this->SetXLabelType('data', $which_prec);
}
/*
* Set the precision for numerically formatted Y labels.
* $which_prec : Number of digits to display.
* Note: This is equivalent to: SetYLabelType('data', $which_prec)
*/
function SetPrecisionY($which_prec)
{
return $this->SetYLabelType('data', $which_prec);
}
/*
* Set the line width (in pixels) for error bars.
*/
function SetErrorBarLineWidth($which_seblw)
{
$this->error_bar_line_width = $which_seblw;
return TRUE;
}
/*
* Set the position for pie chart percentage labels.
* $which_blb : Real number between 0 and 1.
* Smaller values move the labels in towards the center.
*/
function SetLabelScalePosition($which_blp)
{
$this->label_scale_position = $which_blp;
return TRUE;
}
/*
* Set the size (in pixels) of the "T" in error bars.
*/
function SetErrorBarSize($which_ebs)
{
$this->error_bar_size = $which_ebs;
return TRUE;
}
/*
* Set the shape of the in error bars.
* $which_ebs : Error bar shape, 'tee' or 'line'.
*/
function SetErrorBarShape($which_ebs)
{
$this->error_bar_shape = $this->CheckOption($which_ebs, 'tee, line', __FUNCTION__);
return (boolean)$this->error_bar_shape;
}
/*
* Synchronize the point shape and point size arrays.
* This is called just before drawing any plot that needs 'points'.
*/
protected function CheckPointParams()
{
// Make both point_shapes and point_sizes the same size, by padding the smaller.
$ps = count($this->point_sizes);
$pt = count($this->point_shapes);
if ($ps < $pt) {
$this->pad_array($this->point_sizes, $pt);
$this->point_counts = $pt;
} elseif ($ps > $pt) {
$this->pad_array($this->point_shapes, $ps);
$this->point_counts = $ps;
} else {
$this->point_counts = $ps;
}
// Note: PHPlot used to check and adjust point_sizes to be an even number here,
// for all 'diamond' and 'triangle' shapes. The reason for this having been
// lost, and the current maintainer seeing no sense it doing this for only
// some shapes, the code has been removed. But see what DrawDot() does.
}
/*
* Set the point shape for each data set.
* $which_pt : Array (or single value) of valid point shapes. See also DrawDot() for valid shapes.
* The point shape and point sizes arrays are synchronized before drawing a graph
* that uses points. See CheckPointParams()
*/
function SetPointShapes($which_pt)
{
$this->point_shapes = $this->CheckOptionArray($which_pt, 'halfline, line, plus, cross, rect,'
. ' circle, dot, diamond, triangle, trianglemid, delta, yield, star, hourglass,'
. ' bowtie, target, box, home, up, down, none', __FUNCTION__);
return !empty($this->point_shapes);
}
/*
* Set the point size for point plots.
* $which_ps : Array (or single value) of point sizes in pixels.
* The point shape and point sizes arrays are synchronized before drawing a graph
* that uses points. See CheckPointParams()
*/
function SetPointSizes($which_ps)
{
if (is_array($which_ps)) {
// Use provided array:
$this->point_sizes = $which_ps;
} elseif (!is_null($which_ps)) {
// Make the single value into an array:
$this->point_sizes = array($which_ps);
}
return TRUE;
}
/*
* Sets whether lines should be broken at missing data.
* $bl : True to break the lines, false to connect around missing data.
* This only works with 'lines' and 'squared' plots.
*/
function SetDrawBrokenLines($bl)
{
$this->draw_broken_lines = (bool)$bl;
return TRUE;
}
/*
* Set the data type, which defines the structure of the data array
* text-data: ('label', y1, y2, y3, ...)
* text-data-single: ('label', data), for some pie charts.
* data-data: ('label', x, y1, y2, y3, ...)
* data-data-error: ('label', x1, y1, e1+, e2-, y2, e2+, e2-, y3, e3+, e3-, ...)
* data-data-yx: ('label', y, x1, x2, x3, ..)
* text-data-yx: ('label', x1, x2, x3, ...)
*/
function SetDataType($which_dt)
{
//The next four lines are for past compatibility.
if ($which_dt == 'text-linear') $which_dt = 'text-data';
elseif ($which_dt == 'linear-linear') $which_dt = 'data-data';
elseif ($which_dt == 'linear-linear-error') $which_dt = 'data-data-error';
elseif ($which_dt == 'text-data-pie') $which_dt = 'text-data-single';
$this->data_type = $this->CheckOption($which_dt, 'text-data, text-data-single, '.
'data-data, data-data-error, '.
'data-data-yx, text-data-yx',
__FUNCTION__);
return (boolean)$this->data_type;
}
/*
* Copy the array passed as data values. We convert to numerical indexes, for its
* use for (or while) loops, which sometimes are faster. Performance improvements
* vary from 28% in DrawLines() to 49% in DrawArea() for plot drawing functions.
*/
function SetDataValues($which_dv)
{
$this->num_data_rows = count($which_dv);
$this->total_records = 0;
$this->data = array();
$this->num_recs = array();
for ($i = 0; $i < $this->num_data_rows; $i++) {
$this->data[$i] = array_values($which_dv[$i]); // convert to numerical indices.
// Count size of each row, and total for the array.
$recs = count($this->data[$i]);
$this->total_records += $recs;
$this->num_recs[$i] = $recs;
}
// This is the size of the widest row in the data array
// Note records_per_group isn't used much anymore. See data_columns in CheckDataArray()
$this->records_per_group = max($this->num_recs);
return TRUE;
}
/*
* Pad styles arrays for later use by plot drawing functions:
* This removes the need for $max_data_colors, etc. and $color_index = $color_index % $max_data_colors
* in DrawBars(), DrawLines(), etc.
* The arrays are padded to data_columns which is the maximum number of data sets.
* See CheckDataArray() for the calculation.
*/
protected function PadArrays()
{
$this->pad_array($this->line_widths, $this->data_columns);
$this->pad_array($this->line_styles, $this->data_columns);
$this->pad_array($this->ndx_data_colors, $this->data_columns);
$this->pad_array($this->ndx_data_border_colors, $this->data_columns);
// Other data color arrays are handled in the Need*Colors() functions.
return TRUE;
}
/*
* Pads an array with itself. This only works on 0-based sequential integer indexed arrays.
* $arr : The array (or scalar) to pad. This argument is modified.
* $size : Minimum size of the resulting array.
* If $arr is a scalar, it will be converted first to a single element array.
* If $arr has at least $size elements, it is unchanged.
* Otherwise, append elements of $arr to itself until it reaches $size elements.
*/
protected function pad_array(&$arr, $size)
{
if (! is_array($arr)) {
$arr = array($arr);
}
$n = count($arr);
$base = 0;
while ($n < $size) $arr[$n++] = $arr[$base++];
}
/*
* Format a floating-point number.
* $number : A floating point number to format
* $decimals : Number of decimal places in the result
* Returns the formatted result.
* This is like PHP's number_format, but uses class variables for separators.
* The separators will default to locale-specific values, if available.
*/
protected function number_format($number, $decimals=0)
{
if (!isset($this->decimal_point) || !isset($this->thousands_sep)) {
// Load locale-specific values from environment, unless disabled:
if (empty($this->locale_override))
@setlocale(LC_ALL, '');
// Fetch locale settings:
$locale = @localeconv();
if (isset($locale['decimal_point']) && isset($locale['thousands_sep'])) {
$this->decimal_point = $locale['decimal_point'];
$this->thousands_sep = $locale['thousands_sep'];
} else {
// Locale information not available.
$this->decimal_point = '.';
$this->thousands_sep = ',';
}
}
return number_format($number, $decimals, $this->decimal_point, $this->thousands_sep);
}
/*
* Register a callback (hook) function
* $reason : A pre-defined name where a callback can be defined.
* $function : The name of a function to register for callback, or an instance/method
* pair in an array (see 'callbacks' in the PHP reference manual).
* $arg : Optional argument to supply to the callback function when it is triggered.
* (Often called "clientData")
* Returns True if the callback reason is valid, else False.
*/
function SetCallback($reason, $function, $arg = NULL)
{
// Use array_key_exists because valid reason keys have NULL as value.
if (!array_key_exists($reason, $this->callbacks))
return FALSE;
$this->callbacks[$reason] = array($function, $arg);
return TRUE;
}
/*
* Return the name of a function registered for callback. See SetCallBack.
* $reason - A pre-defined name where a callback can be defined.
* Returns the current callback function (name or array) for the given reason,
* or False if there was no active callback or the reason is not valid.
* Note you can safely test the return value with a simple 'if', as
* no valid function name evaluates to false.
*/
function GetCallback($reason)
{
if (isset($this->callbacks[$reason]))
return $this->callbacks[$reason][0];
return FALSE;
}
/*
* Un-register (remove) a function registered for callback.
* $reason - A pre-defined name where a callback can be defined.
* Returns: True if it was a valid callback reason, else False.
* Note: Returns True whether or not there was a callback registered.
*/
function RemoveCallback($reason)
{
if (!array_key_exists($reason, $this->callbacks))
return FALSE;
$this->callbacks[$reason] = NULL;
return TRUE;
}
/*
* Invoke a callback, if one is registered.
* Accepts a variable number of arguments >= 1:
* $reason : A string naming the callback.
* ... : Zero or more additional arguments to be passed to the
* callback function, after the passthru argument:
* callback_function($image, $passthru, ...)
* Returns: whatever value (if any) was returned by the callback.
*/
protected function DoCallback() // Note: Variable arguments
{
$args = func_get_args();
$reason = $args[0];
if (!isset($this->callbacks[$reason]))
return;
list($function, $args[0]) = $this->callbacks[$reason];
array_unshift($args, $this->img);
// Now args[] looks like: img, passthru, extra args...
return call_user_func_array($function, $args);
}
/*
* Allocate colors for the plot.
* This is called by DrawGraph to allocate the colors needed for the plot. Each selectable
* color has already been validated, parsed into an array (r,g,b,a), and stored into a member
* variable. Now the GD color indexes are assigned and stored into the ndx_*_color variables.
* This is deferred here to avoid allocating unneeded colors and to avoid order dependencies,
* especially with the transparent color.
*
* For drawing data elements, only the main data colors and border colors are allocated here.
* Dark colors and error bar colors are allocated by Need*Color() functions.
* (Data border colors default to just black, so there is no cost to always allocating.)
*
* Data color allocation works as follows. If there is a data_color callback, then allocate all
* defined data colors (because the callback can use them however it wants). Otherwise, only allocate
* the number of colors that will be used. This is the larger of the number of data sets and the
* number of legend lines.
*/
protected function SetColorIndexes()
{
$this->ndx_bg_color = $this->GetColorIndex($this->bg_color); // Background first
$this->ndx_plot_bg_color = $this->GetColorIndex($this->plot_bg_color);
if ($this->image_border_type != 'none') {
$this->ndx_i_border = $this->GetColorIndex($this->i_border);
$this->ndx_i_border_dark = $this->GetDarkColorIndex($this->i_border);
}
// Handle defaults for X and Y title colors.
$this->ndx_title_color = $this->GetColorIndex($this->title_color);
if (empty($this->x_title_color)) {
$this->ndx_x_title_color = $this->ndx_title_color;
} else {
$this->ndx_x_title_color = $this->GetColorIndex($this->x_title_color);
}
if (empty($this->y_title_color)) {
$this->ndx_y_title_color = $this->ndx_title_color;
} else {
$this->ndx_y_title_color = $this->GetColorIndex($this->y_title_color);
}
$this->ndx_text_color = $this->GetColorIndex($this->text_color);
$this->ndx_grid_color = $this->GetColorIndex($this->grid_color);
$this->ndx_light_grid_color = $this->GetColorIndex($this->light_grid_color);
$this->ndx_tick_color = $this->GetColorIndex($this->tick_color);
// Maximum number of data & border colors to allocate:
if ($this->GetCallback('data_color')) {
$n_data = count($this->data_colors); // Need all of them
$n_border = count($this->data_border_colors);
} else {
$n_data = max($this->data_columns, empty($this->legend) ? 0 : count($this->legend));
$n_border = $n_data; // One border color per data color
}
// Allocate main data colors. For other colors used for data, see the functions which follow.
$this->ndx_data_colors = $this->GetColorIndexArray($this->data_colors, $n_data);
$this->ndx_data_border_colors = $this->GetColorIndexArray($this->data_border_colors, $n_border);
// Set up a color as transparent, if SetTransparentColor was used.
if (!empty($this->transparent_color)) {
imagecolortransparent($this->img, $this->GetColorIndex($this->transparent_color));
}
}
/*
* Allocate dark-shade data colors. Called if needed by graph drawing functions.
*/
protected function NeedDataDarkColors()
{
// This duplicates the calculation in SetColorIndexes() for number of data colors to allocate.
if ($this->GetCallback('data_color')) {
$n_data = count($this->data_colors);
} else {
$n_data = max($this->data_columns, empty($this->legend) ? 0 : count($this->legend));
}
$this->ndx_data_dark_colors = $this->GetDarkColorIndexArray($this->data_colors, $n_data);
$this->pad_array($this->ndx_data_dark_colors, $this->data_columns);
}
/*
* Allocate error bar colors. Called if needed by graph drawing functions.
*/
protected function NeedErrorBarColors()
{
// This is similar to the calculation in SetColorIndexes() for number of data colors to allocate.
if ($this->GetCallback('data_color')) {
$n_err = count($this->error_bar_colors);
} else {
$n_err = max($this->data_columns, empty($this->legend) ? 0 : count($this->legend));
}
$this->ndx_error_bar_colors = $this->GetColorIndexArray($this->error_bar_colors, $n_err);
$this->pad_array($this->ndx_error_bar_colors, $this->data_columns);
}
/*
* Determine if, and where, to draw Data Value Labels.
* $label_control : Label position control. Either x_data_label_pos or y_data_label_pos.
* &$x_adj, &$y_adj : Returns X,Y adjustments (offset in pixels) to the text position.
* &$h_align, &$v_align : Returns horizontal and vertical alignment for the label.
* The above 4 argument values should be passed to DrawDataValueLabel()
* Returns True if data value labels should be drawn (based on $label_control), else False.
* This is used for plot types other than bars/stackedbars (which have their own way of doing it).
* It uses two member variables (unset by default): data_value_label_angle and data_value_label_distance
* to define the vector to the label. Default is 90 degrees at 5 pixels.
*/
protected function CheckDataValueLabels($label_control, &$x_adj, &$y_adj, &$h_align, &$v_align)
{
if ($label_control != 'plotin')
return FALSE; // No data value labels
$angle = deg2rad(isset($this->data_value_label_angle) ? $this->data_value_label_angle : 90);
$radius = isset($this->data_value_label_distance) ? $this->data_value_label_distance : 5;
$cos = cos($angle);
$sin = sin($angle);
$x_adj = (int)($radius * $cos);
$y_adj = -(int)($radius * $sin); // Y is reversed in device coordinates
// Choose from 8 (not 9, center/center can't happen) text alignments based on angle:
if ($sin >= 0.383) $v_align = 'bottom'; // 0.383 = sin(360deg / 16)
elseif ($sin >= -0.383) $v_align = 'center';
else $v_align = 'top';
if ($cos >= 0.383) $h_align = 'left';
elseif ($cos >= -0.383) $h_align = 'center';
else $h_align = 'right';
return TRUE;
}
//////////////////////////////////////////////////////////
/////////// DATA ANALYSIS, SCALING AND TRANSLATION
//////////////////////////////////////////////////////////
/*
* Analyzes the data array and calculates the minimum and maximum values.
* In this function, IV refers to the independent variable, and DV the dependent variable.
* For most plots, IV is X and DV is Y. For swapped X/Y plots, IV is Y and DV is X.
* At the end of the function, IV and DV ranges get assigned into X or Y.
*
* The data type mostly determines the data array structure, but some plot types do special
* things such as sum the values in a row. This information is in the plots[] array.
*
* This calculates min_x, max_x, min_y, and max_y. It also calculates two arrays
* data_min[] and data_max[] with per-row min and max values. These are used for
* data label lines. For normal (unswapped) data, these are the Y range for each X.
* For swapped X/Y data, they are the X range for each Y.
*/
protected function FindDataLimits()
{
// Does this plot type need special processing of the data values?
$sum_vals = !empty(PHPlot::$plots[$this->plot_type]['sum_vals']); // Add up values in each row
$abs_vals = !empty(PHPlot::$plots[$this->plot_type]['abs_vals']); // Take absolute values
// These need to be initialized in case there are multiple plots and missing data points.
$this->data_min = array();
$this->data_max = array();
// Independent values are in the data array or assumed?
if ($this->datatype_implied) {
$all_iv = array(0, $this->num_data_rows - 1);
} else {
$all_iv = array();
}
// Process all rows of data:
for ($i = 0; $i < $this->num_data_rows; $i++) {
$n_vals = $this->num_recs[$i];
$j = 1; // Skips label at [0]
if (!$this->datatype_implied) {
$all_iv[] = (double)$this->data[$i][$j++];
}
if ($sum_vals) {
$all_dv = array(0, 0); // One limit is 0, other calculated below
} else {
$all_dv = array();
}
while ($j < $n_vals) {
if (is_numeric($this->data[$i][$j])) {
$val = (double)$this->data[$i][$j++];
if ($this->datatype_error_bars) {
$all_dv[] = $val + (double)$this->data[$i][$j++];
$all_dv[] = $val - (double)$this->data[$i][$j++];
} else {
if ($abs_vals) {
$val = abs($val); // Use absolute values
}
if ($sum_vals) {
$all_dv[1] += $val; // Sum of values
} else {
$all_dv[] = $val; // List of all values
}
}
} else { // Missing DV value
$j++;
if ($this->datatype_error_bars) $j += 2;
}
}
if (!empty($all_dv)) {
$this->data_min[$i] = min($all_dv); // Store per-row DV range
$this->data_max[$i] = max($all_dv);
}
}
if ($this->datatype_swapped_xy) {
// Assign min and max for swapped X/Y plots: IV=Y and DV=X
$this->min_y = min($all_iv);
$this->max_y = max($all_iv);
if (empty($this->data_min)) { // Guard against regressive case: No X at all
$this->min_x = 0;
$this->max_x = 0;
} else {
$this->min_x = min($this->data_min); // Store global X range
$this->max_x = max($this->data_max);
}
} else {
// Assign min and max for normal plots: IV=X and DV=Y
$this->min_x = min($all_iv);
$this->max_x = max($all_iv);
if (empty($this->data_min)) { // Guard against regressive case: No Y at all
$this->min_y = 0;
$this->max_y = 0;
} else {
$this->min_y = min($this->data_min); // Store global Y range
$this->max_y = max($this->data_max);
}
}
if ($this->GetCallback('debug_scale')) {
$this->DoCallback('debug_scale', __FUNCTION__, array(
'min_x' => $this->min_x, 'min_y' => $this->min_y,
'max_x' => $this->max_x, 'max_y' => $this->max_y));
}
return TRUE;
}
/*
* Calculates image margins on the fly from title positions and sizes,
* and tick labels positions and sizes.
*
* A picture of the locations of elements and spacing can be found in the
* PHPlot Reference Manual.
*
* Calculates the following (class variables unless noted):
*
* Plot area margins (see note below):
* y_top_margin
* y_bot_margin
* x_left_margin
* x_right_margin
*
* Title sizes (these are now local, not class variables, since they are not used elsewhere):
* title_height : Height of main title
* x_title_height : Height of X axis title, 0 if no X title
* y_title_width : Width of Y axis title, 0 if no Y title
*
* Tick/Data label offsets, relative to plot_area:
* x_label_top_offset, x_label_bot_offset, x_label_axis_offset
* y_label_left_offset, y_label_right_offset, y_label_axis_offset
*
* Title offsets, relative to plot area:
* x_title_top_offset, x_title_bot_offset
* y_title_left_offset, y_title_left_offset
* title_offset (for main title, relative to image edge)
*
* Note: The margins are calculated, but not stored, if margins or plot area were
* set by the user with SetPlotAreaPixels or SetMarginsPixels. The margin
* calculation is mixed in with the offset variables, so it doesn't seem worth the
* trouble to separate them.
*
* If the $maximize argument is true, we use the full image size, minus safe_margin
* and main title, for the plot. This is for pie charts which have no axes or X/Y titles.
*/
protected function CalcMargins($maximize)
{
// This is the line-to-line or line-to-text spacing:
$gap = $this->safe_margin;
// Initial margin on each side takes into account a possible image border.
// For compatibility, if border is 1 or 2, don't increase the margins.
$base_margin = max($gap, $this->GetImageBorderWidth() + 3);
$this->title_offset = $base_margin; // For use in DrawTitle
// Minimum margin on each side. This reduces the chance that the
// right-most tick label (for example) will run off the image edge
// if there are no titles on that side.
$min_margin = 2 * $gap + $base_margin;
// Calculate the title sizes:
list($unused, $title_height) = $this->SizeText($this->fonts['title'], 0, $this->title_txt);
list($unused, $x_title_height) = $this->SizeText($this->fonts['x_title'], 0, $this->x_title_txt);
list($y_title_width, $unused) = $this->SizeText($this->fonts['y_title'], 90, $this->y_title_txt);
// Special case for maximum area usage with no X/Y titles or labels, only main title:
if ($maximize) {
if (!isset($this->x_left_margin))
$this->x_left_margin = $base_margin;
if (!isset($this->x_right_margin))
$this->x_right_margin = $base_margin;
if (!isset($this->y_top_margin)) {
$this->y_top_margin = $base_margin;
if ($title_height > 0)
$this->y_top_margin += $title_height + $gap;
}
if (!isset($this->y_bot_margin))
$this->y_bot_margin = $base_margin;
return TRUE;
}
// Make local variables for these. (They get used a lot and I'm tired of this, this, this.)
$x_tick_label_pos = $this->x_tick_label_pos;
$x_data_label_pos = $this->x_data_label_pos;
$x_tick_pos = $this->x_tick_pos;
$x_tick_len = $this->x_tick_length;
$y_tick_label_pos = $this->y_tick_label_pos;
$y_tick_pos = $this->y_tick_pos;
$y_tick_len = $this->y_tick_length;
$y_data_label_pos = $this->y_data_label_pos;
// For X/Y tick and label position of 'xaxis' or 'yaxis', determine if the axis happens to be
// on an edge of a plot. If it is, we need to account for the margins there.
if ($this->x_axis_position <= $this->plot_min_y)
$x_axis_pos = 'bottom';
elseif ($this->x_axis_position >= $this->plot_max_y)
$x_axis_pos = 'top';
else
$x_axis_pos = 'none';
if ($this->y_axis_position <= $this->plot_min_x)
$y_axis_pos = 'left';
elseif ($this->y_axis_position >= $this->plot_max_x)
$y_axis_pos = 'right';
else
$y_axis_pos = 'none';
// Calculate the heights for X tick and data labels, and the max (used if they are overlaid):
$x_data_label_height = ($x_data_label_pos == 'none') ? 0 : $this->CalcMaxDataLabelSize('x');
$x_tick_label_height = ($x_tick_label_pos == 'none') ? 0 : $this->CalcMaxTickLabelSize('x');
$x_max_label_height = max($x_data_label_height, $x_tick_label_height);
// Calculate the space needed above and below the plot for X tick and X data labels:
// Above the plot:
$tick_labels_above = ($x_tick_label_pos == 'plotup' || $x_tick_label_pos == 'both'
|| ($x_tick_label_pos == 'xaxis' && $x_axis_pos == 'top'));
$data_labels_above = ($x_data_label_pos == 'plotup' || $x_data_label_pos == 'both');
if ($tick_labels_above) {
if ($data_labels_above) {
$label_height_above = $x_max_label_height;
} else {
$label_height_above = $x_tick_label_height;
}
} elseif ($data_labels_above) {
$label_height_above = $x_data_label_height;
} else {
$label_height_above = 0;
}
// Below the plot:
$tick_labels_below = ($x_tick_label_pos == 'plotdown' || $x_tick_label_pos == 'both'
|| ($x_tick_label_pos == 'xaxis' && $x_axis_pos == 'bottom'));
$data_labels_below = ($x_data_label_pos == 'plotdown' || $x_data_label_pos == 'both');
if ($tick_labels_below) {
if ($data_labels_below) {
$label_height_below = $x_max_label_height;
} else {
$label_height_below = $x_tick_label_height;
}
} elseif ($data_labels_below) {
$label_height_below = $x_data_label_height;
} else {
$label_height_below = 0;
}
// Calculate the width for Y tick and data labels, if on, and the max:
// Note CalcMaxDataLabelSize('y') returns 0 except for swapped X/Y plots.
$y_data_label_width = ($y_data_label_pos == 'none') ? 0 : $this->CalcMaxDataLabelSize('y');
$y_tick_label_width = ($y_tick_label_pos == 'none') ? 0 : $this->CalcMaxTickLabelSize('y');
$y_max_label_width = max($y_data_label_width, $y_tick_label_width);
// Calculate the space needed left and right of the plot for Y tick and Y data labels:
// (Y data labels here are for swapped X/Y plots such has horizontal bars)
// Left of the plot:
$tick_labels_left = ($y_tick_label_pos == 'plotleft' || $y_tick_label_pos == 'both'
|| ($y_tick_label_pos == 'yaxis' && $y_axis_pos == 'left'));
$data_labels_left = ($y_data_label_pos == 'plotleft' || $y_data_label_pos == 'both');
if ($tick_labels_left) {
if ($data_labels_left) {
$label_width_left = $y_max_label_width;
} else {
$label_width_left = $y_tick_label_width;
}
} elseif ($data_labels_left) {
$label_width_left = $y_data_label_width;
} else {
$label_width_left = 0;
}
// Right of the plot:
$tick_labels_right = ($y_tick_label_pos == 'plotright' || $y_tick_label_pos == 'both'
|| ($y_tick_label_pos == 'yaxis' && $y_axis_pos == 'right'));
$data_labels_right = ($y_data_label_pos == 'plotright' || $y_data_label_pos == 'both');
if ($tick_labels_right) {
if ($data_labels_right) {
$label_width_right = $y_max_label_width;
} else {
$label_width_right = $y_tick_label_width;
}
} elseif ($data_labels_right) {
$label_width_right = $y_data_label_width;
} else {
$label_width_right = 0;
}
///////// Calculate margins:
// Calculating Top and Bottom margins:
// y_top_margin: Main title, Upper X title, X ticks and tick labels, and X data labels:
// y_bot_margin: Lower title, ticks and tick labels, and data labels:
$top_margin = $base_margin;
$bot_margin = $base_margin;
$this->x_title_top_offset = $gap;
$this->x_title_bot_offset = $gap;
// Space for main title?
if ($title_height > 0)
$top_margin += $title_height + $gap;
// Space for X Title?
if ($x_title_height > 0) {
$pos = $this->x_title_pos;
if ($pos == 'plotup' || $pos == 'both')
$top_margin += $x_title_height + $gap;
if ($pos == 'plotdown' || $pos == 'both')
$bot_margin += $x_title_height + $gap;
}
// Space for X Labels above the plot?
if ($label_height_above > 0) {
$top_margin += $label_height_above + $gap;
$this->x_title_top_offset += $label_height_above + $gap;
}
// Space for X Labels below the plot?
if ($label_height_below > 0) {
$bot_margin += $label_height_below + $gap;
$this->x_title_bot_offset += $label_height_below + $gap;
}
// Space for X Ticks above the plot?
if ($x_tick_pos == 'plotup' || $x_tick_pos == 'both'
|| ($x_tick_pos == 'xaxis' && $x_axis_pos == 'top')) {
$top_margin += $x_tick_len;
$this->x_label_top_offset = $x_tick_len + $gap;
$this->x_title_top_offset += $x_tick_len;
} else {
// No X Ticks above the plot:
$this->x_label_top_offset = $gap;
}
// Space for X Ticks below the plot?
if ($x_tick_pos == 'plotdown' || $x_tick_pos == 'both'
|| ($x_tick_pos == 'xaxis' && $x_axis_pos == 'bottom')) {
$bot_margin += $x_tick_len;
$this->x_label_bot_offset = $x_tick_len + $gap;
$this->x_title_bot_offset += $x_tick_len;
} else {
// No X Ticks below the plot:
$this->x_label_bot_offset = $gap;
}
// Label offsets for on-axis ticks:
if ($x_tick_pos == 'xaxis') {
$this->x_label_axis_offset = $x_tick_len + $gap;
} else {
$this->x_label_axis_offset = $gap;
}
// Calculating Left and Right margins:
// x_left_margin: Left Y title, Y ticks and tick labels:
// x_right_margin: Right Y title, Y ticks and tick labels:
$left_margin = $base_margin;
$right_margin = $base_margin;
$this->y_title_left_offset = $gap;
$this->y_title_right_offset = $gap;
// Space for Y Title?
if ($y_title_width > 0) {
$pos = $this->y_title_pos;
if ($pos == 'plotleft' || $pos == 'both')
$left_margin += $y_title_width + $gap;
if ($pos == 'plotright' || $pos == 'both')
$right_margin += $y_title_width + $gap;
}
// Space for Y Labels left of the plot?
if ($label_width_left > 0) {
$left_margin += $label_width_left + $gap;
$this->y_title_left_offset += $label_width_left + $gap;
}
// Space for Y Labels right of the plot?
if ($label_width_right > 0) {
$right_margin += $label_width_right + $gap;
$this->y_title_right_offset += $label_width_right + $gap;
}
// Space for Y Ticks left of plot?
if ($y_tick_pos == 'plotleft' || $y_tick_pos == 'both'
|| ($y_tick_pos == 'yaxis' && $y_axis_pos == 'left')) {
$left_margin += $y_tick_len;
$this->y_label_left_offset = $y_tick_len + $gap;
$this->y_title_left_offset += $y_tick_len;
} else {
// No Y Ticks left of plot:
$this->y_label_left_offset = $gap;
}
// Space for Y Ticks right of plot?
if ($y_tick_pos == 'plotright' || $y_tick_pos == 'both'
|| ($y_tick_pos == 'yaxis' && $y_axis_pos == 'right')) {
$right_margin += $y_tick_len;
$this->y_label_right_offset = $y_tick_len + $gap;
$this->y_title_right_offset += $y_tick_len;
} else {
// No Y Ticks right of plot:
$this->y_label_right_offset = $gap;
}
// Label offsets for on-axis ticks:
if ($x_tick_pos == 'yaxis') {
$this->y_label_axis_offset = $y_tick_len + $gap;
} else {
$this->y_label_axis_offset = $gap;
}
// Apply the minimum margins and store in the object.
// Do not set margins which were user-defined (see note at top of function).
if (!isset($this->y_top_margin))
$this->y_top_margin = max($min_margin, $top_margin);
if (!isset($this->y_bot_margin))
$this->y_bot_margin = max($min_margin, $bot_margin);
if (!isset($this->x_left_margin))
$this->x_left_margin = max($min_margin, $left_margin);
if (!isset($this->x_right_margin))
$this->x_right_margin = max($min_margin, $right_margin);
if ($this->GetCallback('debug_scale')) {
// (Too bad compact() doesn't work on class member variables...)
$this->DoCallback('debug_scale', __FUNCTION__, array(
'label_height_above' => $label_height_above,
'label_height_below' => $label_height_below,
'label_width_left' => $label_width_left,
'label_width_right' => $label_width_right,
'x_tick_len' => $x_tick_len,
'y_tick_len' => $y_tick_len,
'x_left_margin' => $this->x_left_margin,
'x_right_margin' => $this->x_right_margin,
'y_top_margin' => $this->y_top_margin,
'y_bot_margin' => $this->y_bot_margin,
'x_label_top_offset' => $this->x_label_top_offset,
'x_label_bot_offset' => $this->x_label_bot_offset,
'y_label_left_offset' => $this->y_label_left_offset,
'y_label_right_offset' => $this->y_label_right_offset,
'x_title_top_offset' => $this->x_title_top_offset,
'x_title_bot_offset' => $this->x_title_bot_offset,
'y_title_left_offset' => $this->y_title_left_offset,
'y_title_right_offset' => $this->y_title_right_offset));
}
return TRUE;
}
/*
* Calculate the plot area (device coordinates) from the margins.
* (This used to be part of SetPlotAreaPixels.)
* The margins might come from SetMarginsPixels, SetPlotAreaPixels,
* or CalcMargins.
*/
protected function CalcPlotAreaPixels()
{
$this->plot_area = array($this->x_left_margin, $this->y_top_margin,
$this->image_width - $this->x_right_margin,
$this->image_height - $this->y_bot_margin);
$this->plot_area_width = $this->plot_area[2] - $this->plot_area[0];
$this->plot_area_height = $this->plot_area[3] - $this->plot_area[1];
$this->DoCallback('debug_scale', __FUNCTION__, $this->plot_area);
return TRUE;
}
/*
* Set the margins in pixels (left, right, top, bottom)
* This determines the plot area, equivalent to SetPlotAreaPixels().
* Deferred calculations now occur in CalcPlotAreaPixels().
*/
function SetMarginsPixels($which_lm = NULL, $which_rm = NULL, $which_tm = NULL, $which_bm = NULL)
{
$this->x_left_margin = $which_lm;
$this->x_right_margin = $which_rm;
$this->y_top_margin = $which_tm;
$this->y_bot_margin = $which_bm;
return TRUE;
}
/*
* Sets the limits for the plot area.
* This stores the margins, not the area. That may seem odd, but
* the idea is to make SetPlotAreaPixels and SetMarginsPixels two
* ways to accomplish the same thing, and the deferred calculations
* in CalcMargins and CalcPlotAreaPixels don't need to know which
* was used.
* (x1, y1) - Upper left corner of the plot area
* (x2, y2) - Lower right corner of the plot area
*/
function SetPlotAreaPixels($x1 = NULL, $y1 = NULL, $x2 = NULL, $y2 = NULL)
{
$this->x_left_margin = $x1;
if (isset($x2)) $this->x_right_margin = $this->image_width - $x2;
else unset($this->x_right_margin);
$this->y_top_margin = $y1;
if (isset($y2)) $this->y_bot_margin = $this->image_height - $y2;
else unset($this->y_bot_margin);
return TRUE;
}
/*
* Calculate the World Coordinate limits of the plot area.
* This goes with SetPlotAreaWorld, but the calculations are
* deferred until the graph is being drawn.
* Uses and sets: plot_min_x, plot_max_x, plot_min_y, plot_max_y
* These can be user-supplied or NULL to auto-calculate.
* Pre-requisites: FindDataLimits() calculates min_x, max_x, min_y, max_y
* which are the limits of the data to be plotted.
*
* The general method is this:
* If any part of the range is user-defined (via SetPlotAreaWorld),
* use the user-defined value.
* Else, if this is an implicitly-defined independent variable,
* use the fixed range of 0 to (max+1).
* Else, if this is an explicitly-defined independent variable,
* use the exact data range (min to max).
* Else, this is the dependent variable, so define a range which
* includes and exceeds the data range by a bit.
*/
protected function CalcPlotAreaWorld()
{
// Data array omits X or Y?
$implied_x = $this->datatype_implied && !$this->datatype_swapped_xy;
$implied_y = $this->datatype_implied && $this->datatype_swapped_xy;
if (isset($this->plot_min_x) && $this->plot_min_x !== '')
$xmin = $this->plot_min_x; // Use user-provided value
elseif ($implied_x)
$xmin = 0; // Implied X starts at zero
elseif ($this->datatype_swapped_xy)
// If X is the dependent variable, leave some room below.
$xmin = floor($this->min_x - abs($this->min_x) * 0.1);
else
$xmin = $this->min_x; // Otherwise just start at the min data X
if (isset($this->plot_max_x) && $this->plot_max_x !== '')
$xmax = $this->plot_max_x; // Use user-provided value
elseif ($implied_x)
$xmax = $this->max_x + 1; // Implied X ends after last value
elseif ($this->datatype_swapped_xy)
// If X is the dependent variable, leave some room above.
$xmax = ceil($this->max_x + abs($this->max_x) * 0.1);
else
$xmax = $this->max_x; // Otherwise just end at the max data X
if (isset($this->plot_min_y) && $this->plot_min_y !== '')
$ymin = $this->plot_min_y; // Use user-provided value
elseif ($implied_y)
$ymin = 0; // Implied Y starts at zero
elseif ($this->datatype_swapped_xy)
$ymin = $this->min_y; // Start at min data Y
else
// If Y is the dependent variable, leave some room below.
$ymin = floor($this->min_y - abs($this->min_y) * 0.1);
if (isset($this->plot_max_y) && $this->plot_max_y !== '')
$ymax = $this->plot_max_y; // Use user-provided value
elseif ($implied_y)
$ymax = $this->max_y + 1; // Implied Y ends after last value
elseif ($this->datatype_swapped_xy)
$ymax = $this->max_y; // End at max data Y
else
// If Y is the dependent variable, leave some room above.
$ymax = ceil($this->max_y + abs($this->max_y) * 0.1);
// Error checking
if ($ymin == $ymax)
$ymax++;
if ($xmin == $xmax)
$xmax++;
if ($this->yscale_type == 'log') {
if ($ymin <= 0) {
$ymin = 1;
}
if ($ymax <= 0) {
// Note: Error messages reference the user function, not this function.
return $this->PrintError('SetPlotAreaWorld(): Log plots need data greater than 0');
}
}
if ($ymax <= $ymin) {
return $this->PrintError('SetPlotAreaWorld(): Error in data - max not greater than min');
}
$this->plot_min_x = $xmin;
$this->plot_max_x = $xmax;
$this->plot_min_y = $ymin;
$this->plot_max_y = $ymax;
if ($this->GetCallback('debug_scale')) {
$this->DoCallback('debug_scale', __FUNCTION__, array(
'plot_min_x' => $this->plot_min_x, 'plot_min_y' => $this->plot_min_y,
'plot_max_x' => $this->plot_max_x, 'plot_max_y' => $this->plot_max_y));
}
return TRUE;
}
/*
* Stores the desired World Coordinate range of the plot.
* The user calls this to force one or more of the range limits to
* specific values. Anything not set will be calculated in CalcPlotAreaWorld().
*/
function SetPlotAreaWorld($xmin=NULL, $ymin=NULL, $xmax=NULL, $ymax=NULL)
{
$this->plot_min_x = $xmin;
$this->plot_max_x = $xmax;
$this->plot_min_y = $ymin;
$this->plot_max_y = $ymax;
return TRUE;
}
/*
* Calculate the width (or height) of bars for bar plots.
* $stacked : If true, this is a stacked bar plot (1 bar per group).
* $verticals : If false, this is a horizontal bar plot.
* This calculates:
* record_bar_width : Allocated width for each bar (including gaps)
* actual_bar_width : Actual drawn width of each bar
* bar_adjust_gap : Gap on each side of each bar (0 if they touch)
* For the case $verticals=False, horizontal bars are being drawn,
* but the same variable names are used. Think of "bar_width" as being
* the width if you are standing on the Y axis looking towards positive X.
*/
protected function CalcBarWidths($stacked, $verticals)
{
// group_width is the width of a group, including padding
if ($verticals) {
$group_width = $this->plot_area_width / $this->num_data_rows;
} else {
$group_width = $this->plot_area_height / $this->num_data_rows;
}
// Actual number of bar spaces in the group. This includes the drawn bars, and
// 'bar_extra_space'-worth of extra bars.
if ($stacked) {
$num_spots = 1 + $this->bar_extra_space;
} else {
$num_spots = $this->data_columns + $this->bar_extra_space;
}
// record_bar_width is the width of each bar's allocated area.
// If bar_width_adjust=1 this is the width of the bar, otherwise
// the bar is centered inside record_bar_width.
// The equation is:
// group_frac_width * group_width = record_bar_width * num_spots
$this->record_bar_width = $this->group_frac_width * $group_width / $num_spots;
// Note that the extra space due to group_frac_width and bar_extra_space will be
// evenly divided on each side of the group: the drawn bars are centered in the group.
// Within each bar's allocated space, if bar_width_adjust=1 the bar fills the
// space, otherwise it is centered.
// This is the actual drawn bar width:
$this->actual_bar_width = $this->record_bar_width * $this->bar_width_adjust;
// This is the gap on each side of the bar (0 if bar_width_adjust=1):
$this->bar_adjust_gap = ($this->record_bar_width - $this->actual_bar_width) / 2;
if ($this->GetCallback('debug_scale')) {
$this->DoCallback('debug_scale', __FUNCTION__, array(
'record_bar_width' => $this->record_bar_width,
'actual_bar_width' => $this->actual_bar_width,
'bar_adjust_gap' => $this->bar_adjust_gap));
}
return TRUE;
}
/*
* Calculate X and Y Axis Positions, world coordinates.
* This needs the min/max x/y range set by CalcPlotAreaWorld.
* It adjusts or sets x_axis_position and y_axis_position per the data.
* Empty string means the values need to be calculated; otherwise they
* are supplied but need to be validated against the World area.
*
* Note: This used to be in CalcTranslation, but CalcMargins needs it too.
* This does not calculate the pixel values of the axes. That happens in
* CalcTranslation, after scaling is set up (which has to happen after
* margins are set up).
*
* For vertical plots, the X axis defaults to Y=0 if that is inside the plot range, else whichever
* of the top or bottom that has the smallest absolute value (that is, the value closest to 0).
* The Y axis defaults to the left edge. For horizontal plots, the axis roles and defaults are switched.
*/
protected function CalcAxisPositions()
{
// Validate user-provided X axis position, or calculate a default if not provided:
if ($this->x_axis_position !== '') {
// Force user-provided X axis position to be within the plot range:
$this->x_axis_position = min(max($this->plot_min_y, $this->x_axis_position), $this->plot_max_y);
} elseif ($this->yscale_type == 'log') {
// Always use 1 for X axis position on log scale plots.
$this->x_axis_position = 1;
} elseif ($this->datatype_swapped_xy || $this->plot_min_y > 0) {
// Horizontal plot, or Vertical Plot with all Y > 0: Place X axis on the bottom.
$this->x_axis_position = $this->plot_min_y;
} elseif ($this->plot_max_y < 0) {
// Vertical plot with all Y < 0, so place the X axis at the top.
$this->x_axis_position = $this->plot_max_y;
} else {
// Vertical plot range includes Y=0, so place X axis at 0.
$this->x_axis_position = 0;
}
// Validate user-provided Y axis position, or calculate a default if not provided:
if ($this->y_axis_position !== '') {
// Force user-provided Y axis position to be within the plot range:
$this->y_axis_position = min(max($this->plot_min_x, $this->y_axis_position), $this->plot_max_x);
} elseif ($this->xscale_type == 'log') {
// Always use 1 for Y axis position on log scale plots.
$this->y_axis_position = 1;
} elseif (!$this->datatype_swapped_xy || $this->plot_min_x > 0) {
// Vertical plot, or Horizontal Plot with all X > 0: Place Y axis on left side.
$this->y_axis_position = $this->plot_min_x;
} elseif ($this->plot_max_x < 0) {
// Horizontal plot with all X < 0, so place the Y axis on the right side.
$this->y_axis_position = $this->plot_max_x;
} else {
// Horizontal plot range includes X=0: place Y axis at 0.
$this->y_axis_position = 0;
}
if ($this->GetCallback('debug_scale')) {
$this->DoCallback('debug_scale', __FUNCTION__, array(
'x_axis_position' => $this->x_axis_position,
'y_axis_position' => $this->y_axis_position));
}
return TRUE;
}
/*
* Calculates scaling stuff...
*/
protected function CalcTranslation()
{
if ($this->plot_max_x - $this->plot_min_x == 0) { // Check for div by 0
$this->xscale = 0;
} else {
if ($this->xscale_type == 'log') {
$this->xscale = $this->plot_area_width /
(log10($this->plot_max_x) - log10($this->plot_min_x));
} else {
$this->xscale = $this->plot_area_width / ($this->plot_max_x - $this->plot_min_x);
}
}
if ($this->plot_max_y - $this->plot_min_y == 0) { // Check for div by 0
$this->yscale = 0;
} else {
if ($this->yscale_type == 'log') {
$this->yscale = $this->plot_area_height /
(log10($this->plot_max_y) - log10($this->plot_min_y));
} else {
$this->yscale = $this->plot_area_height / ($this->plot_max_y - $this->plot_min_y);
}
}
// GD defines x = 0 at left and y = 0 at TOP so -/+ respectively
if ($this->xscale_type == 'log') {
$this->plot_origin_x = $this->plot_area[0] - ($this->xscale * log10($this->plot_min_x) );
} else {
$this->plot_origin_x = $this->plot_area[0] - ($this->xscale * $this->plot_min_x);
}
if ($this->yscale_type == 'log') {
$this->plot_origin_y = $this->plot_area[3] + ($this->yscale * log10($this->plot_min_y));
} else {
$this->plot_origin_y = $this->plot_area[3] + ($this->yscale * $this->plot_min_y);
}
// Convert axis positions to device coordinates:
$this->y_axis_x_pixels = $this->xtr($this->y_axis_position);
$this->x_axis_y_pixels = $this->ytr($this->x_axis_position);
if ($this->GetCallback('debug_scale')) {
$this->DoCallback('debug_scale', __FUNCTION__, array(
'xscale' => $this->xscale, 'yscale' => $this->yscale,
'plot_origin_x' => $this->plot_origin_x, 'plot_origin_y' => $this->plot_origin_y,
'y_axis_x_pixels' => $this->y_axis_x_pixels,
'x_axis_y_pixels' => $this->x_axis_y_pixels));
}
return TRUE;
}
/*
* Translate X world coordinate into pixel coordinate
* See CalcTranslation() for calculation of xscale.
* Note: This function should be 'protected', but is left public for historical reasons.
* See GetDeviceXY() for a preferred public method.
*/
function xtr($x_world)
{
if ($this->xscale_type == 'log') {
$x_pixels = $this->plot_origin_x + log10($x_world) * $this->xscale ;
} else {
$x_pixels = $this->plot_origin_x + $x_world * $this->xscale ;
}
return round($x_pixels);
}
/*
* Translate Y world coordinate into pixel coordinate.
* See CalcTranslation() for calculation of yscale.
* Note: This function should be 'protected', but is left public for historical reasons.
* See GetDeviceXY() for a preferred public method.
*/
function ytr($y_world)
{
if ($this->yscale_type == 'log') {
//minus because GD defines y = 0 at top. doh!
$y_pixels = $this->plot_origin_y - log10($y_world) * $this->yscale ;
} else {
$y_pixels = $this->plot_origin_y - $y_world * $this->yscale ;
}
return round($y_pixels);
}
/* A public interface to xtr and ytr. Translates (x,y) in world coordinates
* to (x,y) in device coordinates and returns them as an array.
* Usage is: list($x_pixel, $y_pixel) = $plot->GetDeviceXY($x_world, $y_world)
*/
function GetDeviceXY($x_world, $y_world)
{
if (!isset($this->xscale)) {
return $this->PrintError("GetDeviceXY() was called before translation factors were calculated");
}
return array($this->xtr($x_world), $this->ytr($y_world));
}
/*
* Calculate tick parameters: Start, end, and delta values. This is used
* by both DrawXTicks() and DrawYTicks().
* This currently uses the same simplistic method previously used by
* PHPlot (basically just range/10), but splitting this out into its
* own function is the first step in replacing the method.
* This is also used by CalcMaxTickSize() for CalcMargins().
*
* $which : 'x' or 'y' : Which tick parameters to calculate
*
* Returns an array of 3 elements: tick_start, tick_end, tick_step
*/
protected function CalcTicks($which)
{
if ($which == 'x') {
$num_ticks = $this->num_x_ticks;
$tick_inc = $this->x_tick_inc;
$data_max = $this->plot_max_x;
$data_min = $this->plot_min_x;
$skip_lo = $this->skip_left_tick;
$skip_hi = $this->skip_right_tick;
$anchor = &$this->x_tick_anchor; // Use reference because this might not be set
} elseif ($which == 'y') {
$num_ticks = $this->num_y_ticks;
$tick_inc = $this->y_tick_inc;
$data_max = $this->plot_max_y;
$data_min = $this->plot_min_y;
$skip_lo = $this->skip_bottom_tick;
$skip_hi = $this->skip_top_tick;
$anchor = &$this->y_tick_anchor; // Use reference because this might not be set
} else {
return $this->PrintError("CalcTicks: Invalid usage ($which)");
}
if (!empty($tick_inc)) {
$tick_step = $tick_inc;
} elseif (!empty($num_ticks)) {
$tick_step = ($data_max - $data_min) / $num_ticks;
} else {
$tick_step = ($data_max - $data_min) / 10;
}
// NOTE: When working with floats, because of approximations when adding $tick_step,
// the value may not quite reach the end, or may exceed it very slightly.
// So apply a "fudge" factor.
$tick_start = (double)$data_min;
$tick_end = (double)$data_max + ($data_max - $data_min) / 10000.0;
// If a tick anchor was given, adjust the start of the range so the anchor falls
// at an exact tick mark (or would, if it was within range).
if (isset($anchor)) {
$tick_start = $anchor - $tick_step * floor(($anchor - $tick_start) / $tick_step);
}
// Lastly, adjust for option to skip left/bottom or right/top tick marks:
if ($skip_lo)
$tick_start += $tick_step;
if ($skip_hi)
$tick_end -= $tick_step;
return array($tick_start, $tick_end, $tick_step);
}
/*
* Calculate the size of the biggest tick label. This is used by CalcMargins().
* For 'x' ticks, it returns the height . For 'y' ticks, it returns the width.
* This means height along Y, or width along X - not relative to the text angle.
* That is what we need to calculate the needed margin space.
* (Previous versions of PHPlot estimated this, using the maximum X or Y value,
* or maybe the longest string. That doesn't work. -10 is longer than 9, etc.
* So this gets the actual size of each label, slow as that may be.
*/
protected function CalcMaxTickLabelSize($which)
{
list($tick_start, $tick_end, $tick_step) = $this->CalcTicks($which);
if ($which == 'x') {
$font = $this->fonts['x_label'];
$angle = $this->x_label_angle;
} elseif ($which == 'y') {
$font = $this->fonts['y_label'];
$angle = $this->y_label_angle;
} else {
return $this->PrintError("CalcMaxTickLabelSize: Invalid usage ($which)");
}
$max_width = 0;
$max_height = 0;
// Loop over ticks, same as DrawXTicks and DrawYTicks:
// Avoid cumulative round-off errors from $val += $delta
$n = 0;
$tick_val = $tick_start;
while ($tick_val <= $tick_end) {
$tick_label = $this->FormatLabel($which, $tick_val);
list($width, $height) = $this->SizeText($font, $angle, $tick_label);
if ($width > $max_width) $max_width = $width;
if ($height > $max_height) $max_height = $height;
$tick_val = $tick_start + ++$n * $tick_step;
}
if ($this->GetCallback('debug_scale')) {
$this->DoCallback('debug_scale', __FUNCTION__, array(
'which' => $which, 'height' => $max_height, 'width' => $max_width));
}
if ($which == 'x')
return $max_height;
return $max_width;
}
/*
* Calculate the size of the biggest data label. This is used by CalcMargins().
* For $which='x', it returns the height of labels along the top or bottom.
* For $which='y', it returns the width of labels along the left or right sides.
* There is only one set of data labels (the first position in each data record).
* They normally go along the top or bottom (or both). If the data type indicates
* X/Y swapping (which is used for horizontal bar charts), the data labels go
* along the sides instead. So CalcMaxDataLabelSize('x') returns 0 if the
* data is X/Y swapped, and CalcMaxDataLabelSize('y') returns 0 if the data is
* is not X/Y swapped.
*/
protected function CalcMaxDataLabelSize($which = 'x')
{
if ($which == 'x') {
if ($this->datatype_swapped_xy)
return 0; // Shortcut: labels aren't on top/bottom.
$font = $this->fonts['x_label'];
$angle = $this->x_data_label_angle;
$format_code = 'xd';
} elseif ($which == 'y') {
if (!$this->datatype_swapped_xy)
return 0; // Shortcut: labels aren't on left/right.
$font = $this->fonts['y_label'];
$angle = $this->y_data_label_angle;
$format_code = 'yd';
} else {
return $this->PrintError("CalcMaxDataLabelSize: Invalid usage ($which)");
}
$max_width = 0;
$max_height = 0;
// Loop over all data labels and find the biggest:
for ($i = 0; $i < $this->num_data_rows; $i++) {
$label = $this->FormatLabel($format_code, $this->data[$i][0]);
list($width, $height) = $this->SizeText($font, $angle, $label);
if ($width > $max_width) $max_width = $width;
if ($height > $max_height) $max_height = $height;
}
if ($this->GetCallback('debug_scale')) {
$this->DoCallback('debug_scale', __FUNCTION__, array(
'height' => $max_height, 'width' => $max_width));
}
if ($this->datatype_swapped_xy)
return $max_width;
return $max_height;
}
/*
* Set grid control defaults.
* X grid defaults off, Y grid defaults on, except the reverse is true
* with swapped graphs such as horizontal bars.
*/
protected function CalcGridSettings()
{
if (!isset($this->draw_x_grid))
$this->draw_x_grid = $this->datatype_swapped_xy;
if (!isset($this->draw_y_grid))
$this->draw_y_grid = !$this->datatype_swapped_xy;
}
/*
* Helper for CheckLabels() - determine if there are any non-empty labels.
* Returns True if all data labels are empty, else False.
*/
protected function CheckLabelsAllEmpty()
{
for ($i = 0; $i < $this->num_data_rows; $i++)
if ($this->data[$i][0] !== '') return FALSE;
return TRUE;
}
/*
* Check and set label parameters. This handles deferred processing for label
* positioning and other label-related parameters.
* Copy label_format from 'x' to 'xd', and 'y' to 'yd', if not already set.
* Set x_data_label_angle from x_label_angle, if not already set.
* Apply defaults to X and Y tick and data label positions.
* Note: the label strings in the data array are used as X data labels in
* the normal case, but as Y data labels in the swapped X/Y case.
*/
protected function CheckLabels()
{
// The X and Y data labels are formatted the same as X and Y tick labels,
// unless overridden. Check and apply defaults for FormatLabel here:
if (empty($this->label_format['xd']) && !empty($this->label_format['x']))
$this->label_format['xd'] = $this->label_format['x'];
if (empty($this->label_format['yd']) && !empty($this->label_format['y']))
$this->label_format['yd'] = $this->label_format['y'];
// The X tick label angle setting controls X data label angles too,
// unless overridden. Check and apply the default here:
if (!isset($this->x_data_label_angle))
$this->x_data_label_angle = $this->x_label_angle;
// Note: Y data label angle defaults to zero, unlike X,
// for compatibility with older releases.
// X Label position fixups, for x_data_label_pos and x_tick_label_pos:
if ($this->datatype_swapped_xy) {
// Just apply defaults - there is no position conflict for X labels.
if (!isset($this->x_tick_label_pos))
$this->x_tick_label_pos = 'plotdown';
if (!isset($this->x_data_label_pos))
$this->x_data_label_pos = 'none';
} else {
// Apply defaults but do not allow conflict between tick and data labels.
if (isset($this->x_data_label_pos)) {
if (!isset($this->x_tick_label_pos)) {
// Case: data_label_pos is set, tick_label_pos needs a default:
if ($this->x_data_label_pos == 'none')
$this->x_tick_label_pos = 'plotdown';
else
$this->x_tick_label_pos = 'none';
}
} elseif (isset($this->x_tick_label_pos)) {
// Case: tick_label_pos is set, data_label_pos needs a default:
if ($this->x_tick_label_pos == 'none')
$this->x_data_label_pos = 'plotdown';
else
$this->x_data_label_pos = 'none';
} else {
// Case: Neither tick_label_pos nor data_label_pos is set.
// We do not want them to be both on (as PHPlot used to do in this case).
// Turn on data labels if any were supplied, else tick labels.
if ($this->CheckLabelsAllEmpty()) {
$this->x_data_label_pos = 'none';
$this->x_tick_label_pos = 'plotdown';
} else {
$this->x_data_label_pos = 'plotdown';
$this->x_tick_label_pos = 'none';
}
}
}
// Y Label position fixups, for y_data_label_pos and y_tick_label_pos:
if (!$this->datatype_swapped_xy) {
// Just apply defaults - there is no position conflict.
if (!isset($this->y_tick_label_pos))
$this->y_tick_label_pos = 'plotleft';
if (!isset($this->y_data_label_pos))
$this->y_data_label_pos = 'none';
} else {
// Apply defaults but do not allow conflict between tick and data labels.
if (isset($this->y_data_label_pos)) {
if (!isset($this->y_tick_label_pos)) {
// Case: data_label_pos is set, tick_label_pos needs a default:
if ($this->y_data_label_pos == 'none')
$this->y_tick_label_pos = 'plotleft';
else
$this->y_tick_label_pos = 'none';
}
} elseif (isset($this->y_tick_label_pos)) {
// Case: tick_label_pos is set, data_label_pos needs a default:
if ($this->y_tick_label_pos == 'none')
$this->y_data_label_pos = 'plotleft';
else
$this->y_data_label_pos = 'none';
} else {
// Case: Neither tick_label_pos nor data_label_pos is set.
// Turn on data labels if any were supplied, else tick labels.
if ($this->CheckLabelsAllEmpty()) {
$this->y_data_label_pos = 'none';
$this->y_tick_label_pos = 'plotleft';
} else {
$this->y_data_label_pos = 'plotleft';
$this->y_tick_label_pos = 'none';
}
}
}
return TRUE;
}
/*
* Formats a tick or data label.
* which_pos - 'x', 'xd', 'y', or 'yd', selects formatting controls.
* x, y are for tick labels; xd, yd are for data labels.
* which_lab - String to format as a label.
* Credits: Time formatting suggested by Marlin Viss
* Custom formatting suggested by zer0x333
* Notes:
* Type 'title' is obsolete and retained for compatibility.
* Class variable 'data_units_text' is retained as a suffix for 'data' type formatting for
* backward compatibility. Since there was never a function/method to set it, there
* could be somebody out there who sets it directly in the object.
*/
protected function FormatLabel($which_pos, $which_lab)
{
// Assign a reference shortcut to the label format controls.
// Note CheckLabels() made sure the 'xd' and 'yd' arrays are set.
$format =& $this->label_format[$which_pos];
// Don't format empty strings (especially as time or numbers), or if no type was set.
if ($which_lab !== '' && !empty($format['type'])) {
switch ($format['type']) {
case 'title': // Note: This is obsolete
$which_lab = @ $this->data[$which_lab][0];
break;
case 'data':
$which_lab = $format['prefix']
. $this->number_format($which_lab, $format['precision'])
. $this->data_units_text // Obsolete
. $format['suffix'];
break;
case 'time':
$which_lab = strftime($format['time_format'], $which_lab);
break;
case 'printf':
$which_lab = sprintf($format['printf_format'], $which_lab);
break;
case 'custom':
$which_lab = call_user_func($format['custom_callback'], $which_lab, $format['custom_arg']);
break;
}
}
return $which_lab;
}
/////////////////////////////////////////////
/////////////// TICKS
/////////////////////////////////////////////
/*
* Set the step (interval) between X ticks.
* Use either this or SetNumXTicks(), not both, to control the X tick marks.
*/
function SetXTickIncrement($which_ti='')
{
$this->x_tick_inc = $which_ti;
if (!empty($which_ti)) {
$this->num_x_ticks = '';
}
return TRUE;
}
/*
* Set the step (interval) between Y ticks.
* Use either this or SetNumYTicks(), not both, to control the Y tick marks.
*/
function SetYTickIncrement($which_ti='')
{
$this->y_tick_inc = $which_ti;
if (!empty($which_ti)) {
$this->num_y_ticks = '';
}
return TRUE;
}
/*
* Set the number of X tick marks.
* Use either this or SetXTickIncrement(), not both, to control the X tick marks.
*/
function SetNumXTicks($which_nt='')
{
$this->num_x_ticks = $which_nt;
if (!empty($which_nt)) {
$this->x_tick_inc = '';
}
return TRUE;
}
/*
* Set the number of Y tick marks.
* Use either this or SetYTickIncrement(), not both, to control the Y tick marks.
*/
function SetNumYTicks($which_nt='')
{
$this->num_y_ticks = $which_nt;
if (!empty($which_nt)) {
$this->y_tick_inc = ''; //either use num_y_ticks or y_tick_inc, not both
}
return TRUE;
}
/*
* Set the position for the X tick marks.
* These can be above the plot, below, both positions, at the X axis, or suppressed.
*/
function SetXTickPos($which_tp)
{
$this->x_tick_pos = $this->CheckOption($which_tp, 'plotdown, plotup, both, xaxis, none',
__FUNCTION__);
return (boolean)$this->x_tick_pos;
}
/*
* Set the position for the Y tick marks.
* These can be left of the plot, right, both positions, at the Y axis, or suppressed.
*/
function SetYTickPos($which_tp)
{
$this->y_tick_pos = $this->CheckOption($which_tp, 'plotleft, plotright, both, yaxis, none',
__FUNCTION__);
return (boolean)$this->y_tick_pos;
}
/*
* Skip the top-most Y axis tick mark and label if $skip is true.
*/
function SetSkipTopTick($skip)
{
$this->skip_top_tick = (bool)$skip;
return TRUE;
}
/*
* Skip the bottom-most Y axis tick mark and label if $skip is true.
*/
function SetSkipBottomTick($skip)
{
$this->skip_bottom_tick = (bool)$skip;
return TRUE;
}
/*
* Skip the left-most X axis tick mark and label if $skip is true.
*/
function SetSkipLeftTick($skip)
{
$this->skip_left_tick = (bool)$skip;
return TRUE;
}
/*
* Skip the right-most X axis tick mark and label if $skip is true.
*/
function SetSkipRightTick($skip)
{
$this->skip_right_tick = (bool)$skip;
return TRUE;
}
/*
* Set the outer length of X tick marks to $which_xln pixels.
* This is the part of the tick mark that sticks out from the plot area.
*/
function SetXTickLength($which_xln)
{
$this->x_tick_length = $which_xln;
return TRUE;
}
/*
* Set the outer length of Y tick marks to $which_yln pixels.
* This is the part of the tick mark that sticks out from the plot area.
*/
function SetYTickLength($which_yln)
{
$this->y_tick_length = $which_yln;
return TRUE;
}
/*
* Set the crossing length of X tick marks to $which_xc pixels.
* This is the part of the tick mark that sticks into the plot area.
*/
function SetXTickCrossing($which_xc)
{
$this->x_tick_cross = $which_xc;
return TRUE;
}
/*
* Set the crossing length of Y tick marks to $which_yc pixels.
* This is the part of the tick mark that sticks into the plot area.
*/
function SetYTickCrossing($which_yc)
{
$this->y_tick_cross = $which_yc;
return TRUE;
}
/*
* Set an anchor point for X tick marks. There will be an X tick mark at
* this exact value (if the data range were extended to include it).
*/
function SetXTickAnchor($xta = NULL)
{
$this->x_tick_anchor = $xta;
return TRUE;
}
/*
* Set an anchor point for Y tick marks. There will be a Y tick mark at
* this exact value (if the data range were extended to include it).
*/
function SetYTickAnchor($yta = NULL)
{
$this->y_tick_anchor = $yta;
return TRUE;
}
/////////////////////////////////////////////
//////////////////// GENERIC DRAWING
/////////////////////////////////////////////
/*
* Fill the image background, with a tiled image file or solid color.
*/
protected function DrawBackground()
{
// Don't draw this twice if drawing two plots on one image
if (empty($this->done['background'])) {
if (isset($this->bgimg)) { // If bgimg is defined, use it
$this->tile_img($this->bgimg, 0, 0, $this->image_width, $this->image_height, $this->bgmode);
} else { // Else use solid color
ImageFilledRectangle($this->img, 0, 0, $this->image_width, $this->image_height,
$this->ndx_bg_color);
}
$this->done['background'] = TRUE;
}
return TRUE;
}
/*
* Fill the plot area background, with a tiled image file or solid color.
*/
protected function DrawPlotAreaBackground()
{
if (isset($this->plotbgimg)) {
$this->tile_img($this->plotbgimg, $this->plot_area[0], $this->plot_area[1],
$this->plot_area_width, $this->plot_area_height, $this->plotbgmode);
} elseif ($this->draw_plot_area_background) {
ImageFilledRectangle($this->img, $this->plot_area[0], $this->plot_area[1],
$this->plot_area[2], $this->plot_area[3], $this->ndx_plot_bg_color);
}
return TRUE;
}
/*
* Tiles an image at some given coordinates.
* $file : Filename of the picture to be used as tile.
* $xorig : X device coordinate of where the tile is to begin.
* $yorig : Y device coordinate of where the tile is to begin.
* $width : Width of the area to be tiled.
* $height : Height of the area to be tiled.
* $mode : Tiling mode. One of 'centeredtile', 'tile', 'scale'.
*/
protected function tile_img($file, $xorig, $yorig, $width, $height, $mode)
{
$im = $this->GetImage($file, $tile_width, $tile_height);
if (!$im)
return FALSE; // GetImage already produced an error message.
if ($mode == 'scale') {
imagecopyresampled($this->img, $im, $xorig, $yorig, 0, 0, $width, $height,
$tile_width, $tile_height);
return TRUE;
}
if ($mode == 'centeredtile') {
$x0 = - floor($tile_width/2); // Make the tile look better
$y0 = - floor($tile_height/2);
} else { // Accept anything else as $mode == 'tile'
$x0 = 0;
$y0 = 0;
}
// Draw the tile onto a temporary image first.
$tmp = imagecreate($width, $height);
if (! $tmp)
return $this->PrintError('tile_img(): Could not create image resource.');
for ($x = $x0; $x < $width; $x += $tile_width)
for ($y = $y0; $y < $height; $y += $tile_height)
imagecopy($tmp, $im, $x, $y, 0, 0, $tile_width, $tile_height);
// Copy the temporary image onto the final one.
imagecopy($this->img, $tmp, $xorig, $yorig, 0,0, $width, $height);
// Free resources
imagedestroy($tmp);
imagedestroy($im);
return TRUE;
}
/*
* Return the image border width.
* This is used by CalcMargins() and DrawImageBorder().
*/
protected function GetImageBorderWidth()
{
if ($this->image_border_type == 'none')
return 0; // No border
if (!empty($this->image_border_width))
return $this->image_border_width; // Specified border width
if ($this->image_border_type == 'raised')
return 2; // Default for raised border is 2 pixels.
return 1; // Default for other border types is 1 pixel.
}
/*
* Draws a border around the final image.
* Note: 'plain' draws a flat border using the dark shade of the border color.
* This probably should have been written to use the actual border color, but
* it is too late to fix it without changing plot appearances. Therefore a
* new type 'solid' was added to use the SetImageBorderColor color.
*/
protected function DrawImageBorder()
{
// Do nothing if already drawn, or if no border has been set.
if ($this->image_border_type == 'none' || !empty($this->done['border']))
return TRUE;
$width = $this->GetImageBorderWidth();
$color1 = $this->ndx_i_border;
$color2 = $this->ndx_i_border_dark;
$ex = $this->image_width - 1;
$ey = $this->image_height - 1;
switch ($this->image_border_type) {
case 'raised':
// Top and left lines use border color, right and bottom use the darker shade.
// Drawing order matters in the upper right and lower left corners.
for ($i = 0; $i < $width; $i++, $ex--, $ey--) {
imageline($this->img, $i, $i, $ex, $i, $color1); // Top
imageline($this->img, $ex, $i, $ex, $ey, $color2); // Right
imageline($this->img, $i, $i, $i, $ey, $color1); // Left
imageline($this->img, $i, $ey, $ex, $ey, $color2); // Bottom
}
break;
case 'plain': // See note above re colors
$color1 = $color2;
// Fall through
case 'solid':
for ($i = 0; $i < $width; $i++, $ex--, $ey--) {
imagerectangle($this->img, $i, $i, $ex, $ey, $color1);
}
break;
default:
return $this->PrintError(
"DrawImageBorder(): unknown image_border_type: '$this->image_border_type'");
}
$this->done['border'] = TRUE; // Border should only be drawn once per image.
return TRUE;
}
/*
* Draws the main title on the graph.
* The title must not be drawn more than once (in the case of multiple plots
* on the image), because TTF text antialiasing makes it look bad.
*/
protected function DrawTitle()
{
if (!empty($this->done['title']) || $this->title_txt === '')
return TRUE;
// Center of the image:
$xpos = $this->image_width / 2;
// Place it at almost at the top
$ypos = $this->title_offset;
$this->DrawText($this->fonts['title'], 0, $xpos, $ypos,
$this->ndx_title_color, $this->title_txt, 'center', 'top');
$this->done['title'] = TRUE;
return TRUE;
}
/*
* Draws the X-Axis Title
*/
protected function DrawXTitle()
{
if ($this->x_title_pos == 'none')
return TRUE;
// Center of the plot
$xpos = ($this->plot_area[2] + $this->plot_area[0]) / 2;
// Upper title
if ($this->x_title_pos == 'plotup' || $this->x_title_pos == 'both') {
$ypos = $this->plot_area[1] - $this->x_title_top_offset;
$this->DrawText($this->fonts['x_title'], 0, $xpos, $ypos, $this->ndx_x_title_color,
$this->x_title_txt, 'center', 'bottom');
}
// Lower title
if ($this->x_title_pos == 'plotdown' || $this->x_title_pos == 'both') {
$ypos = $this->plot_area[3] + $this->x_title_bot_offset;
$this->DrawText($this->fonts['x_title'], 0, $xpos, $ypos, $this->ndx_x_title_color,
$this->x_title_txt, 'center', 'top');
}
return TRUE;
}
/*
* Draws the Y-Axis Title
*/
protected function DrawYTitle()
{
if ($this->y_title_pos == 'none')
return TRUE;
// Center the title vertically to the plot area
$ypos = ($this->plot_area[3] + $this->plot_area[1]) / 2;
if ($this->y_title_pos == 'plotleft' || $this->y_title_pos == 'both') {
$xpos = $this->plot_area[0] - $this->y_title_left_offset;
$this->DrawText($this->fonts['y_title'], 90, $xpos, $ypos, $this->ndx_y_title_color,
$this->y_title_txt, 'right', 'center');
}
if ($this->y_title_pos == 'plotright' || $this->y_title_pos == 'both') {
$xpos = $this->plot_area[2] + $this->y_title_right_offset;
$this->DrawText($this->fonts['y_title'], 90, $xpos, $ypos, $this->ndx_y_title_color,
$this->y_title_txt, 'left', 'center');
}
return TRUE;
}
/*
* Draw the X axis, including ticks and labels, and X (vertical) grid lines.
*/
protected function DrawXAxis()
{
// Draw ticks, labels and grid
$this->DrawXTicks();
//Draw X Axis at Y = x_axis_y_pixels, unless suppressed (See SetXAxisPosition)
if (empty($this->suppress_x_axis)) {
ImageLine($this->img, $this->plot_area[0]+1, $this->x_axis_y_pixels,
$this->plot_area[2]-1, $this->x_axis_y_pixels, $this->ndx_grid_color);
}
return TRUE;
}
/*
* Draw the Y axis, including ticks and labels, and Y (horizontal) grid lines.
* Horizontal grid lines overwrite horizontal axis with y=0, so call this first, then DrawXAxis()
*/
protected function DrawYAxis()
{
// Draw ticks, labels and grid
$this->DrawYTicks();
// Draw Y axis at X = y_axis_x_pixels, unless suppressed (See SetYAxisPosition)
if (empty($this->suppress_y_axis)) {
ImageLine($this->img, $this->y_axis_x_pixels, $this->plot_area[1],
$this->y_axis_x_pixels, $this->plot_area[3], $this->ndx_grid_color);
}
return TRUE;
}
/*
* Draw one X tick mark and its tick label.
* $which_xlab : Formatted X value for the label.
* $which_xpix : X device coordinate for this tick mark.
*/
protected function DrawXTick($which_xlab, $which_xpix)
{
// Ticks on X axis
if ($this->x_tick_pos == 'xaxis') {
ImageLine($this->img, $which_xpix, $this->x_axis_y_pixels - $this->x_tick_cross,
$which_xpix, $this->x_axis_y_pixels + $this->x_tick_length, $this->ndx_tick_color);
}
// Ticks on top of the Plot Area
if ($this->x_tick_pos == 'plotup' || $this->x_tick_pos == 'both') {
ImageLine($this->img, $which_xpix, $this->plot_area[1] - $this->x_tick_length,
$which_xpix, $this->plot_area[1] + $this->x_tick_cross, $this->ndx_tick_color);
}
// Ticks on bottom of Plot Area
if ($this->x_tick_pos == 'plotdown' || $this->x_tick_pos == 'both') {
ImageLine($this->img, $which_xpix, $this->plot_area[3] + $this->x_tick_length,
$which_xpix, $this->plot_area[3] - $this->x_tick_cross, $this->ndx_tick_color);
}
// Label on X axis
if ($this->x_tick_label_pos == 'xaxis') {
$this->DrawText($this->fonts['x_label'], $this->x_label_angle,
$which_xpix, $this->x_axis_y_pixels + $this->x_label_axis_offset,
$this->ndx_text_color, $which_xlab, 'center', 'top');
}
// Label on top of the Plot Area
if ($this->x_tick_label_pos == 'plotup' || $this->x_tick_label_pos == 'both') {
$this->DrawText($this->fonts['x_label'], $this->x_label_angle,
$which_xpix, $this->plot_area[1] - $this->x_label_top_offset,
$this->ndx_text_color, $which_xlab, 'center', 'bottom');
}
// Label on bottom of the Plot Area
if ($this->x_tick_label_pos == 'plotdown' || $this->x_tick_label_pos == 'both') {
$this->DrawText($this->fonts['x_label'], $this->x_label_angle,
$which_xpix, $this->plot_area[3] + $this->x_label_bot_offset,
$this->ndx_text_color, $which_xlab, 'center', 'top');
}
return TRUE;
}
/*
* Draw one Y tick mark and its tick label. Called from DrawYTicks() and DrawXAxis()
* $which_ylab : Formatted Y value for the label.
* $which_ypix : Y device coordinate for this tick mark.
*/
protected function DrawYTick($which_ylab, $which_ypix)
{
// Ticks on Y axis
if ($this->y_tick_pos == 'yaxis') {
ImageLine($this->img, $this->y_axis_x_pixels - $this->y_tick_length, $which_ypix,
$this->y_axis_x_pixels + $this->y_tick_cross, $which_ypix, $this->ndx_tick_color);
}
// Ticks to the left of the Plot Area
if (($this->y_tick_pos == 'plotleft') || ($this->y_tick_pos == 'both') ) {
ImageLine($this->img, $this->plot_area[0] - $this->y_tick_length, $which_ypix,
$this->plot_area[0] + $this->y_tick_cross, $which_ypix, $this->ndx_tick_color);
}
// Ticks to the right of the Plot Area
if (($this->y_tick_pos == 'plotright') || ($this->y_tick_pos == 'both') ) {
ImageLine($this->img, $this->plot_area[2] + $this->y_tick_length, $which_ypix,
$this->plot_area[2] - $this->y_tick_cross, $which_ypix, $this->ndx_tick_color);
}
// Labels on Y axis
if ($this->y_tick_label_pos == 'yaxis') {
$this->DrawText($this->fonts['y_label'], $this->y_label_angle,
$this->y_axis_x_pixels - $this->y_label_axis_offset, $which_ypix,
$this->ndx_text_color, $which_ylab, 'right', 'center');
}
// Labels to the left of the plot area
if ($this->y_tick_label_pos == 'plotleft' || $this->y_tick_label_pos == 'both') {
$this->DrawText($this->fonts['y_label'], $this->y_label_angle,
$this->plot_area[0] - $this->y_label_left_offset, $which_ypix,
$this->ndx_text_color, $which_ylab, 'right', 'center');
}
// Labels to the right of the plot area
if ($this->y_tick_label_pos == 'plotright' || $this->y_tick_label_pos == 'both') {
$this->DrawText($this->fonts['y_label'], $this->y_label_angle,
$this->plot_area[2] + $this->y_label_right_offset, $which_ypix,
$this->ndx_text_color, $which_ylab, 'left', 'center');
}
return TRUE;
}
/*
* Draws Grid, Ticks and Tick Labels along X-Axis
* Ticks and tick labels can be down of plot only, up of plot only,
* both on up and down of plot, or crossing a user defined X-axis
*
* Original vertical code submitted by Marlin Viss
*/
protected function DrawXTicks()
{
// Sets the line style for IMG_COLOR_STYLED lines (grid)
if ($this->dashed_grid) {
$this->SetDashedStyle($this->ndx_light_grid_color);
$style = IMG_COLOR_STYLED;
} else {
$style = $this->ndx_light_grid_color;
}
// Calculate the tick start, end, and step:
list($x_start, $x_end, $delta_x) = $this->CalcTicks('x');
// Loop, avoiding cumulative round-off errors from $x_tmp += $delta_x
$n = 0;
$x_tmp = $x_start;
while ($x_tmp <= $x_end) {
$xlab = $this->FormatLabel('x', $x_tmp);
$x_pixels = $this->xtr($x_tmp);
// Vertical grid lines
if ($this->draw_x_grid) {
ImageLine($this->img, $x_pixels, $this->plot_area[1], $x_pixels, $this->plot_area[3], $style);
}
// Draw tick mark(s)
$this->DrawXTick($xlab, $x_pixels);
// Step to next X, without accumulating error
$x_tmp = $x_start + ++$n * $delta_x;
}
return TRUE;
}
/*
* Draw the grid, ticks, and tick labels along the Y axis.
* Ticks and tick labels can be left of plot only, right of plot only,
* both on the left and right of plot, or crossing a user defined Y-axis
*/
protected function DrawYTicks()
{
// Sets the line style for IMG_COLOR_STYLED lines (grid)
if ($this->dashed_grid) {
$this->SetDashedStyle($this->ndx_light_grid_color);
$style = IMG_COLOR_STYLED;
} else {
$style = $this->ndx_light_grid_color;
}
// Calculate the tick start, end, and step:
list($y_start, $y_end, $delta_y) = $this->CalcTicks('y');
// Loop, avoiding cumulative round-off errors from $y_tmp += $delta_y
$n = 0;
$y_tmp = $y_start;
while ($y_tmp <= $y_end) {
$ylab = $this->FormatLabel('y', $y_tmp);
$y_pixels = $this->ytr($y_tmp);
// Horizontal grid line
if ($this->draw_y_grid) {
ImageLine($this->img, $this->plot_area[0]+1, $y_pixels, $this->plot_area[2]-1,
$y_pixels, $style);
}
// Draw tick mark(s)
$this->DrawYTick($ylab, $y_pixels);
// Step to next Y, without accumulating error
$y_tmp = $y_start + ++$n * $delta_y;
}
return TRUE;
}
/*
* Draw a border around the plot area. See SetPlotBorderType.
* Note: SetPlotBorderType sets plot_border_type to an array, but
* it won't be an array if it defaults or is set directly (backward compatibility).
*/
protected function DrawPlotBorder()
{
$pbt = (array)$this->plot_border_type;
$sides = 0; // Bitmap: 1=left 2=top 4=right 8=bottom
$map = array('left' => 1, 'plotleft' => 1, 'right' => 4, 'plotright' => 4, 'top' => 2,
'bottom' => 8, 'both' => 5, 'sides' => 5, 'full' => 15, 'none' => 0);
foreach ($pbt as $option) $sides |= $map[$option];
if ($sides == 15) { // Border on all 4 sides
imagerectangle($this->img, $this->plot_area[0], $this->plot_area[1],
$this->plot_area[2], $this->plot_area[3], $this->ndx_grid_color);
} else {
if ($sides & 1) // Left
imageline($this->img, $this->plot_area[0], $this->plot_area[1],
$this->plot_area[0], $this->plot_area[3], $this->ndx_grid_color);
if ($sides & 2) // Top
imageline($this->img, $this->plot_area[0], $this->plot_area[1],
$this->plot_area[2], $this->plot_area[1], $this->ndx_grid_color);
if ($sides & 4) // Right
imageline($this->img, $this->plot_area[2], $this->plot_area[1],
$this->plot_area[2], $this->plot_area[3], $this->ndx_grid_color);
if ($sides & 8) // Bottom
imageline($this->img, $this->plot_area[0], $this->plot_area[3],
$this->plot_area[2], $this->plot_area[3], $this->ndx_grid_color);
}
return TRUE;
}
/*
* Draw the data value label associated with a point in the plot.
* These are labels that show the value (dependent variable, usually Y) of the data point,
* and are drawn within the plot area (not to be confused with axis data labels).
*
* $x_or_y : Specify 'x' or 'y' labels. This selects font, angle, and formatting.
* $x_world, $y_world : World coordinates of the text (see also x/y_adjustment).
* $text : The text to draw, after formatting with FormatLabel().
* $halign, $valign : Selects from 9-point text alignment.
* $x_adjustment, $y_adjustment : Text position offsets, in device coordinates.
* $min_width, $min_height : If supplied, suppress the text if it will not fit.
* Returns True, if the text was drawn, or False, if it will not fit.
*/
protected function DrawDataValueLabel($x_or_y, $x_world, $y_world, $text, $halign, $valign,
$x_adjustment=0, $y_adjustment=0, $min_width=NULL, $min_height=NULL)
{
if ($x_or_y == 'x') {
$angle = $this->x_data_label_angle;
$font = $this->fonts['x_label'];
$formatted_text = $this->FormatLabel('xd', $text);
} else { // Assumed 'y'
$angle = $this->y_data_label_angle;
$font = $this->fonts['y_label'];
$formatted_text = $this->FormatLabel('yd', $text);
}
$color = $this->ndx_title_color; // Currently this is the same for X and Y labels
// Check to see if the text fits in the available space, if requested.
if (isset($min_width) || isset($min_height)) {
list($width, $height) = $this->SizeText($font, $angle, $formatted_text);
if ((isset($min_width) && ($min_width - $width) < 2)
|| (isset($min_height) && ($min_height - $height) < 2))
return FALSE;
}
$this->DrawText($font, $angle, $this->xtr($x_world) + $x_adjustment,
$this->ytr($y_world) + $y_adjustment,
$color, $formatted_text, $halign, $valign);
return TRUE;
}
/*
* Draws the axis data label associated with a point in the plot.
* This is different from x_labels drawn by DrawXTicks() and care
* should be taken not to draw both, as they'd probably overlap.
* Calling of this function in DrawLines(), etc is decided after x_data_label_pos value.
* Leave the last parameter out, to avoid the drawing of vertical lines, no matter
* what the setting is (for plots that need it, like DrawSquared())
*/
protected function DrawXDataLabel($xlab, $xpos, $row=FALSE)
{
$xlab = $this->FormatLabel('xd', $xlab);
// Labels below the plot area
if ($this->x_data_label_pos == 'plotdown' || $this->x_data_label_pos == 'both')
$this->DrawText($this->fonts['x_label'], $this->x_data_label_angle,
$xpos, $this->plot_area[3] + $this->x_label_bot_offset,
$this->ndx_text_color, $xlab, 'center', 'top');
// Labels above the plot area
if ($this->x_data_label_pos == 'plotup' || $this->x_data_label_pos == 'both')
$this->DrawText($this->fonts['x_label'], $this->x_data_label_angle,
$xpos, $this->plot_area[1] - $this->x_label_top_offset,
$this->ndx_text_color, $xlab, 'center', 'bottom');
// $row=0 means this is the first row. $row=FALSE means don't do any rows.
if ($row !== FALSE && $this->draw_x_data_label_lines)
$this->DrawXDataLine($xpos, $row);
return TRUE;
}
/*
* Draw a data label along the Y axis or side.
* This is used by horizontal plots.
*/
protected function DrawYDataLabel($ylab, $ypos)
{
$ylab = $this->FormatLabel('yd', $ylab);
// Labels left of the plot area
if ($this->y_data_label_pos == 'plotleft' || $this->y_data_label_pos == 'both')
$this->DrawText($this->fonts['y_label'], $this->y_data_label_angle,
$this->plot_area[0] - $this->y_label_left_offset, $ypos,
$this->ndx_text_color, $ylab, 'right', 'center');
// Labels right of the plot area
if ($this->y_data_label_pos == 'plotright' || $this->y_data_label_pos == 'both')
$this->DrawText($this->fonts['y_label'], $this->y_data_label_angle,
$this->plot_area[2] + $this->y_label_right_offset, $ypos,
$this->ndx_text_color, $ylab, 'left', 'center');
return TRUE;
}
/*
* Draws Vertical lines from data points up and down.
* Which lines are drawn depends on the value of x_data_label_pos,
* and whether this is at all done or not, on draw_x_data_label_lines
*
* $xpos : position in pixels of the line.
* $row : index of the data row being drawn.
*/
protected function DrawXDataLine($xpos, $row)
{
// Sets the line style for IMG_COLOR_STYLED lines (grid)
if ($this->dashed_grid) {
$this->SetDashedStyle($this->ndx_light_grid_color);
$style = IMG_COLOR_STYLED;
} else {
$style = $this->ndx_light_grid_color;
}
if ($this->x_data_label_pos == 'both') {
// Lines from the bottom up
ImageLine($this->img, $xpos, $this->plot_area[3], $xpos, $this->plot_area[1], $style);
} elseif ($this->x_data_label_pos == 'plotdown' && isset($this->data_max[$row])) {
// Lines from the bottom of the plot up to the max Y value at this X:
$ypos = $this->ytr($this->data_max[$row]);
ImageLine($this->img, $xpos, $ypos, $xpos, $this->plot_area[3], $style);
} elseif ($this->x_data_label_pos == 'plotup' && isset($this->data_min[$row])) {
// Lines from the top of the plot down to the min Y value at this X:
$ypos = $this->ytr($this->data_min[$row]);
ImageLine($this->img, $xpos, $this->plot_area[1], $xpos, $ypos, $style);
}
return TRUE;
}
/////////////////////////////////////////////
/////////////// LEGEND
/////////////////////////////////////////////
/*
* Set text to display in the graph's legend.
* $which_leg : Array of strings for the complete legend, or a single string
* to be appended to the legend.
* Or NULL (or an empty array) to cancel the legend.
*/
function SetLegend($which_leg)
{
if (is_array($which_leg)) { // use array (or cancel, if empty array)
$this->legend = $which_leg;
} elseif (!is_null($which_leg)) { // append string
$this->legend[] = $which_leg;
} else {
$this->legend = ''; // Reinitialize to empty, meaning no legend.
}
return TRUE;
}
/*
* Specifies the position of the legend's upper/leftmost corner, in pixel (device) coordinates.
* Both X and Y must be provided, or both omitted (or use NULL) to restore auto-positioning.
*/
function SetLegendPixels($which_x=NULL, $which_y=NULL)
{
return $this->SetLegendPosition(0, 0, 'image', 0, 0, $which_x, $which_y);
}
/*
* Specifies the position of the legend's upper/leftmost corner, in world (data space) coordinates.
*/
function SetLegendWorld($which_x, $which_y)
{
return $this->SetLegendPosition(0, 0, 'world', $which_x, $which_y);
}
/*
* Specifies the position of the legend. This includes SetLegendWorld(), SetLegendPixels(), and
* additional choices using relative coordinates, with optional pixel offset.
* $x, $y : Relative coordinates of a point on the legend box. (See below)
* $relative_to : What to position the legend relative to: 'image', 'plot', 'world', or 'title'.
* $x_base, $y_base : Base point for positioning.
* If $relative_to is 'world', then this is a world coordinate position.
* Otherwise, this is a relative coordinate position on the $relative_to element.
* $x_offset, $y_offset : Additional legend box offset in device coordinates (pixels).
* The legend is positioned so that point ($x,$y) is at ($x_base, $y_base).
* 'Relative coordinates' means: (0,0) is the upper left corner, and (1,1) is the lower right corner
* of the element (legend, image, plot, or title area), regardless of its size. These are floating
* point values, each usually in the range [0,1], but they can be negative or greater than 1.
* If any of x, y, x_offset, or y_offset are NULL, default legend positioning is restored.
*/
function SetLegendPosition($x, $y, $relative_to, $x_base, $y_base, $x_offset = 0, $y_offset = 0)
{
// Special case: NULL means restore the default positioning.
if (!isset($x, $y, $x_offset, $y_offset)) {
unset($this->legend_pos);
} else {
$mode = $this->CheckOption($relative_to, 'image, plot, title, world', __FUNCTION__);
if (empty($mode))
return FALSE;
// Save all values for use by GetLegendPosition()
$this->legend_pos = compact('x', 'y', 'mode', 'x_base', 'y_base', 'x_offset', 'y_offset');
}
return TRUE;
}
/*
* Set legend text alignment, color box alignment, and style options.
* $text_align : Alignment of the text, 'left' or 'right'.
* $colorbox_align : Alignment of the color boxes, 'left', 'right', 'none', or missing/empty.
* If missing or empty, the same alignment as $text_align is used. Color box is positioned first.
*/
function SetLegendStyle($text_align, $colorbox_align = '')
{
$this->legend_text_align = $this->CheckOption($text_align, 'left, right', __FUNCTION__);
if (empty($colorbox_align))
$this->legend_colorbox_align = $this->legend_text_align;
else
$this->legend_colorbox_align = $this->CheckOption($colorbox_align, 'left, right, none',
__FUNCTION__);
return ((boolean)$this->legend_text_align && (boolean)$this->legend_colorbox_align);
}
/*
* Use color boxes or point shapes (for points and linepoints plots only) in the legend.
* $use_shapes : True to use point shapes, false to use color boxes.
*/
function SetLegendUseShapes($use_shapes)
{
$this->legend_use_shapes = (bool)$use_shapes;
return TRUE;
}
/*
* Get legend sizing parameters.
* This is used internally by DrawLegend(), and also by the public GetLegendSize().
* It returns information based on any SetLegend*() calls already made. It does not use
* legend position or data scaling, so it can be called before data scaling is set up.
* Returns an associative array with these entries describing legend sizing:
* 'width', 'height' : Overall legend box size in pixels.
* 'char_w', 'char_h' : Width and height of 'E' in legend text font. (Used to size color boxes)
* 'v_margin' : Inside margin for legend
* 'text_align', 'colorbox_align' : Same as the class variables, with default applied.
* 'draw_colorbox' : True if color boxes will be drawn.
* 'dot_height' : Height of color boxes (even if not drawn), for line spacing.
* 'colorbox_width' : Width of color boxes.
*/
protected function GetLegendSizeParams()
{
$font = &$this->fonts['legend']; // Shortcut to font info array
// Find maximum legend label line width.
$max_width = 0;
foreach ($this->legend as $line) {
list($width, $unused) = $this->SizeText($font, 0, $line);
if ($width > $max_width) $max_width = $width;
}
// Font parameters are used to size the color boxes:
$char_w = $font['width'];
$char_h = $font['height'];
$line_spacing = $this->GetLineSpacing($font);
// Apply defaults to text alignment and colorbox alignment variables:
$text_align = isset($this->legend_text_align) ? $this->legend_text_align : 'right';
$colorbox_align = isset($this->legend_colorbox_align) ? $this->legend_colorbox_align : 'right';
$draw_colorbox = ($colorbox_align != 'none');
// Sizing parameters:
$v_margin = $char_h / 2; // Between vertical borders and labels
$dot_height = $char_h + $line_spacing; // Height of the color boxes (even if not drawn)
$colorbox_width = $char_w; // Base color box width
if (isset($this->legend_colorbox_width))
$colorbox_width *= $this->legend_colorbox_width; // Adjustment to color box width
// Calculate overall legend box width and height.
// Width is e.g.: "| space colorbox space text space |" where each space adds $char_w,
// and colorbox (if drawn) adds $char_w * its width adjustment.
if ($draw_colorbox) {
$width = $max_width + 3 * $char_w + $colorbox_width;
} else {
$width = $max_width + 2 * $char_w;
}
$height = $dot_height * count($this->legend) + 2 * $v_margin;
return compact('width', 'height', 'char_w', 'char_h', 'v_margin',
'text_align', 'colorbox_align', 'draw_colorbox', 'dot_height', 'colorbox_width');
}
/*
* Get legend box size. This can be used to adjust the plot margins, for example.
* Returns: Array of ($width, $height) of the legend box in pixels.
*/
function GetLegendSize()
{
$params = $this->GetLegendSizeParams();
return array($params['width'], $params['height']);
}
/*
* Get legend location in device coordinates. This is a helper for DrawLegend, and is only
* called if there is a legend. See SetLegendWorld(), SetLegendPixels(), SetLegendPosition().
* $width, $height : Width and height of the legend box.
* Returns: coordinates of the upper left corner of the legend box as an array ($x, $y)
*/
protected function GetLegendPosition($width, $height)
{
// Extract variables set by SetLegend*(): $mode, $x, $y, $x_base, $y_base, $x_offset, $y_offset
if (isset($this->legend_pos['mode']))
extract($this->legend_pos);
else
$mode = ''; // Default legend position mode.
switch ($mode) {
case 'plot': // SetLegendPosition with mode='plot', relative coordinates over plot area.
return array((int)($x_base * $this->plot_area_width - $x * $width)
+ $this->plot_area[0] + $x_offset,
(int)($y_base * $this->plot_area_height - $y * $height)
+ $this->plot_area[1] + $y_offset);
case 'world': // User-defined position in world-coordinates (SetLegendWorld), using x_base, y_base
return array($this->xtr($x_base) + $x_offset - (int)($x * $width),
$this->ytr($y_base) + $y_offset - (int)($y * $height));
case 'image': // SetLegendPosition with mode='image', relative coordinates over image area.
// SetLegendPixels() uses this too, with x=y=0.
return array((int)($x_base * $this->image_width - $x * $width) + $x_offset,
(int)($y_base * $this->image_height - $y * $height) + $y_offset);
case 'title': // SetLegendPosition with mode='title', relative to main title.
// Recalculate main title position/size, since CalcMargins does not save it. See DrawTitle()
list($title_width, $title_height) = $this->SizeText($this->fonts['title'], 0, $this->title_txt);
$title_x = (int)(($this->image_width - $title_width) / 2);
return array((int)($x_base * $title_width - $x * $width) + $title_x + $x_offset,
(int)($y_base * $title_height - $y * $height) + $this->title_offset + $y_offset);
default: // If mode is unset (or invalid), use default position.
return array ($this->plot_area[2] - $width - $this->safe_margin,
$this->plot_area[1] + $this->safe_margin);
}
}
/*
* Draws the graph legend
* This is called by DrawGraph only if $this->legend is not empty.
* Base code submitted by Marlin Viss
*/
protected function DrawLegend()
{
$font = &$this->fonts['legend']; // Shortcut to font info array
// Calculate legend box sizing parameters:
// See GetLegendSizeParams() to see what variables are set by this.
extract($this->GetLegendSizeParams());
// Get legend box position:
list($box_start_x, $box_start_y) = $this->GetLegendPosition($width, $height);
$box_end_y = $box_start_y + $height;
$box_end_x = $box_start_x + $width;
// Draw outer box
ImageFilledRectangle($this->img, $box_start_x, $box_start_y, $box_end_x, $box_end_y,
$this->ndx_bg_color);
ImageRectangle($this->img, $box_start_x, $box_start_y, $box_end_x, $box_end_y,
$this->ndx_grid_color);
$color_index = 0;
$max_color_index = count($this->ndx_data_colors) - 1;
// Calculate color box and text horizontal positions.
if (!$draw_colorbox) {
if ($text_align == 'left')
$x_pos = $box_start_x + $char_w;
else
$x_pos = $box_end_x - $char_w;
$dot_left_x = 0; // Not used directly if color boxes/shapes are off, but referenced below.
} elseif ($colorbox_align == 'left') {
$dot_left_x = $box_start_x + $char_w;
$dot_right_x = $dot_left_x + $colorbox_width;
if ($text_align == 'left')
$x_pos = $dot_right_x + $char_w;
else
$x_pos = $box_end_x - $char_w;
} else { // $colorbox_align == 'right'
$dot_right_x = $box_end_x - $char_w;
$dot_left_x = $dot_right_x - $colorbox_width;
if ($text_align == 'left')
$x_pos = $box_start_x + $char_w;
else
$x_pos = $dot_left_x - $char_w;
}
// $y_pos is the bottom of each color box. $yc is the vertical center of the color box or
// the point shape (if drawn). The text is centered vertically on $yc.
$y_pos = $box_start_y + $v_margin + $dot_height;
$yc = (int)($y_pos - $dot_height / 2);
$xc = (int)($dot_left_x + $colorbox_width / 2); // Horizontal center for point shape if drawn
$shape_index = 0; // Shape number index, if drawing point shapes
// Option to use point shapes rather than solid boxes. Disallow this if the shapes array
// has not been initialized (see CheckPointParams). Only works with 'points' or 'linepoints' plots.
$use_shapes = !empty($this->legend_use_shapes) && !empty($this->point_counts);
foreach ($this->legend as $leg) {
// Draw text with requested alignment:
$this->DrawText($font, 0, $x_pos, $yc, $this->ndx_text_color, $leg, $text_align, 'center');
if ($draw_colorbox) {
$y1 = $y_pos - $dot_height + 1;
$y2 = $y_pos - 1;
if ($use_shapes) {
// Draw a point shape in the data color
// If plot area background is on, use that as the shape background:
if ($this->draw_plot_area_background) {
ImageFilledRectangle($this->img, $dot_left_x, $y1, $dot_right_x, $y2,
$this->ndx_plot_bg_color);
}
// Draw the shape. DrawShape() takes shape_index modulo number of defined shapes.
$this->DrawShape($xc, $yc, $shape_index++, $this->ndx_data_colors[$color_index]);
} else {
// Draw color boxes:
ImageFilledRectangle($this->img, $dot_left_x, $y1, $dot_right_x, $y2,
$this->ndx_data_colors[$color_index]);
// Draw a rectangle around the box
ImageRectangle($this->img, $dot_left_x, $y1, $dot_right_x, $y2, $this->ndx_text_color);
}
}
$y_pos += $dot_height;
$yc += $dot_height;
if (++$color_index > $max_color_index)
$color_index = 0;
}
return TRUE;
}
/////////////////////////////////////////////
//////////////////// PLOT DRAWING HELPERS
/////////////////////////////////////////////
/*
* Get data color to use for plotting.
* $row, $idx : Index arguments for the current data point.
* &$vars : Variable storage. Caller makes an empty array, and this function uses it.
* &$data_color : Returned result - Color index for the data point.
* $extra : Extra info flag passed through to data color callback.
*/
protected function GetDataColor($row, $idx, &$vars, &$data_color, $extra = 0)
{
// Initialize or extract variables:
if (empty($vars)) {
$custom_color = (bool)$this->GetCallback('data_color');
$num_data_colors = count($this->ndx_data_colors);
$vars = compact('custom_color', 'num_data_colors');
} else {
extract($vars);
}
// Select the colors.
if ($custom_color) {
$col_i = $this->DoCallback('data_color', $row, $idx, $extra); // Custom color index
$data_color = $this->ndx_data_colors[$col_i % $num_data_colors];
} else {
$data_color = $this->ndx_data_colors[$idx];
}
}
/*
* Get data color and error bar color to use for plotting.
* $row, $idx : Index arguments for the current bar.
* &$vars : Variable storage. Caller makes an empty array, and this function uses it.
* &$data_color : Returned result - Color index for the data (bar fill)
* &$error_color : Returned result - Color index for the error bars
* $extra : Extra info flag passed through to data color callback.
*/
protected function GetDataErrorColors($row, $idx, &$vars, &$data_color, &$error_color, $extra = 0)
{
// Initialize or extract variables:
if (empty($vars)) {
$this->NeedErrorBarColors(); // This plot needs error bar colors.
$custom_color = (bool)$this->GetCallback('data_color');
$num_data_colors = count($this->ndx_data_colors);
$num_error_colors = count($this->ndx_error_bar_colors);
$vars = compact('custom_color', 'num_data_colors', 'num_error_colors');
} else {
extract($vars);
}
// Select the colors.
if ($custom_color) {
$col_i = $this->DoCallback('data_color', $row, $idx, $extra); // Custom color index
$data_color = $this->ndx_data_colors[$col_i % $num_data_colors];
$error_color = $this->ndx_error_bar_colors[$col_i % $num_error_colors];
} else {
$data_color = $this->ndx_data_colors[$idx];
$error_color = $this->ndx_error_bar_colors[$idx];
}
}
/*
* Get colors to use for a bar chart. There is a data color, and either a border color
* or a shading color (data dark color).
* $row, $idx : Index arguments for the current bar.
* &$vars : Variable storage. Caller makes an empty array, and this function uses it.
* &$data_color : Returned result - Color index for the data (bar fill).
* &$alt_color : Returned result - Color index for the shading or outline.
*/
protected function GetBarColors($row, $idx, &$vars, &$data_color, &$alt_color)
{
// Initialize or extract variables:
if (empty($vars)) {
if ($this->shading > 0) // This plot needs dark colors if shading is on.
$this->NeedDataDarkColors();
$custom_color = (bool)$this->GetCallback('data_color');
$num_data_colors = count($this->ndx_data_colors);
$num_border_colors = count($this->ndx_data_border_colors);
$vars = compact('custom_color', 'num_data_colors', 'num_border_colors');
} else {
extract($vars);
}
// Select the colors.
if ($custom_color) {
$col_i = $this->DoCallback('data_color', $row, $idx); // Custom color index
$i_data = $col_i % $num_data_colors; // Index for data colors and dark colors
$i_border = $col_i % $num_border_colors; // Index for data borders (if used)
} else {
$i_data = $i_border = $idx;
}
$data_color = $this->ndx_data_colors[$i_data];
if ($this->shading > 0) {
$alt_color = $this->ndx_data_dark_colors[$i_data];
} else {
$alt_color = $this->ndx_data_border_colors[$i_border];
}
}
/*
* Draw a shape (dot, point). This is the bottom half of DrawDot, and is also
* used by legend drawing. Unlike DrawDot this takes device coordinates.
* The list of supported shapes can also be found in SetPointShapes().
* $x, $y - Device coordinates of the center of the shape
* $record - Index into point_shapes[] and point_sizes[]. This is taken modulo the array sizes.
* $color - Shape color to use.
*/
protected function DrawShape($x, $y, $record, $color)
{
$index = $record % $this->point_counts;
$point_size = $this->point_sizes[$index];
$half_point = (int)($point_size / 2);
$x1 = $x - $half_point;
$x2 = $x + $half_point;
$y1 = $y - $half_point;
$y2 = $y + $half_point;
switch ($this->point_shapes[$index]) {
case 'halfline':
ImageLine($this->img, $x1, $y, $x, $y, $color);
break;
case 'line':
ImageLine($this->img, $x1, $y, $x2, $y, $color);
break;
case 'plus':
ImageLine($this->img, $x1, $y, $x2, $y, $color);
ImageLine($this->img, $x, $y1, $x, $y2, $color);
break;
case 'cross':
ImageLine($this->img, $x1, $y1, $x2, $y2, $color);
ImageLine($this->img, $x1, $y2, $x2, $y1, $color);
break;
case 'circle':
ImageArc($this->img, $x, $y, $point_size, $point_size, 0, 360, $color);
break;
case 'dot':
ImageFilledEllipse($this->img, $x, $y, $point_size, $point_size, $color);
break;
case 'diamond':
$arrpoints = array($x1, $y, $x, $y1, $x2, $y, $x, $y2);
ImageFilledPolygon($this->img, $arrpoints, 4, $color);
break;
case 'triangle':
$arrpoints = array($x1, $y, $x2, $y, $x, $y2);
ImageFilledPolygon($this->img, $arrpoints, 3, $color);
break;
case 'trianglemid':
$arrpoints = array($x1, $y1, $x2, $y1, $x, $y);
ImageFilledPolygon($this->img, $arrpoints, 3, $color);
break;
case 'yield':
$arrpoints = array($x1, $y1, $x2, $y1, $x, $y2);
ImageFilledPolygon($this->img, $arrpoints, 3, $color);
break;
case 'delta':
$arrpoints = array($x1, $y2, $x2, $y2, $x, $y1);
ImageFilledPolygon($this->img, $arrpoints, 3, $color);
break;
case 'star':
ImageLine($this->img, $x1, $y, $x2, $y, $color);
ImageLine($this->img, $x, $y1, $x, $y2, $color);
ImageLine($this->img, $x1, $y1, $x2, $y2, $color);
ImageLine($this->img, $x1, $y2, $x2, $y1, $color);
break;
case 'hourglass':
$arrpoints = array($x1, $y1, $x2, $y1, $x1, $y2, $x2, $y2);
ImageFilledPolygon($this->img, $arrpoints, 4, $color);
break;
case 'bowtie':
$arrpoints = array($x1, $y1, $x1, $y2, $x2, $y1, $x2, $y2);
ImageFilledPolygon($this->img, $arrpoints, 4, $color);
break;
case 'target':
ImageFilledRectangle($this->img, $x1, $y1, $x, $y, $color);
ImageFilledRectangle($this->img, $x, $y, $x2, $y2, $color);
ImageRectangle($this->img, $x1, $y1, $x2, $y2, $color);
break;
case 'box':
ImageRectangle($this->img, $x1, $y1, $x2, $y2, $color);
break;
case 'home': /* As in: "home plate" (baseball), also looks sort of like a house. */
$arrpoints = array($x1, $y2, $x2, $y2, $x2, $y, $x, $y1, $x1, $y);
ImageFilledPolygon($this->img, $arrpoints, 5, $color);
break;
case 'up':
ImagePolygon($this->img, array($x, $y1, $x2, $y2, $x1, $y2), 3, $color);
break;
case 'down':
ImagePolygon($this->img, array($x, $y2, $x1, $y1, $x2, $y1), 3, $color);
break;
case 'none': /* Special case, no point shape here */
break;
default: /* Also 'rect' */
ImageFilledRectangle($this->img, $x1, $y1, $x2, $y2, $color);
break;
}
return TRUE;
}
/*
* Draws a styled dot. Uses world coordinates.
* Note: DrawShape() does all the work.
*/
protected function DrawDot($x_world, $y_world, $record, $color)
{
return $this->DrawShape($this->xtr($x_world), $this->ytr($y_world), $record, $color);
}
/*
* Draw a bar (or segment of a bar), with optional shading or border.
* This is used by the bar and stackedbar plots, vertical and horizontal.
* $x1, $y1 : One corner of the bar.
* $x2, $y2 : Other corner of the bar.
* $data_color : Color index to use for the bar fill.
* $alt_color : Color index to use for the shading (if shading is on), else for the border.
* Note the same color is NOT used for shading and border - just the same argument.
* See GetBarColors() for where these arguments come from.
* $shade_top : Shade the top? (Suppressed for downward stack segments except first.)
* $shade_side : Shade the right side? (Suppressed for leftward stack segments except first.)
* Only one of $shade_top or $shade_side can be FALSE. Both default to TRUE.
*/
protected function DrawBar($x1, $y1, $x2, $y2, $data_color, $alt_color,
$shade_top = TRUE, $shade_side = TRUE)
{
// Sort the points so x1,y1 is upper left and x2,y2 is lower right. This
// is needed in order to get the shading right, and imagerectangle may require it.
if ($x1 > $x2) {
$t = $x1; $x1 = $x2; $x2 = $t;
}
if ($y1 > $y2) {
$t = $y1; $y1 = $y2; $y2 = $t;
}
// Draw the bar
ImageFilledRectangle($this->img, $x1, $y1, $x2, $y2, $data_color);
// Draw a shade, or a border.
if (($shade = $this->shading) > 0) {
if ($shade_top && $shade_side) {
$npts = 6;
$pts = array($x1, $y1, $x1 + $shade, $y1 - $shade, $x2 + $shade, $y1 - $shade,
$x2 + $shade, $y2 - $shade, $x2, $y2, $x2, $y1);
} else {
$npts = 4;
if ($shade_top) { // Suppress side shading
$pts = array($x1, $y1, $x1 + $shade, $y1 - $shade, $x2 + $shade, $y1 - $shade, $x2, $y1);
} else { // Suppress top shading
$pts = array($x2, $y2, $x2, $y1, $x2 + $shade, $y1 - $shade, $x2 + $shade, $y2 - $shade);
}
}
ImageFilledPolygon($this->img, $pts, $npts, $alt_color);
} else {
ImageRectangle($this->img, $x1, $y1, $x2,$y2, $alt_color);
}
}
/*
* Draw an Error Bar set. Used by DrawDotsError and DrawLinesError
*/
protected function DrawYErrorBar($x_world, $y_world, $error_height, $error_bar_type, $color)
{
$x1 = $this->xtr($x_world);
$y1 = $this->ytr($y_world);
$y2 = $this->ytr($y_world+$error_height) ;
ImageSetThickness($this->img, $this->error_bar_line_width);
ImageLine($this->img, $x1, $y1 , $x1, $y2, $color);
if ($error_bar_type == 'tee') {
ImageLine($this->img, $x1-$this->error_bar_size, $y2, $x1+$this->error_bar_size, $y2, $color);
}
ImageSetThickness($this->img, 1);
return TRUE;
}
/////////////////////////////////////////////
//////////////////// PLOT DRAWING
/////////////////////////////////////////////
/*
* Draws a pie chart. Data is 'text-data', 'data-data', or 'text-data-single'.
*
* For text-data-single, the data array contains records with an ignored label,
* and one Y value. Each record defines a sector of the pie, as a portion of
* the sum of all Y values.
*
* For text-data and data-data, the data array contains records with an ignored label,
* an ignored X value (for data-data only), and N (N>=1) Y values per record.
* The pie chart will be produced with N segments. The relative size of the first
* sector of the pie is the sum of the first Y data value in each record, etc.
*
* Note: With text-data-single, the data labels could be used, but are not currently.
*
* If there are no valid data points > 0 at all, just draw nothing. It may seem more correct to
* raise an error, but all of the other plot types handle it this way implicitly. DrawGraph
* checks for an empty data array, but this is different: a non-empty data array with no Y values,
* or all Y=0.
*/
protected function DrawPieChart()
{
if (!$this->CheckDataType('text-data, text-data-single, data-data'))
return FALSE;
// Allocate dark colors only if they will be used for shading.
if ($this->shading > 0)
$this->NeedDataDarkColors();
$xpos = $this->plot_area[0] + $this->plot_area_width/2;
$ypos = $this->plot_area[1] + $this->plot_area_height/2;
$diameter = min($this->plot_area_width, $this->plot_area_height);
$radius = $diameter/2;
$num_slices = $this->data_columns; // See CheckDataArray which calculates this for us.
if ($num_slices < 1) return TRUE; // Give up early if there is no data at all.
$sumarr = array_fill(0, $num_slices, 0);
if ($this->datatype_pie_single) {
// text-data-single: One data column per row, one pie slice per row.
for ($i = 0; $i < $num_slices; $i++) {
// $legend[$i] = $this->data[$i][0]; // Note: Labels are not used yet
if (is_numeric($this->data[$i][1]))
$sumarr[$i] = abs($this->data[$i][1]);
}
} else {
// text-data: Sum each column (skipping label), one pie slice per column.
// data-data: Sum each column (skipping X value and label), one pie slice per column.
$skip = ($this->datatype_implied) ? 1 : 2; // Leading values to skip in each row.
for ($i = 0; $i < $this->num_data_rows; $i++) {
for ($j = $skip; $j < $this->num_recs[$i]; $j++) {
if (is_numeric($this->data[$i][$j]))
$sumarr[$j-$skip] += abs($this->data[$i][$j]);
}
}
}
$total = array_sum($sumarr);
if ($total == 0) {
// There are either no valid data points, or all are 0.
// See top comment about why not to make this an error.
return TRUE;
}
if ($this->shading) {
$diam2 = $diameter / 2;
} else {
$diam2 = $diameter;
}
$max_data_colors = count($this->ndx_data_colors);
// Use the Y label format precision, with default value:
if (isset($this->label_format['y']['precision']))
$precision = $this->label_format['y']['precision'];
else
$precision = 1;
for ($h = $this->shading; $h >= 0; $h--) {
$color_index = 0;
$start_angle = 0;
$end_angle = 0;
for ($j = 0; $j < $num_slices; $j++) {
$val = $sumarr[$j];
// For shaded pies: the last one (at the top of the "stack") has a brighter color:
if ($h == 0)
$slicecol = $this->ndx_data_colors[$color_index];
else
$slicecol = $this->ndx_data_dark_colors[$color_index];
$label_txt = $this->number_format(($val / $total * 100), $precision) . '%';
$val = 360 * ($val / $total);
// NOTE that imagefilledarc measures angles CLOCKWISE (go figure why),
// so the pie chart would start clockwise from 3 o'clock, would it not be
// for the reversal of start and end angles in imagefilledarc()
// Also note ImageFilledArc only takes angles in integer degrees, and if the
// the start and end angles match then you get a full circle not a zero-width
// pie. This is bad. So skip any zero-size wedge. On the other hand, we cannot
// let cumulative error from rounding to integer result in missing wedges. So
// keep the running total as a float, and round the angles. It should not
// be necessary to check that the last wedge ends at 360 degrees.
$start_angle = $end_angle;
$end_angle += $val;
// This method of conversion to integer - truncate after reversing it - was
// chosen to match the implicit method of PHPlot<=5.0.4 to get the same slices.
$arc_start_angle = (int)(360 - $start_angle);
$arc_end_angle = (int)(360 - $end_angle);
if ($arc_start_angle > $arc_end_angle) {
$mid_angle = deg2rad($end_angle - ($val / 2));
// Draw the slice
ImageFilledArc($this->img, $xpos, $ypos+$h, $diameter, $diam2,
$arc_end_angle, $arc_start_angle,
$slicecol, IMG_ARC_PIE);
// Draw the labels only once
if ($h == 0) {
// Draw the outline
if (! $this->shading)
ImageFilledArc($this->img, $xpos, $ypos+$h, $diameter, $diam2,
$arc_end_angle, $arc_start_angle, $this->ndx_grid_color,
IMG_ARC_PIE | IMG_ARC_EDGED |IMG_ARC_NOFILL);
// The '* 1.2' trick is to get labels out of the pie chart so there are more
// chances they can be seen in small sectors.
$label_x = $xpos + ($diameter * 1.2 * cos($mid_angle)) * $this->label_scale_position;
$label_y = $ypos+$h - ($diam2 * 1.2 * sin($mid_angle)) * $this->label_scale_position;
$this->DrawText($this->fonts['generic'], 0, $label_x, $label_y, $this->ndx_grid_color,
$label_txt, 'center', 'center');
}
}
if (++$color_index >= $max_data_colors)
$color_index = 0;
} // end for
} // end for
return TRUE;
}
/*
* Draw the points and errors bars for an error plot of types points and linepoints
* Supports only data-data-error format, with each row of the form
* array("title", x, y1, error1+, error1-, y2, error2+, error2-, ...)
* This is called from DrawDots, with data type already checked.
* $paired is true for linepoints error plots, to make sure elements are
* only drawn once. If true, data labels are drawn by DrawLinesError, and error
* bars are drawn by DrawDotsError. (This choice is for backwards compatibility.)
*/
protected function DrawDotsError($paired = FALSE)
{
// Adjust the point shapes and point sizes arrays:
$this->CheckPointParams();
$gcvars = array(); // For GetDataErrorColors, which initializes and uses this.
// Special flag for data color callback to indicate the 'points' part of 'linepoints':
$alt_flag = $paired ? 1 : 0;
for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
$record = 1; // Skip record #0 (title)
$x_now = $this->data[$row][$record++]; // Read it, advance record index
$x_now_pixels = $this->xtr($x_now); // Absolute coordinates.
// Draw X Data labels?
if ($this->x_data_label_pos != 'none' && !$paired)
$this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
// Now go for Y, E+, E-
for ($idx = 0; $record < $this->num_recs[$row]; $idx++) {
if (is_numeric($this->data[$row][$record])) { // Allow for missing Y data
// Select the colors:
$this->GetDataErrorColors($row, $idx, $gcvars, $data_color, $error_color, $alt_flag);
// Y:
$y_now = $this->data[$row][$record++];
$this->DrawDot($x_now, $y_now, $idx, $data_color);
// Error +
$val = $this->data[$row][$record++];
$this->DrawYErrorBar($x_now, $y_now, $val, $this->error_bar_shape, $error_color);
// Error -
$val = $this->data[$row][$record++];
$this->DrawYErrorBar($x_now, $y_now, -$val, $this->error_bar_shape, $error_color);
} else {
$record += 3; // Skip over missing Y and its error values
}
}
}
return TRUE;
}
/*
* Draw a points plot, or the points for a linepoints plot
* Data format can be text-data (label, y1, y2, ...) or data-data (label, x, y1, y2, ...)
* Points plot with error bars (data-data-error format) is redirected to DrawDotsError.
* $paired is true for linepoints plots, to make sure elements are only drawn once.
*/
protected function DrawDots($paired = FALSE)
{
if (!$this->CheckDataType('text-data, data-data, data-data-error'))
return FALSE;
if ($this->datatype_error_bars)
return $this->DrawDotsError($paired); // Redirect for points+errorbars plot
// Adjust the point shapes and point sizes arrays:
$this->CheckPointParams();
$gcvars = array(); // For GetDataColor, which initializes and uses this.
// Special flag for data color callback to indicate the 'points' part of 'linepoints':
$alt_flag = $paired ? 1 : 0;
// Data Value Labels? (Skip if doing the points from a linepoints plot)
$do_dvls = !$paired && $this->CheckDataValueLabels($this->y_data_label_pos,
$dvl_x_off, $dvl_y_off, $dvl_h_align, $dvl_v_align);
for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
$rec = 1; // Skip record #0 (data label)
if ($this->datatype_implied) // Implied X values?
$x_now = 0.5 + $cnt++; // Place text-data at X = 0.5, 1.5, 2.5, etc...
else
$x_now = $this->data[$row][$rec++]; // Read it, advance record index
$x_now_pixels = $this->xtr($x_now);
// Draw X Data labels?
if (!$paired && $this->x_data_label_pos != 'none')
$this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
// Proceed with Y values
for ($idx = 0;$rec < $this->num_recs[$row]; $rec++, $idx++) {
if (is_numeric($this->data[$row][$rec])) { // Allow for missing Y data
$y_now = (double)$this->data[$row][$rec];
// Select the color:
$this->GetDataColor($row, $idx, $gcvars, $data_color, $alt_flag);
// Draw the marker:
$this->DrawDot($x_now, $y_now, $idx, $data_color);
// Draw data value labels?
if ($do_dvls) {
$this->DrawDataValueLabel('y', $x_now, $y_now, $y_now, $dvl_h_align, $dvl_v_align,
$dvl_x_off, $dvl_y_off);
}
}
}
}
return TRUE;
}
/*
* Draw a Thin Bar Line plot, also known as an Impulse plot.
* A clean, fast routine for when you just want charts like stock volume charts.
* Supports data-data and text-data formats for vertical plots,
* and data-data-yx and text-data-yx for horizontal plots.
* Note that although this plot type supports multiple data sets, it rarely makes
* sense to have more than 1, because the lines will overlay.
* This one function does both vertical and horizontal plots. "iv" is used for the
* independent variable (X for vertical plots, Y for horizontal) and "dv" is used
* for the dependent variable (Y for vertical plots, X for horizontal).
*/
protected function DrawThinBarLines()
{
if (!$this->CheckDataType('text-data, data-data, text-data-yx, data-data-yx'))
return FALSE;
$gcvars = array(); // For GetDataColor, which initializes and uses this.
for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
$rec = 1; // Skip record #0 (data label)
if ($this->datatype_implied) // Implied independent variable values?
$iv_now = 0.5 + $cnt++; // Place text-data at 0.5, 1.5, 2.5, etc...
else
$iv_now = $this->data[$row][$rec++]; // Read it, advance record index
if ($this->datatype_swapped_xy) {
$y_now_pixels = $this->ytr($iv_now);
// Draw Y Data labels?
if ($this->y_data_label_pos != 'none')
$this->DrawYDataLabel($this->data[$row][0], $y_now_pixels);
} else {
$x_now_pixels = $this->xtr($iv_now);
// Draw X Data labels?
if ($this->x_data_label_pos != 'none')
$this->DrawXDataLabel($this->data[$row][0], $x_now_pixels);
}
// Proceed with dependent values
for ($idx = 0; $rec < $this->num_recs[$row]; $rec++, $idx++) {
if (is_numeric($this->data[$row][$rec])) { // Allow for missing data
$dv = $this->data[$row][$rec];
ImageSetThickness($this->img, $this->line_widths[$idx]);
// Select the color:
$this->GetDataColor($row, $idx, $gcvars, $data_color);
if ($this->datatype_swapped_xy) {
// Draw a line from user defined y axis position right (or left) to xtr($dv)
ImageLine($this->img, $this->y_axis_x_pixels, $y_now_pixels,
$this->xtr($dv), $y_now_pixels, $data_color);
} else {
// Draw a line from user defined x axis position up (or down) to ytr($dv)
ImageLine($this->img, $x_now_pixels, $this->x_axis_y_pixels,
$x_now_pixels, $this->ytr($dv), $data_color);
}
}
}
}
ImageSetThickness($this->img, 1);
return TRUE;
}
/*
* Draw an 'area' or 'stacked area' plot.
* Both of these fill the area between lines, but in the stacked area graph the Y values
* are accumulated for each X, same as stacked bars. In the regular area graph, the areas
* are filled in order from the X axis up to each Y (so the Y values for each X need to be
* in decreasing order in this case).
* Data format can be text-data (label, y1, y2, ...) or data-data (label, x, y1, y2, ...)
* Notes:
* All Y values must be >= 0. (If any Y<0 the absolute value is used.)
* Missing data points are NOT handled. (They are counted as 0.)
* All rows must have the same number of Y points, or an error image will be produced.
*/
protected function DrawArea($do_stacked = FALSE)
{
if (!$this->CheckDataType('text-data, data-data'))
return FALSE;
$n = $this->num_data_rows; // Number of X values
// These arrays store the device X and Y coordinates for all lines:
$xd = array();
$yd = array();
// Make sure each row has the same number of values. Note records_per_group is max(num_recs).
if ($this->records_per_group != min($this->num_recs)) {
return $this->PrintError("DrawArea(): Data array must contain the same number"
. " of Y values for each X");
}
// Calculate the Y value for each X, and store the device
// coordinates into the xd and yd arrays.
// For stacked area plots, the Y values accumulate.
for ($row = 0; $row < $n; $row++) {
$rec = 1; // Skip record #0 (data label)
if ($this->datatype_implied) // Implied X values?
$x_now = 0.5 + $row; // Place text-data at X = 0.5, 1.5, 2.5, etc...
else
$x_now = $this->data[$row][$rec++]; // Read it, advance record index
$x_now_pixels = $this->xtr($x_now);
if ($this->x_data_label_pos != 'none') // Draw X Data labels?
$this->DrawXDataLabel($this->data[$row][0], $x_now_pixels);
// Store the X value.
// There is an artificial Y value at the axis. For 'area' it goes
// at the end; for stackedarea it goes before the start.
$xd[$row] = $x_now_pixels;
$yd[$row] = array();
if ($do_stacked)
$yd[$row][] = $this->x_axis_y_pixels;
// Store the Y values for this X.
// All Y values are clipped to the x axis which should be zero but can be moved.
$y = 0;
while ($rec < $this->records_per_group) {
if (is_numeric($this->data[$row][$rec])) { // Treat missing values as 0.
$y += abs($this->data[$row][$rec]);
}
$yd[$row][] = $this->ytr(max($this->x_axis_position, $y));
if (!$do_stacked) $y = 0;
$rec++;
}
if (!$do_stacked)
$yd[$row][] = $this->x_axis_y_pixels;
}
// Now draw the filled polygons.
// Note data_columns is the number of Y points (columns excluding label and X), and the
// number of entries in the yd[] arrays is data_columns+1.
$prev_row = 0;
for ($row = 1; $row <= $this->data_columns; $row++) { // 1 extra for X axis artificial row
$pts = array();
// Previous data set forms top (for area) or bottom (for stackedarea):
for ($j = 0; $j < $n; $j++) {
$pts[] = $xd[$j];
$pts[] = $yd[$j][$prev_row];
}
// Current data set forms bottom (for area) or top (for stackedarea):
for ($j = $n- 1; $j >= 0; $j--) {
$pts[] = $xd[$j];
$pts[] = $yd[$j][$row];
}
// Draw it:
ImageFilledPolygon($this->img, $pts, $n * 2, $this->ndx_data_colors[$prev_row]);
$prev_row = $row;
}
return TRUE;
}
/*
* Draw a line plot, or the lines part of a linepoints plot
* Data format can be text-data (label, y1, y2, ...) or data-data (label, x, y1, y2, ...)
* Line plot with error bars (data-data-error format) is redirected to DrawLinesError.
* $paired is true for linepoints plots, to make sure elements are only drawn once.
*/
protected function DrawLines($paired = FALSE)
{
if (!$this->CheckDataType('text-data, data-data, data-data-error'))
return FALSE;
if ($this->datatype_error_bars)
return $this->DrawLinesError($paired); // Redirect for lines+errorbar plot
// Flag array telling if the current point is valid, one element per plot line.
// If start_lines[i] is true, then (lastx[i], lasty[i]) is the previous point.
$start_lines = array_fill(0, $this->data_columns, FALSE);
$gcvars = array(); // For GetDataColor, which initializes and uses this.
// Data Value Labels?
$do_dvls = $this->CheckDataValueLabels($this->y_data_label_pos,
$dvl_x_off, $dvl_y_off, $dvl_h_align, $dvl_v_align);
for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
$record = 1; // Skip record #0 (data label)
if ($this->datatype_implied) // Implied X values?
$x_now = 0.5 + $cnt++; // Place text-data at X = 0.5, 1.5, 2.5, etc...
else
$x_now = $this->data[$row][$record++]; // Read it, advance record index
$x_now_pixels = $this->xtr($x_now); // Absolute coordinates
if ($this->x_data_label_pos != 'none') // Draw X Data labels?
$this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
if (($line_style = $this->line_styles[$idx]) == 'none')
continue; //Allow suppressing entire line, useful with linepoints
if (is_numeric($this->data[$row][$record])) { //Allow for missing Y data
$y_now = (double)$this->data[$row][$record];
$y_now_pixels = $this->ytr($y_now);
if ($start_lines[$idx]) {
// Set line width, revert it to normal at the end
ImageSetThickness($this->img, $this->line_widths[$idx]);
// Select the color:
$this->GetDataColor($row, $idx, $gcvars, $data_color);
if ($line_style == 'dashed') {
$this->SetDashedStyle($data_color);
$data_color = IMG_COLOR_STYLED;
}
ImageLine($this->img, $x_now_pixels, $y_now_pixels,
$lastx[$idx], $lasty[$idx], $data_color);
}
// Draw data value labels?
if ($do_dvls) {
$this->DrawDataValueLabel('y', $x_now, $y_now, $y_now, $dvl_h_align, $dvl_v_align,
$dvl_x_off, $dvl_y_off);
}
$lasty[$idx] = $y_now_pixels;
$lastx[$idx] = $x_now_pixels;
$start_lines[$idx] = TRUE;
} elseif ($this->draw_broken_lines) { // Y data missing, leave a gap.
$start_lines[$idx] = FALSE;
}
} // end for
} // end for
ImageSetThickness($this->img, 1); // Revert to original state for lines to be drawn later.
return TRUE;
}
/*
* Draw lines with error bars for an error plot of types lines and linepoints
* Supports only data-data-error format, with each row of the form
* array("title", x, y1, error1+, error1-, y2, error2+, error2-, ...)
* This is called from DrawLines, with data type already checked.
* $paired is true for linepoints error plots, to make sure elements are
* only drawn once. If true, data labels are drawn by DrawLinesError, and error
* bars are drawn by DrawDotsError. (This choice is for backwards compatibility.)
*/
protected function DrawLinesError($paired = FALSE)
{
$start_lines = array_fill(0, $this->data_columns, FALSE);
$gcvars = array(); // For GetDataErrorColors, which initializes and uses this.
for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
$record = 1; // Skip record #0 (data label)
$x_now = $this->data[$row][$record++]; // Read X value, advance record index
$x_now_pixels = $this->xtr($x_now); // Absolute coordinates.
if ($this->x_data_label_pos != 'none') // Draw X Data labels?
$this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
// Now go for Y, E+, E-
for ($idx = 0; $record < $this->num_recs[$row]; $idx++) {
if (($line_style = $this->line_styles[$idx]) == 'none')
continue; //Allow suppressing entire line, useful with linepoints
if (is_numeric($this->data[$row][$record])) { // Allow for missing Y data
// Select the colors:
$this->GetDataErrorColors($row, $idx, $gcvars, $data_color, $error_color);
// Y
$y_now = $this->data[$row][$record++];
$y_now_pixels = $this->ytr($y_now);
if ($start_lines[$idx]) {
ImageSetThickness($this->img, $this->line_widths[$idx]);
if ($line_style == 'dashed') {
$this->SetDashedStyle($data_color);
$data_color = IMG_COLOR_STYLED;
}
ImageLine($this->img, $x_now_pixels, $y_now_pixels,
$lastx[$idx], $lasty[$idx], $data_color);
}
if ($paired) {
$record += 2; // Skip error bars - done in the 'points' part of 'linepoints'.
} else {
// Error+
$val = $this->data[$row][$record++];
$this->DrawYErrorBar($x_now, $y_now, $val, $this->error_bar_shape, $error_color);
// Error-
$val = $this->data[$row][$record++];
$this->DrawYErrorBar($x_now, $y_now, -$val, $this->error_bar_shape, $error_color);
}
// Update indexes:
$start_lines[$idx] = TRUE; // Tells us if we already drew the first column of points,
// thus having $lastx and $lasty ready for the next column.
$lastx[$idx] = $x_now_pixels;
$lasty[$idx] = $y_now_pixels;
} else {
$record += 3; // Skip over missing Y and its error values
if ($this->draw_broken_lines) {
$start_lines[$idx] = FALSE;
}
}
} // end for
} // end for
ImageSetThickness($this->img, 1); // Revert to original state for lines to be drawn later.
return TRUE;
}
/*
* Draw a Lines+Points plot (linepoints).
* This just uses DrawLines and DrawDots. They handle the error-bar case themselves.
*/
protected function DrawLinePoints()
{
// This check is redundant, as DrawLines and DrawDots do it, but left here as insurance.
if (!$this->CheckDataType('text-data, data-data, data-data-error'))
return FALSE;
$this->DrawLines(TRUE);
$this->DrawDots(TRUE);
return TRUE;
}
/*
* Draw a Squared Line plot.
* Data format can be text-data (label, y1, y2, ...) or data-data (label, x, y1, y2, ...)
* This is based on DrawLines(), with one more line drawn for each point.
*/
protected function DrawSquared()
{
if (!$this->CheckDataType('text-data, data-data'))
return FALSE;
// Flag array telling if the current point is valid, one element per plot line.
// If start_lines[i] is true, then (lastx[i], lasty[i]) is the previous point.
$start_lines = array_fill(0, $this->data_columns, FALSE);
$gcvars = array(); // For GetDataColor, which initializes and uses this.
// Data Value Labels?
$do_dvls = $this->CheckDataValueLabels($this->y_data_label_pos,
$dvl_x_off, $dvl_y_off, $dvl_h_align, $dvl_v_align);
for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
$record = 1; // Skip record #0 (data label)
if ($this->datatype_implied) // Implied X values?
$x_now = 0.5 + $cnt++; // Place text-data at X = 0.5, 1.5, 2.5, etc...
else
$x_now = $this->data[$row][$record++]; // Read it, advance record index
$x_now_pixels = $this->xtr($x_now); // Absolute coordinates
if ($this->x_data_label_pos != 'none') // Draw X Data labels?
$this->DrawXDataLabel($this->data[$row][0], $x_now_pixels); // notice there is no last param.
// Draw Lines
for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
if (is_numeric($this->data[$row][$record])) { // Allow for missing Y data
$y_now = (double)$this->data[$row][$record];
$y_now_pixels = $this->ytr($y_now);
if ($start_lines[$idx]) {
// Set line width, revert it to normal at the end
ImageSetThickness($this->img, $this->line_widths[$idx]);
// Select the color:
$this->GetDataColor($row, $idx, $gcvars, $data_color);
if ($this->line_styles[$idx] == 'dashed') {
$this->SetDashedStyle($data_color);
$data_color = IMG_COLOR_STYLED;
}
ImageLine($this->img, $lastx[$idx], $lasty[$idx],
$x_now_pixels, $lasty[$idx], $data_color);
ImageLine($this->img, $x_now_pixels, $lasty[$idx],
$x_now_pixels, $y_now_pixels, $data_color);
}
// Draw data value labels?
if ($do_dvls) {
$this->DrawDataValueLabel('y', $x_now, $y_now, $y_now, $dvl_h_align, $dvl_v_align,
$dvl_x_off, $dvl_y_off);
}
$lastx[$idx] = $x_now_pixels;
$lasty[$idx] = $y_now_pixels;
$start_lines[$idx] = TRUE;
} elseif ($this->draw_broken_lines) { // Y data missing, leave a gap.
$start_lines[$idx] = FALSE;
}
}
} // end while
ImageSetThickness($this->img, 1);
return TRUE;
}
/*
* Draw a Bar chart
* Supports text-data format, with each row in the form array(label, y1, y2, y3, ...)
* Horizontal bars (text-data-yx format) are sent to DrawHorizBars() instead.
*/
protected function DrawBars()
{
if (!$this->CheckDataType('text-data, text-data-yx'))
return FALSE;
if ($this->datatype_swapped_xy)
return $this->DrawHorizBars();
$this->CalcBarWidths(FALSE, TRUE); // Calculate bar widths for unstacked, vertical
// This is the X offset from the bar group's label center point to the left side of the first bar
// in the group. See also CalcBarWidths above.
$x_first_bar = ($this->data_columns * $this->record_bar_width) / 2 - $this->bar_adjust_gap;
$gcvars = array(); // For GetBarColors, which initializes and uses this.
for ($row = 0; $row < $this->num_data_rows; $row++) {
$record = 1; // Skip record #0 (data label)
$x_now_pixels = $this->xtr(0.5 + $row); // Place text-data at X = 0.5, 1.5, 2.5, etc...
if ($this->x_data_label_pos != 'none') // Draw X Data labels?
$this->DrawXDataLabel($this->data[$row][0], $x_now_pixels);
// Lower left X of first bar in the group:
$x1 = $x_now_pixels - $x_first_bar;
// Draw the bars in the group:
for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
if (is_numeric($this->data[$row][$record])) { // Allow for missing Y data
$y = $this->data[$row][$record];
$x2 = $x1 + $this->actual_bar_width;
if (($upgoing_bar = $y >= $this->x_axis_position)) {
$y1 = $this->ytr($y);
$y2 = $this->x_axis_y_pixels;
} else {
$y1 = $this->x_axis_y_pixels;
$y2 = $this->ytr($y);
}
// Select the colors:
$this->GetBarColors($row, $idx, $gcvars, $data_color, $alt_color);
// Draw the bar, and the shade or border:
$this->DrawBar($x1, $y1, $x2, $y2, $data_color, $alt_color);
// Draw optional data labels above the bars (or below, for negative values).
if ( $this->y_data_label_pos == 'plotin') {
if ($upgoing_bar) {
$v_align = 'bottom';
$y_offset = -5 - $this->shading;
} else {
$v_align = 'top';
$y_offset = 2;
}
$this->DrawDataValueLabel('y', $row+0.5, $y, $y, 'center', $v_align,
($idx + 0.5) * $this->record_bar_width - $x_first_bar, $y_offset);
}
}
// Step to next bar in group:
$x1 += $this->record_bar_width;
} // end for
} // end for
return TRUE;
}
/*
* Draw a Horizontal Bar chart
* Supports only text-data-yx format, with each row in the form array(label, x1, x2, x3, ...)
* Note that the data values are X not Y, and the bars are drawn horizontally.
* This is called from DrawBars, which has already checked the data type.
*/
protected function DrawHorizBars()
{
$this->CalcBarWidths(FALSE, FALSE); // Calculate bar widths for unstacked, vertical
// This is the Y offset from the bar group's label center point to the bottom of the first bar
// in the group. See also CalcBarWidths above.
$y_first_bar = ($this->data_columns * $this->record_bar_width) / 2 - $this->bar_adjust_gap;
$gcvars = array(); // For GetBarColors, which initializes and uses this.
for ($row = 0; $row < $this->num_data_rows; $row++) {
$record = 1; // Skip record #0 (data label)
$y_now_pixels = $this->ytr(0.5 + $row); // Place bars at Y=0.5, 1.5, 2.5, etc...
if ($this->y_data_label_pos != 'none') // Draw Y Data Labels?
$this->DrawYDataLabel($this->data[$row][0], $y_now_pixels);
// Lower left Y of first bar in the group:
$y1 = $y_now_pixels + $y_first_bar;
// Draw the bars in the group:
for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
if (is_numeric($this->data[$row][$record])) { // Allow for missing X data
$x = $this->data[$row][$record];
$y2 = $y1 - $this->actual_bar_width;
if (($rightwards_bar = $x >= $this->y_axis_position)) {
$x1 = $this->xtr($x);
$x2 = $this->y_axis_x_pixels;
} else {
$x1 = $this->y_axis_x_pixels;
$x2 = $this->xtr($x);
}
// Select the colors:
$this->GetBarColors($row, $idx, $gcvars, $data_color, $alt_color);
// Draw the bar, and the shade or border:
$this->DrawBar($x1, $y1, $x2, $y2, $data_color, $alt_color);
// Draw optional data labels to the right of the bars (or left, if the bar
// goes left of the Y axis line).
if ($this->x_data_label_pos == 'plotin') {
if ($rightwards_bar) {
$h_align = 'left';
$x_offset = 5 + $this->shading;
} else {
$h_align = 'right';
$x_offset = -2;
}
$this->DrawDataValueLabel('x', $x, $row+0.5, $x, $h_align, 'center',
$x_offset, $y_first_bar - ($idx + 0.5) * $this->record_bar_width);
}
}
// Step to next bar in group:
$y1 -= $this->record_bar_width;
} // end for
} // end for
return TRUE;
}
/*
* Draw a Stacked Bar chart
* Supports text-data format, with each row in the form array(label, y1, y2, y3, ...)
* Horizontal stacked bars (text-data-yx format) are sent to DrawHorizStackedBars() instead.
* Original stacked bars idea by Laurent Kruk < lolok at users.sourceforge.net >
*/
protected function DrawStackedBars()
{
if (!$this->CheckDataType('text-data, text-data-yx'))
return FALSE;
if ($this->datatype_swapped_xy)
return $this->DrawHorizStackedBars();
$this->CalcBarWidths(TRUE, TRUE); // Calculate bar widths for stacked, vertical
// This is the X offset from the bar's label center point to the left side of the bar.
$x_first_bar = $this->record_bar_width / 2 - $this->bar_adjust_gap;
$gcvars = array(); // For GetBarColors, which initializes and uses this.
// Determine if any data labels are on:
$data_labels_within = ($this->y_data_label_pos == 'plotstack');
$data_labels_end = $data_labels_within || ($this->y_data_label_pos == 'plotin');
$data_label_y_offset = -5 - $this->shading; // For upward labels only.
for ($row = 0; $row < $this->num_data_rows; $row++) {
$record = 1; // Skip record #0 (data label)
$x_now_pixels = $this->xtr(0.5 + $row); // Place text-data at X = 0.5, 1.5, 2.5, etc...
if ($this->x_data_label_pos != 'none') // Draw X Data labels?
$this->DrawXDataLabel($this->data[$row][0], $x_now_pixels);
// Determine bar direction based on 1st non-zero value. Note the bar direction is
// based on zero, not the axis value.
$n_recs = $this->num_recs[$row];
$upward = TRUE; // Initialize this for the case of all segments = 0
for ($i = $record; $i < $n_recs; $i++) {
if (is_numeric($this_y = $this->data[$row][$i]) && $this_y != 0) {
$upward = ($this_y > 0);
break;
}
}
$x1 = $x_now_pixels - $x_first_bar; // Left X of bars in this stack
$x2 = $x1 + $this->actual_bar_width; // Right X of bars in this stack
$wy1 = 0; // World coordinates Y1, current sum of values
$wy2 = $this->x_axis_position; // World coordinates Y2, last drawn value
// Draw bar segments and labels in this stack.
$first = TRUE;
for ($idx = 0; $record < $n_recs; $record++, $idx++) {
// Skip missing Y values. Process Y=0 values due to special case of moved axis.
if (is_numeric($this_y = $this->data[$row][$record])) {
$wy1 += $this_y; // Keep the running total for this bar stack
// Draw nothing if this segment would not increase the bar height.
// Upward bars: draw if wy1>wy2. Downward bars: Draw if wy1<wy2.
if (($wy1 < $wy2) XOR $upward) {
$y1 = $this->ytr($wy1); // Convert to device coordinates. $y1 is outermost value.
$y2 = $this->ytr($wy2); // $y2 is innermost (closest to axis).
// Select the colors:
$this->GetBarColors($row, $idx, $gcvars, $data_color, $alt_color);
// Draw the bar, and the shade or border:
$this->DrawBar($x1, $y1, $x2, $y2, $data_color, $alt_color,
// Only shade the top for upward bars, or the first segment of downward bars:
$upward || $first, TRUE);
// Draw optional data label for this bar segment just inside the end.
// Text value is the current Y, but position is the cumulative Y.
// The label is only drawn if it fits in the segment height |y2-y1|.
if ($data_labels_within) {
$this->DrawDataValueLabel('y', $row+0.5, $wy1, $this_y,
'center', $upward ? 'top' : 'bottom',
0, $upward ? 3 : -3, NULL, abs($y1 - $y2));
}
// Mark the new end of the bar, conditional on segment height > 0.
$wy2 = $wy1;
$first = FALSE;
}
}
} // end for
// Draw optional data label above the bar with the total value.
// Value is wy1 (total value), but position is wy2 (end of the bar stack).
// These differ only with wrong-direction segments, or a stack completely clipped by the axis.
if ($data_labels_end) {
$this->DrawDataValueLabel('y', $row+0.5, $wy2, $wy1, 'center', $upward ? 'bottom' : 'top',
0, $upward ? $data_label_y_offset : 5);
}
} // end for
return TRUE;
}
/*
* Draw a Horizontal Stacked Bar chart
* Supports only text-data-yx format, with each row in the form array(label, x1, x2, x3, ...)
* Note that the data values are X not Y, and the bars are drawn horizontally.
* This is called from DrawStackedBars, which has already checked the data type.
*/
protected function DrawHorizStackedBars()
{
$this->CalcBarWidths(TRUE, FALSE); // Calculate bar widths for stacked, horizontal
// This is the Y offset from the bar's label center point to the bottom of the bar
$y_first_bar = $this->record_bar_width / 2 - $this->bar_adjust_gap;
$gcvars = array(); // For GetBarColors, which initializes and uses this.
// Determine if any data labels are on:
$data_labels_within = ($this->x_data_label_pos == 'plotstack');
$data_labels_end = $data_labels_within || ($this->x_data_label_pos == 'plotin');
$data_label_x_offset = 5 + $this->shading; // For rightward labels only
for ($row = 0; $row < $this->num_data_rows; $row++) {
$record = 1; // Skip record #0 (data label)
$y_now_pixels = $this->ytr(0.5 + $row); // Place bars at Y=0.5, 1.5, 2.5, etc...
if ($this->y_data_label_pos != 'none') // Draw Y Data labels?
$this->DrawYDataLabel($this->data[$row][0], $y_now_pixels);
// Determine bar direction based on 1st non-zero value. Note the bar direction is
// based on zero, not the axis value.
$n_recs = $this->num_recs[$row];
$rightward = TRUE; // Initialize this for the case of all segments = 0
for ($i = $record; $i < $n_recs; $i++) {
if (is_numeric($this_x = $this->data[$row][$i]) && $this_x != 0) {
$rightward = ($this_x > 0);
break;
}
}
// Lower left and upper left Y of the bars in this stack:
$y1 = $y_now_pixels + $y_first_bar; // Lower Y of bars in this stack
$y2 = $y1 - $this->actual_bar_width; // Upper Y of bars in this stack
$wx1 = 0; // World coordinates X1, current sum of values
$wx2 = $this->y_axis_position; // World coordinates X2, last drawn value
// Draw bar segments and labels in this stack.
$first = TRUE;
for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
// Skip missing X values. Process Y=0 values due to special case of moved axis.
if (is_numeric($this_x = $this->data[$row][$record])) {
$wx1 += $this_x; // Keep the running total for this bar stack
// Draw nothing if this segment would not increase the bar length.
// Rightward bars: draw if wx1>wx2. Leftward bars: Draw if wx1<wx2.
if (($wx1 < $wx2) XOR $rightward) {
$x1 = $this->xtr($wx1); // Convert to device coordinates. $x1 is outermost value.
$x2 = $this->xtr($wx2); // $x2 is innermost (closest to axis).
// Select the colors:
$this->GetBarColors($row, $idx, $gcvars, $data_color, $alt_color);
// Draw the bar, and the shade or border:
$this->DrawBar($x1, $y1, $x2, $y2, $data_color, $alt_color,
// Only shade the side for rightward bars, or the first segment of leftward bars:
TRUE, $rightward || $first);
// Draw optional data label for this bar segment just inside the end.
// Text value is the current X, but position is the cumulative X.
// The label is only drawn if it fits in the segment width |x2-x1|.
if ($data_labels_within) {
$this->DrawDataValueLabel('x', $wx1, $row+0.5, $this_x,
$rightward ? 'right' : 'left', 'center',
$rightward ? -3 : 3, 0, abs($x1 - $x2), NULL);
}
// Mark the new end of the bar, conditional on segment width > 0.
$wx2 = $wx1;
$first = FALSE;
}
}
} // end for
// Draw optional data label right of the bar with the total value.
// Value is wx1 (total value), but position is wx2 (end of the bar stack).
// These differ only with wrong-direction segments, or a stack completely clipped by the axis.
if ($data_labels_end) {
$this->DrawDataValueLabel('x', $wx2, $row+0.5, $wx1, $rightward ? 'left' : 'right', 'center',
$rightward ? $data_label_x_offset : -5, 0);
}
} // end for
return TRUE;
}
/*
* Draw a financial "Open/High/Low/Close" (OHLC) plot, including candlestick plots.
* Data format can be text-data (label, Yo, Yh, Yl, Yc) or data-data (label, X, Yo, Yh, Yl, Yc).
* Yo="Opening price", Yc="Closing price", Yl="Low price", Yh="High price".
* Each row must have exactly 4 Y values. No multiple data sets, no missing values.
* There are 3 subtypes, selected by $draw_candles and $always_fill.
* $draw_candles $always_fill Description:
* FALSE N/A A basic OHLC chart with a vertical line for price range, horizontal
* tick marks on left for opening price and right for closing price.
* TRUE FALSE A candlestick plot with filled body indicating close down, outline
* for closing up, and vertical wicks for low and high prices.
* TRUE TRUE A candlestick plot where the candle bodies are always filled.
* These map to 3 plot types per the $plots[] array.
*
* Data color usage: If closes down: If closes up or unchanged:
* Candlestick body, ohlc range line: color 0 color 1
* Candlestick wicks, ohlc tick marks: color 2 color 3
* There are three member variables that control the width (candlestick body or tick marks):
* ohlc_max_width, ohlc_min_width, ohlc_frac_width
* (There is no API to change them at this time.)
*/
protected function DrawOHLC($draw_candles, $always_fill = FALSE)
{
if (!$this->CheckDataType('text-data, data-data'))
return FALSE;
// Assign name of GD function to draw candlestick bodies for stocks that close up.
$draw_body_close_up = $always_fill ? 'imagefilledrectangle' : 'imagerectangle';
// These 3 variables control the calculation of the half-width of the candle body, or length of
// the tick marks. This is scaled based on the plot density, but within tight limits.
$min_width = isset($this->ohlc_min_width) ? $this->ohlc_min_width : 2;
$max_width = isset($this->ohlc_max_width) ? $this->ohlc_max_width : 8;
$width_factor = isset($this->ohlc_frac_width) ? $this->ohlc_frac_width : 0.3;
$dw = max($min_width, min($max_width,
(int)($width_factor * $this->plot_area_width / $this->num_data_rows)));
// Get line widths to use: index 0 for body/stroke, 1 for wick/tick.
list($body_thickness, $wick_thickness) = $this->line_widths;
$gcvars = array(); // For GetDataColor, which initializes and uses this.
for ($row = 0, $cnt = 0; $row < $this->num_data_rows; $row++) {
$record = 1; // Skip record #0 (data label)
if ($this->datatype_implied) // Implied X values?
$x_now = 0.5 + $cnt++; // Place text-data at X = 0.5, 1.5, 2.5, etc...
else
$x_now = $this->data[$row][$record++]; // Read it, advance record index
$x_now_pixels = $this->xtr($x_now); // Convert X to device coordinates
$x_left = $x_now_pixels - $dw;
$x_right = $x_now_pixels + $dw;
if ($this->x_data_label_pos != 'none') // Draw X Data labels?
$this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
// Require and use 4 numeric values in each row.
if ($this->num_recs[$row] - $record != 4
|| !is_numeric($yo = $this->data[$row][$record++])
|| !is_numeric($yh = $this->data[$row][$record++])
|| !is_numeric($yl = $this->data[$row][$record++])
|| !is_numeric($yc = $this->data[$row][$record++])) {
return $this->PrintError("DrawOHLC: row $row must have 4 values.");
}
// Set device coordinates for each value and direction flag:
$yh_pixels = $this->ytr($yh);
$yl_pixels = $this->ytr($yl);
$yc_pixels = $this->ytr($yc);
$yo_pixels = $this->ytr($yo);
$closed_up = $yc >= $yo;
// Get data colors and line thicknesses:
if ($closed_up) {
$this->GetDataColor($row, 1, $gcvars, $body_color); // Color 1 for body, closing up
$this->GetDataColor($row, 3, $gcvars, $ext_color); // Color 3 for wicks/ticks
} else {
$this->GetDataColor($row, 0, $gcvars, $body_color); // Color 0 for body, closing down
$this->GetDataColor($row, 2, $gcvars, $ext_color); // Color 2 for wicks/ticks
}
imagesetthickness($this->img, $body_thickness);
if ($draw_candles) {
// Note: Unlike ImageFilledRectangle, ImageRectangle 'requires' its arguments in
// order with upper left corner first.
if ($closed_up) {
$yb1_pixels = $yc_pixels; // Upper body Y
$yb2_pixels = $yo_pixels; // Lower body Y
$draw_body = $draw_body_close_up;
// Avoid a PHP/GD bug resulting in "T"-shaped ends to zero height unfilled rectangle:
if ($yb1_pixels == $yb2_pixels)
$draw_body = 'imagefilledrectangle';
} else {
$yb1_pixels = $yo_pixels;
$yb2_pixels = $yc_pixels;
$draw_body = 'imagefilledrectangle';
}
// Draw candle body
$draw_body($this->img, $x_left, $yb1_pixels, $x_right, $yb2_pixels, $body_color);
// Draw upper and lower wicks, if they have height. (In device coords, that's dY<0)
imagesetthickness($this->img, $wick_thickness);
if ($yh_pixels < $yb1_pixels) {
imageline($this->img, $x_now_pixels, $yb1_pixels, $x_now_pixels, $yh_pixels, $ext_color);
}
if ($yl_pixels > $yb2_pixels) {
imageline($this->img, $x_now_pixels, $yb2_pixels, $x_now_pixels, $yl_pixels, $ext_color);
}
} else {
// Basic OHLC
imageline($this->img, $x_now_pixels, $yl_pixels, $x_now_pixels, $yh_pixels, $body_color);
imagesetthickness($this->img, $wick_thickness);
imageline($this->img, $x_left, $yo_pixels, $x_now_pixels, $yo_pixels, $ext_color);
imageline($this->img, $x_right, $yc_pixels, $x_now_pixels, $yc_pixels, $ext_color);
}
imagesetthickness($this->img, 1);
}
return TRUE;
}
/*
* Draw the graph.
* This is the function that performs the actual drawing, after all
* the parameters and data are set up.
* It also outputs the finished image, unless told not to.
* Note: It is possible for this to be called multiple times.
*/
function DrawGraph()
{
// Test for missing image, missing data, empty data:
if (!$this->CheckDataArray())
return FALSE; // Error message already reported.
// Set defaults then import plot type configuration:
$draw_axes = TRUE;
$draw_arg = array(); // Default is: no arguments to the drawing function
extract(PHPlot::$plots[$this->plot_type]);
// Allocate colors for the plot:
$this->SetColorIndexes();
// Get maxima and minima for scaling:
if (!$this->FindDataLimits())
return FALSE;
// Set plot area world values (plot_max_x, etc.):
if (!$this->CalcPlotAreaWorld())
return FALSE;
// Calculate X and Y axis positions in World Coordinates:
$this->CalcAxisPositions();
// Process label-related parameters:
$this->CheckLabels();
// Apply grid defaults:
$this->CalcGridSettings();
// Calculate the plot margins, if needed.
// For pie charts, set the $maximize argument to maximize space usage.
$this->CalcMargins(!$draw_axes);
// Calculate the actual plot area in device coordinates:
$this->CalcPlotAreaPixels();
// Calculate the mapping between world and device coordinates:
$this->CalcTranslation();
// Pad color and style arrays to fit records per group:
$this->PadArrays();
$this->DoCallback('draw_setup');
$this->DrawBackground();
$this->DrawImageBorder();
$this->DoCallback('draw_image_background');
$this->DrawPlotAreaBackground();
$this->DoCallback('draw_plotarea_background', $this->plot_area);
$this->DrawTitle();
if ($draw_axes) { // If no axes (pie chart), no axis titles either
$this->DrawXTitle();
$this->DrawYTitle();
}
$this->DoCallback('draw_titles');
if ($draw_axes && ! $this->grid_at_foreground) { // Usually one wants grids to go back, but...
$this->DrawYAxis(); // Y axis must be drawn before X axis (see DrawYAxis())
$this->DrawXAxis();
$this->DoCallback('draw_axes');
}
// Call the plot-type drawing method:
call_user_func_array(array($this, $draw_method), $draw_arg);
$this->DoCallback('draw_graph', $this->plot_area);
if ($draw_axes && $this->grid_at_foreground) { // Usually one wants grids to go back, but...
$this->DrawYAxis(); // Y axis must be drawn before X axis (see DrawYAxis())
$this->DrawXAxis();
$this->DoCallback('draw_axes');
}
if ($draw_axes) {
$this->DrawPlotBorder();
$this->DoCallback('draw_border');
}
if ($this->legend) {
$this->DrawLegend();
$this->DoCallback('draw_legend');
}
$this->DoCallback('draw_all', $this->plot_area);
if ($this->print_image && !$this->PrintImage())
return FALSE;
return TRUE;
}
/////////////////////////////////////////////
////////////////// DEPRECATED METHODS
/////////////////////////////////////////////
/*
* Note on deprecated methods - as these pre-date the PHPlot Reference
* Manual, and there is minimal documentation about them, I have neither
* removed them nor changed them. They are not tested or documented, and
* should not be used.
*/
/*
* Deprecated, use SetYTickPos()
*/
function SetDrawVertTicks($which_dvt)
{
if ($which_dvt != 1)
$this->SetYTickPos('none');
return TRUE;
}
/*
* Deprecated, use SetXTickPos()
*/
function SetDrawHorizTicks($which_dht)
{
if ($which_dht != 1)
$this->SetXTickPos('none');
return TRUE;
}
/*
* Deprecated - use SetNumXTicks()
*/
function SetNumHorizTicks($n)
{
return $this->SetNumXTicks($n);
}
/*
* Deprecated - use SetNumYTicks()
*/
function SetNumVertTicks($n)
{
return $this->SetNumYTicks($n);
}
/*
* Deprecated - use SetXTickIncrement()
*/
function SetHorizTickIncrement($inc)
{
return $this->SetXTickIncrement($inc);
}
/*
* Deprecated - use SetYTickIncrement()
*/
function SetVertTickIncrement($inc)
{
return $this->SetYTickIncrement($inc);
}
/*
* Deprecated - use SetYTickPos()
*/
function SetVertTickPosition($which_tp)
{
return $this->SetYTickPos($which_tp);
}
/*
* Deprecated - use SetXTickPos()
*/
function SetHorizTickPosition($which_tp)
{
return $this->SetXTickPos($which_tp);
}
/*
* Deprecated - use SetFont()
*/
function SetTitleFontSize($which_size)
{
return $this->SetFont('title', $which_size);
}
/*
* Deprecated - use SetFont()
*/
function SetAxisFontSize($which_size)
{
$this->SetFont('x_label', $which_size);
$this->SetFont('y_label', $which_size);
}
/*
* Deprecated - use SetFont()
*/
function SetSmallFontSize($which_size)
{
return $this->SetFont('generic', $which_size);
}
/*
* Deprecated - use SetFont()
*/
function SetXLabelFontSize($which_size)
{
return $this->SetFont('x_title', $which_size);
}
/*
* Deprecated - use SetFont()
*/
function SetYLabelFontSize($which_size)
{
return $this->SetFont('y_title', $which_size);
}
/*
* Deprecated - use SetXTitle()
*/
function SetXLabel($which_xlab)
{
return $this->SetXTitle($which_xlab);
}
/*
* Deprecated - use SetYTitle()
*/
function SetYLabel($which_ylab)
{
return $this->SetYTitle($which_ylab);
}
/*
* Deprecated - use SetXTickLength() and SetYTickLength() instead.
*/
function SetTickLength($which_tl)
{
$this->SetXTickLength($which_tl);
$this->SetYTickLength($which_tl);
return TRUE;
}
/*
* Deprecated - use SetYLabelType()
*/
function SetYGridLabelType($which_yglt)
{
return $this->SetYLabelType($which_yglt);
}
/*
* Deprecated - use SetXLabelType()
*/
function SetXGridLabelType($which_xglt)
{
return $this->SetXLabelType($which_xglt);
}
/*
* Deprecated - use SetYTickLabelPos()
*/
function SetYGridLabelPos($which_yglp)
{
return $this->SetYTickLabelPos($which_yglp);
}
/*
* Deprecated - use SetXTickLabelPos()
*/
function SetXGridLabelPos($which_xglp)
{
return $this->SetXTickLabelPos($which_xglp);
}
/*
* Deprecated - use SetXtitle()
*/
function SetXTitlePos($xpos)
{
$this->x_title_pos = $xpos;
return TRUE;
}
/*
* Deprecated - use SetYTitle()
*/
function SetYTitlePos($xpos)
{
$this->y_title_pos = $xpos;
return TRUE;
}
/*
* Deprecated - use SetXDataLabelPos()
*/
function SetDrawXDataLabels($which_dxdl)
{
if ($which_dxdl == '1' )
$this->SetXDataLabelPos('plotdown');
else
$this->SetXDataLabelPos('none');
}
/*
* Deprecated - use SetPlotAreaPixels()
*/
function SetNewPlotAreaPixels($x1, $y1, $x2, $y2)
{
return $this->SetPlotAreaPixels($x1, $y1, $x2, $y2);
}
/*
* Deprecated - use SetLineWidths().
*/
function SetLineWidth($which_lw)
{
$this->SetLineWidths($which_lw);
if (!$this->error_bar_line_width) {
$this->SetErrorBarLineWidth($which_lw);
}
return TRUE;
}
/*
* Deprecated - use SetPointShapes().
*/
function SetPointShape($which_pt)
{
$this->SetPointShapes($which_pt);
return TRUE;
}
/*
* Deprecated - use SetPointSizes().
*/
function SetPointSize($which_ps)
{
$this->SetPointSizes($which_ps);
return TRUE;
}
}
/*
* The PHPlot_truecolor class extends PHPlot to use GD truecolor images.
*/
class PHPlot_truecolor extends PHPlot
{
/*
* PHPlot Truecolor variation constructor: Create a PHPlot_truecolor object and initialize it.
* Note this does NOT call the parent (PHPlot) constructor. It duplicates the code here.
* Everything is the same as the PHPlot constructor except for imagecreatetruecolor.
*
* Parameters are the same as PHPlot:
* $which_width : Image width in pixels.
* $which_height : Image height in pixels.
* $which_output_file : Filename for output.
* $which_input_file : Path to a file to be used as background.
*/
function __construct($which_width=600, $which_height=400, $which_output_file=NULL, $which_input_file=NULL)
{
$this->SetRGBArray($this->color_array);
if ($which_output_file)
$this->SetOutputFile($which_output_file);
if ($which_input_file) {
$this->SetInputFile($which_input_file);
} else {
$this->image_width = $which_width;
$this->image_height = $which_height;
$this->img = imagecreatetruecolor($this->image_width, $this->image_height);
if (! $this->img)
return $this->PrintError('PHPlot_truecolor(): Could not create image resource.');
}
$this->SetDefaultStyles();
$this->SetDefaultFonts();
}
}
|