This file is indexed.

/usr/lib/python3/dist-packages/xlsxwriter/chart.py is in python3-xlsxwriter 0.7.3-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
###############################################################################
#
# Chart - A class for writing the Excel XLSX Worksheet file.
#
# Copyright 2013-2015, John McNamara, jmcnamara@cpan.org
#
import re
import copy
from warnings import warn

from .shape import Shape
from . import xmlwriter
from .utility import get_rgb_color
from .utility import xl_rowcol_to_cell
from .utility import xl_range_formula
from .utility import supported_datetime
from .utility import datetime_to_excel_datetime
from .utility import quote_sheetname


class Chart(xmlwriter.XMLwriter):
    """
    A class for writing the Excel XLSX Chart file.


    """

    ###########################################################################
    #
    # Public API.
    #
    ###########################################################################

    def __init__(self, options=None):
        """
        Constructor.

        """

        super(Chart, self).__init__()

        self.subtype = None
        self.sheet_type = 0x0200
        self.orientation = 0x0
        self.series = []
        self.embedded = 0
        self.id = -1
        self.series_index = 0
        self.style_id = 2
        self.axis_ids = []
        self.axis2_ids = []
        self.cat_has_num_fmt = 0
        self.requires_category = False
        self.legend_position = 'right'
        self.legend_delete_series = None
        self.legend_font = None
        self.legend_layout = None
        self.cat_axis_position = 'b'
        self.val_axis_position = 'l'
        self.formula_ids = {}
        self.formula_data = []
        self.horiz_cat_axis = 0
        self.horiz_val_axis = 1
        self.protection = 0
        self.chartarea = {}
        self.plotarea = {}
        self.x_axis = {}
        self.y_axis = {}
        self.y2_axis = {}
        self.x2_axis = {}
        self.chart_name = ''
        self.show_blanks = 'gap'
        self.show_hidden = 0
        self.show_crosses = 1
        self.width = 480
        self.height = 288
        self.x_scale = 1
        self.y_scale = 1
        self.x_offset = 0
        self.y_offset = 0
        self.table = None
        self.cross_between = 'between'
        self.default_marker = None
        self.series_gap_1 = None
        self.series_gap_2 = None
        self.series_overlap_1 = None
        self.series_overlap_2 = None
        self.drop_lines = None
        self.hi_low_lines = None
        self.up_down_bars = None
        self.smooth_allowed = False
        self.title_font = None
        self.title_name = None
        self.title_formula = None
        self.title_data_id = None
        self.title_layout = None
        self.title_overlay = None
        self.title_none = False
        self.date_category = False
        self.date_1904 = False
        self.label_positions = {}
        self.label_position_default = ''
        self.already_inserted = False
        self.combined = None
        self.is_secondary = False
        self._set_default_properties()

    def add_series(self, options):
        """
        Add a data series to a chart.

        Args:
            options:  A dictionary of chart series options.

        Returns:
            Nothing.

        """
        # Add a series and it's properties to a chart.

        # Check that the required input has been specified.
        if 'values' not in options:
            warn("Must specify 'values' in add_series()")
            return

        if self.requires_category and 'categories' not in options:
            warn("Must specify 'categories' in add_series() "
                 "for this chart type")

        # Convert list into a formula string.
        values = self._list_to_formula(options.get('values'))
        categories = self._list_to_formula(options.get('categories'))

        # Switch name and name_formula parameters if required.
        name, name_formula = self._process_names(options.get('name'),
                                                 options.get('name_formula'))

        # Get an id for the data equivalent to the range formula.
        cat_id = self._get_data_id(categories, options.get('categories_data'))
        val_id = self._get_data_id(values, options.get('values_data'))
        name_id = self._get_data_id(name_formula, options.get('name_data'))

        # Set the line properties for the series.
        line = Shape._get_line_properties(options.get('line'))

        # Allow 'border' as a synonym for 'line' in bar/column style charts.
        if options.get('border'):
            line = Shape._get_line_properties(options['border'])

        # Set the fill properties for the series.
        fill = Shape._get_fill_properties(options.get('fill'))

        # Set the gradient gradient properties for the series.
        gradient = Shape._get_gradient_properties(options.get('gradient'))

        # Gradient fill overrides solid fill.
        if gradient:
            fill = None

        # Set the marker properties for the series.
        marker = self._get_marker_properties(options.get('marker'))

        # Set the trendline properties for the series.
        trendline = self._get_trendline_properties(options.get('trendline'))

        # Set the line smooth property for the series.
        smooth = options.get('smooth')

        # Set the error bars properties for the series.
        y_error_bars = self._get_error_bars_props(options.get('y_error_bars'))
        x_error_bars = self._get_error_bars_props(options.get('x_error_bars'))

        error_bars = {'x_error_bars': x_error_bars,
                      'y_error_bars': y_error_bars}

        # Set the point properties for the series.
        points = self._get_points_properties(options.get('points'))

        # Set the labels properties for the series.
        labels = self._get_labels_properties(options.get('data_labels'))

        # Set the "invert if negative" fill property.
        invert_if_neg = options.get('invert_if_negative', False)

        # Set the secondary axis properties.
        x2_axis = options.get('x2_axis')
        y2_axis = options.get('y2_axis')

        # Store secondary status for combined charts.
        if x2_axis or y2_axis:
            self.is_secondary = True

        # Set the gap for Bar/Column charts.
        if options.get('gap') is not None:
            if y2_axis:
                self.series_gap_2 = options['gap']
            else:
                self.series_gap_1 = options['gap']

        # Set the overlap for Bar/Column charts.
        if options.get('overlap'):
            if y2_axis:
                self.series_overlap_2 = options['overlap']
            else:
                self.series_overlap_1 = options['overlap']

        # Add the user supplied data to the internal structures.
        series = {
            'values': values,
            'categories': categories,
            'name': name,
            'name_formula': name_formula,
            'name_id': name_id,
            'val_data_id': val_id,
            'cat_data_id': cat_id,
            'line': line,
            'fill': fill,
            'gradient': gradient,
            'marker': marker,
            'trendline': trendline,
            'labels': labels,
            'invert_if_neg': invert_if_neg,
            'x2_axis': x2_axis,
            'y2_axis': y2_axis,
            'points': points,
            'error_bars': error_bars,
            'smooth': smooth
        }

        self.series.append(series)

    def set_x_axis(self, options):
        """
        Set the chart X axis options.

        Args:
            options:  A dictionary of axis options.

        Returns:
            Nothing.

        """
        axis = self._convert_axis_args(self.x_axis, options)

        self.x_axis = axis

    def set_y_axis(self, options):
        """
        Set the chart Y axis options.

        Args:
            options: A dictionary of axis options.

        Returns:
            Nothing.

        """
        axis = self._convert_axis_args(self.y_axis, options)

        self.y_axis = axis

    def set_x2_axis(self, options):
        """
        Set the chart secondary X axis options.

        Args:
            options: A dictionary of axis options.

        Returns:
            Nothing.

        """
        axis = self._convert_axis_args(self.x2_axis, options)

        self.x2_axis = axis

    def set_y2_axis(self, options):
        """
        Set the chart secondary Y axis options.

        Args:
            options: A dictionary of axis options.

        Returns:
            Nothing.

        """
        axis = self._convert_axis_args(self.y2_axis, options)

        self.y2_axis = axis

    def set_title(self, options):
        """
        Set the chart title options.

        Args:
            options: A dictionary of chart title options.

        Returns:
            Nothing.

        """
        name, name_formula = self._process_names(options.get('name'),
                                                 options.get('name_formula'))

        data_id = self._get_data_id(name_formula, options.get('data'))

        self.title_name = name
        self.title_formula = name_formula
        self.title_data_id = data_id

        # Set the font properties if present.
        self.title_font = self._convert_font_args(options.get('name_font'))

        # Set the axis name layout.
        self.title_layout = self._get_layout_properties(options.get('layout'),
                                                        True)
        # Set the title overlay option.
        self.title_overlay = options.get('overlay')

        # Set the automatic title option.
        self.title_none = options.get('none')

    def set_legend(self, options):
        """
        Set the chart legend options.

        Args:
            options: A dictionary of chart legend options.

        Returns:
            Nothing.
        """
        self.legend_position = options.get('position', 'right')
        self.legend_delete_series = options.get('delete_series')
        self.legend_font = self._convert_font_args(options.get('font'))
        self.legend_layout = self._get_layout_properties(options.get('layout'),
                                                         False)
        # Turn off the legend.
        if options.get('none'):
            self.legend_position = 'none'

    def set_plotarea(self, options):
        """
        Set the chart plot area options.

        Args:
            options: A dictionary of chart plot area options.

        Returns:
            Nothing.
        """
        # Convert the user defined properties to internal properties.
        self.plotarea = self._get_area_properties(options)

    def set_chartarea(self, options):
        """
        Set the chart area options.

        Args:
            options: A dictionary of chart area options.

        Returns:
            Nothing.
        """
        # Convert the user defined properties to internal properties.
        self.chartarea = self._get_area_properties(options)

    def set_style(self, style_id):
        """
        Set the chart style type.

        Args:
            style_id: An int representing the chart style.

        Returns:
            Nothing.
        """
        # Set one of the 48 built-in Excel chart styles. The default is 2.
        if style_id is None:
            style_id = 2

        if style_id < 0 or style_id > 48:
            style_id = 2

        self.style_id = style_id

    def show_blanks_as(self, option):
        """
        Set the option for displaying blank data in a chart.

        Args:
            option: A string representing the display option.

        Returns:
            Nothing.
        """
        if not option:
            return

        valid_options = {
            'gap': 1,
            'zero': 1,
            'span': 1,
        }

        if option not in valid_options:
            warn("Unknown show_blanks_as() option '%s'" % option)
            return

        self.show_blanks = option

    def show_hidden_data(self):
        """
        Display data on charts from hidden rows or columns.

        Args:
            option: A string representing the display option.

        Returns:
            Nothing.
        """
        self.show_hidden = 1

    def set_size(self, options):
        """
        Set size or scale of the chart.

        Args:
            options: A dictionary of chart size options.

        Returns:
            Nothing.
        """

        # Set dimensions or scale for the chart.
        self.width = options.get('width', self.width)
        self.height = options.get('height', self.height)
        self.x_scale = options.get('x_scale', 1)
        self.y_scale = options.get('y_scale', 1)
        self.x_offset = options.get('x_offset', 0)
        self.y_offset = options.get('y_offset', 0)

    def set_table(self, options=None):
        """
        Set properties for an axis data table.

        Args:
            options: A dictionary of axis table options.

        Returns:
            Nothing.

        """
        if options is None:
            options = {}

        table = {}

        table['horizontal'] = options.get('horizontal', 1)
        table['vertical'] = options.get('vertical', 1)
        table['outline'] = options.get('outline', 1)
        table['show_keys'] = options.get('show_keys', 0)

        self.table = table

    def set_up_down_bars(self, options=None):
        """
        Set properties for the chart up-down bars.

        Args:
            options: A dictionary of options.

        Returns:
            Nothing.

        """
        if options is None:
            options = {}

        # Defaults.
        up_line = None
        up_fill = None
        down_line = None
        down_fill = None

        # Set properties for 'up' bar.
        if options.get('up'):
            if 'border' in options['up']:
                # Map border to line.
                up_line = Shape._get_line_properties(options['up']['border'])

            if 'line' in options['up']:
                up_line = Shape._get_line_properties(options['up']['line'])

            if 'fill' in options['up']:
                up_fill = Shape._get_line_properties(options['up']['fill'])

        # Set properties for 'down' bar.
        if options.get('down'):
            if 'border' in options['down']:
                # Map border to line.
                down_line = \
                    Shape._get_line_properties(options['down']['border'])

            if 'line' in options['down']:
                down_line = Shape._get_line_properties(options['down']['line'])

            if 'fill' in options['down']:
                down_fill = Shape._get_line_properties(options['down']['fill'])

        self.up_down_bars = {'up': {'line': up_line,
                                    'fill': up_fill,
                                    },
                             'down': {'line': down_line,
                                      'fill': down_fill,
                                      },
                             }

    def set_drop_lines(self, options=None):
        """
        Set properties for the chart drop lines.

        Args:
            options: A dictionary of options.

        Returns:
            Nothing.

        """
        if options is None:
            options = {}

        line = Shape._get_line_properties(options.get('line'))
        fill = Shape._get_fill_properties(options.get('fill'))

        # Set the gradient gradient properties for the series.
        gradient = Shape._get_gradient_properties(options.get('gradient'))

        # Gradient fill overrides solid fill.
        if gradient:
            fill = None

        self.drop_lines = {'line': line, 'fill': fill, 'gradient': gradient}

    def set_high_low_lines(self, options=None):
        """
        Set properties for the chart high-low lines.

        Args:
            options: A dictionary of options.

        Returns:
            Nothing.

        """
        if options is None:
            options = {}

        line = Shape._get_line_properties(options.get('line'))
        fill = Shape._get_fill_properties(options.get('fill'))

        # Set the gradient gradient properties for the series.
        gradient = Shape._get_gradient_properties(options.get('gradient'))

        # Gradient fill overrides solid fill.
        if gradient:
            fill = None

        self.hi_low_lines = {'line': line, 'fill': fill, 'gradient': gradient}

    def combine(self, chart=None):
        """
        Create a combination chart with a secondary chart.

        Args:
            chart: The secondary chart to combine with the primary chart.

        Returns:
            Nothing.

        """
        if chart is None:
            return

        self.combined = chart

    ###########################################################################
    #
    # Private API.
    #
    ###########################################################################

    def _assemble_xml_file(self):
        # Assemble and write the XML file.

        # Write the XML declaration.
        self._xml_declaration()

        # Write the c:chartSpace element.
        self._write_chart_space()

        # Write the c:lang element.
        self._write_lang()

        # Write the c:style element.
        self._write_style()

        # Write the c:protection element.
        self._write_protection()

        # Write the c:chart element.
        self._write_chart()

        # Write the c:spPr element for the chartarea formatting.
        self._write_sp_pr(self.chartarea)

        # Write the c:printSettings element.
        if self.embedded:
            self._write_print_settings()

        # Close the worksheet tag.
        self._xml_end_tag('c:chartSpace')
        # Close the file.
        self._xml_close()

    def _convert_axis_args(self, axis, user_options):
        # Convert user defined axis values into private hash values.
        options = axis['defaults'].copy()
        options.update(user_options)

        name, name_formula = self._process_names(options.get('name'),
                                                 options.get('name_formula'))

        data_id = self._get_data_id(name_formula, options.get('data'))

        axis = {
            'defaults': axis['defaults'],
            'name': name,
            'formula': name_formula,
            'data_id': data_id,
            'reverse': options.get('reverse'),
            'min': options.get('min'),
            'max': options.get('max'),
            'minor_unit': options.get('minor_unit'),
            'major_unit': options.get('major_unit'),
            'minor_unit_type': options.get('minor_unit_type'),
            'major_unit_type': options.get('major_unit_type'),
            'display_units': options.get('display_units'),
            'log_base': options.get('log_base'),
            'crossing': options.get('crossing'),
            'position_axis': options.get('position_axis'),
            'position': options.get('position'),
            'label_position': options.get('label_position'),
            'num_format': options.get('num_format'),
            'num_format_linked': options.get('num_format_linked'),
            'interval_unit': options.get('interval_unit'),
            'text_axis': False,
        }

        if 'visible' in options:
            axis['visible'] = options.get('visible')
        else:
            axis['visible'] = 1

        # Convert the display units.
        axis['display_units'] = self._get_display_units(axis['display_units'])
        axis['display_units_visible'] = \
            options.get('display_units_visible', True)

        # Map major_gridlines properties.
        if (options.get('major_gridlines')
                and options['major_gridlines']['visible']):
            axis['major_gridlines'] = \
                self._get_gridline_properties(options['major_gridlines'])

        # Map minor_gridlines properties.
        if (options.get('minor_gridlines')
                and options['minor_gridlines']['visible']):
            axis['minor_gridlines'] = \
                self._get_gridline_properties(options['minor_gridlines'])

        # Only use the first letter of bottom, top, left or right.
        if axis.get('position'):
            axis['position'] = axis['position'].lower()[0]

        # Set the position for a category axis on or between the tick marks.
        if axis.get('position_axis'):
            if axis['position_axis'] == 'on_tick':
                axis['position_axis'] = 'midCat'
            elif axis['position_axis'] == 'between':
                # Doesn't need to be modified.
                pass
            else:
                # Otherwise use the default value.
                axis['position_axis'] = None

        # Set the category axis as a date axis.
        if options.get('date_axis'):
            self.date_category = True

        # Set the category axis as a text axis.
        if options.get('text_axis'):
            self.date_category = False
            axis['text_axis'] = True

        # Convert datetime args if required.
        if axis.get('min') and supported_datetime(axis['min']):
            axis['min'] = datetime_to_excel_datetime(axis['min'],
                                                     self.date_1904)
        if axis.get('max') and supported_datetime(axis['max']):
            axis['max'] = datetime_to_excel_datetime(axis['max'],
                                                     self.date_1904)
        if axis.get('crossing') and supported_datetime(axis['crossing']):
            axis['crossing'] = datetime_to_excel_datetime(axis['crossing'],
                                                          self.date_1904)

        # Set the font properties if present.
        axis['num_font'] = self._convert_font_args(options.get('num_font'))
        axis['name_font'] = self._convert_font_args(options.get('name_font'))

        # Set the axis name layout.
        axis['name_layout'] = \
            self._get_layout_properties(options.get('name_layout'), True)

        # Set the line properties for the axis.
        axis['line'] = Shape._get_line_properties(options.get('line'))

        # Set the fill properties for the axis.
        axis['fill'] = Shape._get_fill_properties(options.get('fill'))

        # Set the gradient gradient properties for the series.
        axis['gradient'] = \
            Shape._get_gradient_properties(options.get('gradient'))

        # Gradient fill overrides solid fill.
        if axis.get('gradient'):
            axis['fill'] = None

        return axis

    def _convert_font_args(self, options):
        # Convert user defined font values into private dict values.
        if not options:
            return

        font = {
            'name': options.get('name'),
            'color': options.get('color'),
            'size': options.get('size'),
            'bold': options.get('bold'),
            'italic': options.get('italic'),
            'underline': options.get('underline'),
            'pitch_family': options.get('pitch_family'),
            'charset': options.get('charset'),
            'baseline': options.get('baseline', 0),
            'rotation': options.get('rotation'),
        }

        # Convert font size units.
        if font['size']:
            font['size'] = int(font['size'] * 100)

        # Convert rotation into 60,000ths of a degree.
        if font['rotation']:
            font['rotation'] = 60000 * int(font['rotation'])

        return font

    def _list_to_formula(self, data):
        # Convert and list of row col values to a range formula.

        # If it isn't an array ref it is probably a formula already.
        if type(data) is not list:
            return data

        formula = xl_range_formula(*data)

        return formula

    def _process_names(self, name, name_formula):
        # Switch name and name_formula parameters if required.

        if name is not None:
            if isinstance(name, list):
                # Convert an list of values into a name formula.
                cell = xl_rowcol_to_cell(name[1], name[2], True, True)
                name_formula = quote_sheetname(name[0]) + '!' + cell
                name = ''
            elif re.match(r'^=?[^!]+!\$?[A-Z]+\$?[0-9]+', name):
                # Name looks like a formula, use it to set name_formula.
                name_formula = name
                name = ''

        return name, name_formula

    def _get_data_type(self, data):
        # Find the overall type of the data associated with a series.

        # Check for no data in the series.
        if data is None or len(data) == 0:
            return 'none'

        if isinstance(data[0], list):
            return 'multi_str'

        # Determine if data is numeric or strings.
        for token in data:
            if token is None:
                continue

            try:
                float(token)
            except ValueError:
                # Not a number. Assume entire data series is string data.
                return 'str'

        # The series data was all numeric.
        return 'num'

    def _get_data_id(self, formula, data):
        # Assign an id to a each unique series formula or title/axis formula.
        # Repeated formulas such as for categories get the same id. If the
        # series or title has user specified data associated with it then
        # that is also stored. This data is used to populate cached Excel
        # data when creating a chart. If there is no user defined data then
        # it will be populated by the parent Workbook._add_chart_data().

        # Ignore series without a range formula.
        if not formula:
            return

        # Strip the leading '=' from the formula.
        if formula.startswith('='):
            formula = formula.lstrip('=')

        # Store the data id in a hash keyed by the formula and store the data
        # in a separate array with the same id.
        if formula not in self.formula_ids:
            # Haven't seen this formula before.
            formula_id = len(self.formula_data)

            self.formula_data.append(data)
            self.formula_ids[formula] = formula_id
        else:
            # Formula already seen. Return existing id.
            formula_id = self.formula_ids[formula]

            # Store user defined data if it isn't already there.
            if self.formula_data[formula_id] is None:
                self.formula_data[formula_id] = data

        return formula_id

    def _get_marker_properties(self, marker):
        # Convert user marker properties to the structure required internally.

        if not marker:
            return

        # Copy the user defined properties since they will be modified.
        marker = copy.deepcopy(marker)

        types = {
            'automatic': 'automatic',
            'none': 'none',
            'square': 'square',
            'diamond': 'diamond',
            'triangle': 'triangle',
            'x': 'x',
            'star': 'star',
            'dot': 'dot',
            'short_dash': 'dot',
            'dash': 'dash',
            'long_dash': 'dash',
            'circle': 'circle',
            'plus': 'plus',
            'picture': 'picture',
        }

        # Check for valid types.
        marker_type = marker.get('type')

        if marker_type is not None:
            if marker_type == 'automatic':
                marker['automatic'] = 1

            if marker_type in types:
                marker['type'] = types[marker_type]
            else:
                warn("Unknown marker type '%s" % marker_type)
                return

        # Set the line properties for the marker.
        line = Shape._get_line_properties(marker.get('line'))

        # Allow 'border' as a synonym for 'line'.
        if 'border' in marker:
            line = Shape._get_line_properties(marker['border'])

        # Set the fill properties for the marker.
        fill = Shape._get_fill_properties(marker.get('fill'))

        # Set the gradient gradient properties for the series.
        gradient = Shape._get_gradient_properties(marker.get('gradient'))

        # Gradient fill overrides solid fill.
        if gradient:
            fill = None

        marker['line'] = line
        marker['fill'] = fill
        marker['gradient'] = gradient

        return marker

    def _get_trendline_properties(self, trendline):
        # Convert user trendline properties to structure required internally.

        if not trendline:
            return

        # Copy the user defined properties since they will be modified.
        trendline = copy.deepcopy(trendline)

        types = {
            'exponential': 'exp',
            'linear': 'linear',
            'log': 'log',
            'moving_average': 'movingAvg',
            'polynomial': 'poly',
            'power': 'power',
        }

        # Check the trendline type.
        trend_type = trendline.get('type')

        if trend_type in types:
            trendline['type'] = types[trend_type]
        else:
            warn("Unknown trendline type '%s'" % trend_type)
            return

        # Set the line properties for the trendline.
        line = Shape._get_line_properties(trendline.get('line'))

        # Allow 'border' as a synonym for 'line'.
        if 'border' in trendline:
            line = Shape._get_line_properties(trendline['border'])

        # Set the fill properties for the trendline.
        fill = Shape._get_fill_properties(trendline.get('fill'))

        # Set the gradient gradient properties for the series.
        gradient = Shape._get_gradient_properties(trendline.get('gradient'))

        # Gradient fill overrides solid fill.
        if gradient:
            fill = None

        trendline['line'] = line
        trendline['fill'] = fill
        trendline['gradient'] = gradient

        return trendline

    def _get_error_bars_props(self, options):
        # Convert user error bars properties to structure required internally.
        if not options:
            return

        # Default values.
        error_bars = {
            'type': 'fixedVal',
            'value': 1,
            'endcap': 1,
            'direction': 'both'
        }

        types = {
            'fixed': 'fixedVal',
            'percentage': 'percentage',
            'standard_deviation': 'stdDev',
            'standard_error': 'stdErr',
            'custom': 'cust',
        }

        # Check the error bars type.
        error_type = options['type']

        if error_type in types:
            error_bars['type'] = types[error_type]
        else:
            warn("Unknown error bars type '%s" % error_type)
            return

        # Set the value for error types that require it.
        if 'value' in options:
            error_bars['value'] = options['value']

        # Set the end-cap style.
        if 'end_style' in options:
            error_bars['endcap'] = options['end_style']

        # Set the error bar direction.
        if 'direction' in options:
            if options['direction'] == 'minus':
                error_bars['direction'] = 'minus'
            elif options['direction'] == 'plus':
                error_bars['direction'] = 'plus'
            else:
                # Default to 'both'.
                pass

        # Set any custom values.
        error_bars['plus_values'] = options.get('plus_values')
        error_bars['minus_values'] = options.get('minus_values')
        error_bars['plus_data'] = options.get('plus_data')
        error_bars['minus_data'] = options.get('minus_data')

        # Set the line properties for the error bars.
        error_bars['line'] = Shape._get_line_properties(options.get('line'))
        error_bars['fill'] = Shape._get_line_properties(options.get('fill'))

        return error_bars

    def _get_gridline_properties(self, options):
        # Convert user gridline properties to structure required internally.

        # Set the visible property for the gridline.
        gridline = {'visible': options.get('visible')}

        # Set the line properties for the gridline.
        gridline['line'] = Shape._get_line_properties(options.get('line'))
        gridline['fill'] = Shape._get_line_properties(options.get('fill'))

        return gridline

    def _get_labels_properties(self, labels):
        # Convert user labels properties to the structure required internally.

        if not labels:
            return None

        # Copy the user defined properties since they will be modified.
        labels = copy.deepcopy(labels)

        # Map user defined label positions to Excel positions.
        position = labels.get('position')

        if position:
            if position in self.label_positions:
                if position == self.label_position_default:
                    labels['position'] = None
                else:
                    labels['position'] = self.label_positions[position]
            else:
                warn("Unsupported label position '%s' for this chart type"
                     % position)
                return

        # Map the user defined label separator to the Excel separator.
        separator = labels.get('separator')
        separators = {
            ',': ', ',
            ';': '; ',
            '.': '. ',
            "\n": "\n",
            ' ': ' ',
        }

        if separator:
            if separator in separators:
                labels['separator'] = separators[separator]
            else:
                warn("Unsupported label separator")
                return

        # Set the font properties if present.
        labels['font'] = self._convert_font_args(labels.get('font'))

        return labels

    def _get_area_properties(self, options):
        # Convert user area properties to the structure required internally.
        area = {}

        # Set the line properties for the chartarea.
        line = Shape._get_line_properties(options.get('line'))

        # Allow 'border' as a synonym for 'line'.
        if options.get('border'):
            line = Shape._get_line_properties(options['border'])

        # Set the fill properties for the chartarea.
        fill = Shape._get_fill_properties(options.get('fill'))

        # Set the gradient gradient properties for the series.
        gradient = Shape._get_gradient_properties(options.get('gradient'))

        # Gradient fill overrides solid fill.
        if gradient:
            fill = None

        # Set the plotarea layout.
        layout = self._get_layout_properties(options.get('layout'), False)

        area['line'] = line
        area['fill'] = fill
        area['layout'] = layout
        area['gradient'] = gradient

        return area

    def _get_layout_properties(self, args, is_text):
        # Convert user defined layout properties to format used internally.
        layout = {}

        if not args:
            return

        if is_text:
            properties = ('x', 'y')
        else:
            properties = ('x', 'y', 'width', 'height')

        # Check for valid properties.
        for key in args.keys():
            if key not in properties:
                warn("Property '%s' allowed not in layout options" % key)
                return

        # Set the layout properties.
        for prop in properties:
            if prop not in args.keys():
                warn("Property '%s' must be specified in layout options"
                     % prop)
                return

            value = args[prop]

            try:
                float(value)
            except ValueError:
                warn("Property '%s' value '%s' must be numeric in layout" %
                     (prop, value))
                return

            if value < 0 or value > 1:
                warn("Property '%s' value '%s' must be in range "
                     "0 < x <= 1 in layout options" % (prop, value))
                return

            # Convert to the format used by Excel for easier testing
            layout[prop] = "%.17g" % value

        return layout

    def _get_points_properties(self, user_points):
        # Convert user points properties to structure required internally.
        points = []

        if not user_points:
            return

        for user_point in user_points:
            point = {}

            if user_point is not None:

                # Set the line properties for the point.
                line = Shape._get_line_properties(user_point.get('line'))

                # Allow 'border' as a synonym for 'line'.
                if 'border' in user_point:
                    line = Shape._get_line_properties(user_point['border'])

                # Set the fill properties for the chartarea.
                fill = Shape._get_fill_properties(user_point.get('fill'))

                # Set the gradient gradient properties for the series.
                gradient = \
                    Shape._get_gradient_properties(user_point.get('gradient'))

                # Gradient fill overrides solid fill.
                if gradient:
                    fill = None

                point['line'] = line
                point['fill'] = fill
                point['gradient'] = gradient

            points.append(point)

        return points

    def _get_display_units(self, display_units):
        # Convert user defined display units to internal units.
        if not display_units:
            return

        types = {
            'hundreds': 'hundreds',
            'thousands': 'thousands',
            'ten_thousands': 'tenThousands',
            'hundred_thousands': 'hundredThousands',
            'millions': 'millions',
            'ten_millions': 'tenMillions',
            'hundred_millions': 'hundredMillions',
            'billions': 'billions',
            'trillions': 'trillions',
        }

        if display_units in types:
            display_units = types[display_units]
        else:
            warn("Unknown display_units type '%s'" % display_units)
            return

        return display_units

    def _get_primary_axes_series(self):
        # Returns series which use the primary axes.
        primary_axes_series = []

        for series in self.series:
            if not series['y2_axis']:
                primary_axes_series.append(series)

        return primary_axes_series

    def _get_secondary_axes_series(self):
        # Returns series which use the secondary axes.
        secondary_axes_series = []

        for series in self.series:
            if series['y2_axis']:
                secondary_axes_series.append(series)

        return secondary_axes_series

    def _add_axis_ids(self, args):
        # Add unique ids for primary or secondary axes
        chart_id = 5001 + int(self.id)
        axis_count = 1 + len(self.axis2_ids) + len(self.axis_ids)

        id1 = '%04d%04d' % (chart_id, axis_count)
        id2 = '%04d%04d' % (chart_id, axis_count + 1)

        if args['primary_axes']:
            self.axis_ids.append(id1)
            self.axis_ids.append(id2)

        if not args['primary_axes']:
            self.axis2_ids.append(id1)
            self.axis2_ids.append(id2)

    def _set_default_properties(self):
        # Setup the default properties for a chart.

        self.x_axis['defaults'] = {
            'num_format': 'General',
            'major_gridlines': {'visible': 0}
        }

        self.y_axis['defaults'] = {
            'num_format': 'General',
            'major_gridlines': {'visible': 1}
        }

        self.x2_axis['defaults'] = {
            'num_format': 'General',
            'label_position': 'none',
            'crossing': 'max',
            'visible': 0
        }

        self.y2_axis['defaults'] = {
            'num_format': 'General',
            'major_gridlines': {'visible': 0},
            'position': 'right',
            'visible': 1
        }

        self.set_x_axis({})
        self.set_y_axis({})

        self.set_x2_axis({})
        self.set_y2_axis({})

    ###########################################################################
    #
    # XML methods.
    #
    ###########################################################################

    def _write_chart_space(self):
        # Write the <c:chartSpace> element.
        schema = 'http://schemas.openxmlformats.org/'
        xmlns_c = schema + 'drawingml/2006/chart'
        xmlns_a = schema + 'drawingml/2006/main'
        xmlns_r = schema + 'officeDocument/2006/relationships'

        attributes = [
            ('xmlns:c', xmlns_c),
            ('xmlns:a', xmlns_a),
            ('xmlns:r', xmlns_r),
        ]

        self._xml_start_tag('c:chartSpace', attributes)

    def _write_lang(self):
        # Write the <c:lang> element.
        val = 'en-US'

        attributes = [('val', val)]

        self._xml_empty_tag('c:lang', attributes)

    def _write_style(self):
        # Write the <c:style> element.
        style_id = self.style_id

        # Don't write an element for the default style, 2.
        if style_id == 2:
            return

        attributes = [('val', style_id)]

        self._xml_empty_tag('c:style', attributes)

    def _write_chart(self):
        # Write the <c:chart> element.
        self._xml_start_tag('c:chart')

        if self.title_none:
            # Turn off the title.
            self._write_c_auto_title_deleted()
        else:
            # Write the chart title elements.
            if self.title_formula is not None:
                self._write_title_formula(self.title_formula,
                                          self.title_data_id,
                                          None,
                                          self.title_font,
                                          self.title_layout,
                                          self.title_overlay)
            elif self.title_name is not None:
                self._write_title_rich(self.title_name,
                                       None,
                                       self.title_font,
                                       self.title_layout,
                                       self.title_overlay)

        # Write the c:plotArea element.
        self._write_plot_area()

        # Write the c:legend element.
        self._write_legend()

        # Write the c:plotVisOnly element.
        self._write_plot_vis_only()

        # Write the c:dispBlanksAs element.
        self._write_disp_blanks_as()

        self._xml_end_tag('c:chart')

    def _write_disp_blanks_as(self):
        # Write the <c:dispBlanksAs> element.
        val = self.show_blanks

        # Ignore the default value.
        if val == 'gap':
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:dispBlanksAs', attributes)

    def _write_plot_area(self):
        # Write the <c:plotArea> element.
        self._xml_start_tag('c:plotArea')

        # Write the c:layout element.
        self._write_layout(self.plotarea.get('layout'), 'plot')

        # Write  subclass chart type elements for primary and secondary axes.
        self._write_chart_type({'primary_axes': True})
        self._write_chart_type({'primary_axes': False})

        # Configure a combined chart if present.
        second_chart = self.combined
        if second_chart:
            # Secondary axis has unique id otherwise use same as primary.
            if second_chart.is_secondary:
                second_chart.id = 1000 + self.id
            else:
                second_chart.id = self.id

            # Shart the same filehandle for writing.
            second_chart.fh = self.fh

            # Share series index with primary chart.
            second_chart.series_index = self.series_index

            # Write the subclass chart type elements for combined chart.
            second_chart._write_chart_type({'primary_axes': True})
            second_chart._write_chart_type({'primary_axes': False})

        # Write the category and value elements for the primary axes.
        args = {'x_axis': self.x_axis,
                'y_axis': self.y_axis,
                'axis_ids': self.axis_ids}

        if self.date_category:
            self._write_date_axis(args)
        else:
            self._write_cat_axis(args)

        self._write_val_axis(args)

        # Write the category and value elements for the secondary axes.
        args = {'x_axis': self.x2_axis,
                'y_axis': self.y2_axis,
                'axis_ids': self.axis2_ids}

        self._write_val_axis(args)

        # Write the secondary axis for the secondary chart.
        if second_chart and second_chart.is_secondary:
            args = {'x_axis': second_chart.x2_axis,
                    'y_axis': second_chart.y2_axis,
                    'axis_ids': second_chart.axis2_ids}

            second_chart._write_val_axis(args)

        if self.date_category:
            self._write_date_axis(args)
        else:
            self._write_cat_axis(args)

        # Write the c:dTable element.
        self._write_d_table()

        # Write the c:spPr element for the plotarea formatting.
        self._write_sp_pr(self.plotarea)

        self._xml_end_tag('c:plotArea')

    def _write_layout(self, layout, layout_type):
        # Write the <c:layout> element.

        if not layout:
            # Automatic layout.
            self._xml_empty_tag('c:layout')
        else:
            # User defined manual layout.
            self._xml_start_tag('c:layout')
            self._write_manual_layout(layout, layout_type)
            self._xml_end_tag('c:layout')

    def _write_manual_layout(self, layout, layout_type):
        # Write the <c:manualLayout> element.
        self._xml_start_tag('c:manualLayout')

        # Plotarea has a layoutTarget element.
        if layout_type == 'plot':
            self._xml_empty_tag('c:layoutTarget', [('val', 'inner')])

        # Set the x, y positions.
        self._xml_empty_tag('c:xMode', [('val', 'edge')])
        self._xml_empty_tag('c:yMode', [('val', 'edge')])
        self._xml_empty_tag('c:x', [('val', layout['x'])])
        self._xml_empty_tag('c:y', [('val', layout['y'])])

        # For plotarea and legend set the width and height.
        if layout_type != 'text':
            self._xml_empty_tag('c:w', [('val', layout['width'])])
            self._xml_empty_tag('c:h', [('val', layout['height'])])

        self._xml_end_tag('c:manualLayout')

    def _write_chart_type(self, options):
        # Write the chart type element. This method should be overridden
        # by the subclasses.
        return

    def _write_grouping(self, val):
        # Write the <c:grouping> element.
        attributes = [('val', val)]

        self._xml_empty_tag('c:grouping', attributes)

    def _write_series(self, series):
        # Write the series elements.
        self._write_ser(series)

    def _write_ser(self, series):
        # Write the <c:ser> element.
        index = self.series_index
        self.series_index += 1

        self._xml_start_tag('c:ser')

        # Write the c:idx element.
        self._write_idx(index)

        # Write the c:order element.
        self._write_order(index)

        # Write the series name.
        self._write_series_name(series)

        # Write the c:spPr element.
        self._write_sp_pr(series)

        # Write the c:marker element.
        self._write_marker(series['marker'])

        # Write the c:invertIfNegative element.
        self._write_c_invert_if_negative(series['invert_if_neg'])

        # Write the c:dPt element.
        self._write_d_pt(series['points'])

        # Write the c:dLbls element.
        self._write_d_lbls(series['labels'])

        # Write the c:trendline element.
        self._write_trendline(series['trendline'])

        # Write the c:errBars element.
        self._write_error_bars(series['error_bars'])

        # Write the c:cat element.
        self._write_cat(series)

        # Write the c:val element.
        self._write_val(series)

        # Write the c:smooth element.
        if self.smooth_allowed:
            self._write_c_smooth(series['smooth'])

        self._xml_end_tag('c:ser')

    def _write_idx(self, val):
        # Write the <c:idx> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:idx', attributes)

    def _write_order(self, val):
        # Write the <c:order> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:order', attributes)

    def _write_series_name(self, series):
        # Write the series name.

        if series['name_formula'] is not None:
            self._write_tx_formula(series['name_formula'], series['name_id'])
        elif series['name'] is not None:
            self._write_tx_value(series['name'])

    def _write_c_smooth(self, smooth):
        # Write the <c:smooth> element.

        if smooth:
            self._xml_empty_tag('c:smooth', [('val', '1')])

    def _write_cat(self, series):
        # Write the <c:cat> element.
        formula = series['categories']
        data_id = series['cat_data_id']
        data = None

        if data_id is not None:
            data = self.formula_data[data_id]

        # Ignore <c:cat> elements for charts without category values.
        if not formula:
            return

        self._xml_start_tag('c:cat')

        # Check the type of cached data.
        cat_type = self._get_data_type(data)

        if cat_type == 'str':
            self.cat_has_num_fmt = 0
            # Write the c:numRef element.
            self._write_str_ref(formula, data, cat_type)

        elif cat_type == 'multi_str':
            self.cat_has_num_fmt = 0
            # Write the c:numRef element.
            self._write_multi_lvl_str_ref(formula, data)

        else:
            self.cat_has_num_fmt = 1
            # Write the c:numRef element.
            self._write_num_ref(formula, data, cat_type)

        self._xml_end_tag('c:cat')

    def _write_val(self, series):
        # Write the <c:val> element.
        formula = series['values']
        data_id = series['val_data_id']
        data = self.formula_data[data_id]

        self._xml_start_tag('c:val')

        # Unlike Cat axes data should only be numeric.
        # Write the c:numRef element.
        self._write_num_ref(formula, data, 'num')

        self._xml_end_tag('c:val')

    def _write_num_ref(self, formula, data, ref_type):
        # Write the <c:numRef> element.
        self._xml_start_tag('c:numRef')

        # Write the c:f element.
        self._write_series_formula(formula)

        if ref_type == 'num':
            # Write the c:numCache element.
            self._write_num_cache(data)
        elif ref_type == 'str':
            # Write the c:strCache element.
            self._write_str_cache(data)

        self._xml_end_tag('c:numRef')

    def _write_str_ref(self, formula, data, ref_type):
        # Write the <c:strRef> element.

        self._xml_start_tag('c:strRef')

        # Write the c:f element.
        self._write_series_formula(formula)

        if ref_type == 'num':
            # Write the c:numCache element.
            self._write_num_cache(data)
        elif ref_type == 'str':
            # Write the c:strCache element.
            self._write_str_cache(data)

        self._xml_end_tag('c:strRef')

    def _write_multi_lvl_str_ref(self, formula, data):
        # Write the <c:multiLvlStrRef> element.

        if not data:
            return

        self._xml_start_tag('c:multiLvlStrRef')

        # Write the c:f element.
        self._write_series_formula(formula)

        self._xml_start_tag('c:multiLvlStrCache')

        # Write the c:ptCount element.
        count = len(data[-1])
        self._write_pt_count(count)

        for cat_data in reversed(data):

            self._xml_start_tag('c:lvl')

            for i, point in enumerate(cat_data):
                # Write the c:pt element.
                self._write_pt(i, cat_data[i])

            self._xml_end_tag('c:lvl')

        self._xml_end_tag('c:multiLvlStrCache')
        self._xml_end_tag('c:multiLvlStrRef')

    def _write_series_formula(self, formula):
        # Write the <c:f> element.

        # Strip the leading '=' from the formula.
        if formula.startswith('='):
            formula = formula.lstrip('=')

        self._xml_data_element('c:f', formula)

    def _write_axis_ids(self, args):
        # Write the <c:axId> elements for the primary or secondary axes.

        # Generate the axis ids.
        self._add_axis_ids(args)

        if args['primary_axes']:
            # Write the axis ids for the primary axes.
            self._write_axis_id(self.axis_ids[0])
            self._write_axis_id(self.axis_ids[1])
        else:
            # Write the axis ids for the secondary axes.
            self._write_axis_id(self.axis2_ids[0])
            self._write_axis_id(self.axis2_ids[1])

    def _write_axis_id(self, val):
        # Write the <c:axId> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:axId', attributes)

    def _write_cat_axis(self, args):
        # Write the <c:catAx> element. Usually the X axis.
        x_axis = args['x_axis']
        y_axis = args['y_axis']
        axis_ids = args['axis_ids']

        # If there are no axis_ids then we don't need to write this element.
        if axis_ids is None or not len(axis_ids):
            return

        position = self.cat_axis_position
        horiz = self.horiz_cat_axis

        # Overwrite the default axis position with a user supplied value.
        if x_axis.get('position'):
            position = x_axis['position']

        self._xml_start_tag('c:catAx')

        self._write_axis_id(axis_ids[0])

        # Write the c:scaling element.
        self._write_scaling(x_axis.get('reverse'),
                            None,
                            None,
                            None)

        if not x_axis.get('visible'):
            self._write_delete(1)

        # Write the c:axPos element.
        self._write_axis_pos(position, y_axis.get('reverse'))

        # Write the c:majorGridlines element.
        self._write_major_gridlines(x_axis.get('major_gridlines'))

        # Write the c:minorGridlines element.
        self._write_minor_gridlines(x_axis.get('minor_gridlines'))

        # Write the axis title elements.
        if x_axis['formula'] is not None:
            self._write_title_formula(x_axis['formula'],
                                      x_axis['data_id'],
                                      horiz,
                                      x_axis['name_font'],
                                      x_axis['name_layout'])
        elif x_axis['name'] is not None:
            self._write_title_rich(x_axis['name'],
                                   horiz,
                                   x_axis['name_font'],
                                   x_axis['name_layout'])

        # Write the c:numFmt element.
        self._write_cat_number_format(x_axis)

        # Write the c:majorTickMark element.
        self._write_major_tick_mark(x_axis.get('major_tick_mark'))

        # Write the c:tickLblPos element.
        self._write_tick_label_pos(x_axis.get('label_position'))

        # Write the c:spPr element for the axis line.
        self._write_sp_pr(x_axis)

        # Write the axis font elements.
        self._write_axis_font(x_axis.get('num_font'))

        # Write the c:crossAx element.
        self._write_cross_axis(axis_ids[1])

        if self.show_crosses or x_axis.get('visible'):

            # Note, the category crossing comes from the value axis.
            if (y_axis.get('crossing') is None
                    or y_axis.get('crossing') == 'max'):

                # Write the c:crosses element.
                self._write_crosses(y_axis.get('crossing'))
            else:

                # Write the c:crossesAt element.
                self._write_c_crosses_at(y_axis.get('crossing'))

        # Write the c:auto element.
        if not x_axis.get('text_axis'):
            self._write_auto(1)

        # Write the c:labelAlign element.
        self._write_label_align('ctr')

        # Write the c:labelOffset element.
        self._write_label_offset(100)

        # Write the c:tickLblSkip element.
        self._write_c_tick_lbl_skip(x_axis.get('interval_unit'))

        self._xml_end_tag('c:catAx')

    def _write_val_axis(self, args):
        # Write the <c:valAx> element. Usually the Y axis.
        x_axis = args['x_axis']
        y_axis = args['y_axis']
        axis_ids = args['axis_ids']
        position = args.get('position', self.val_axis_position)
        horiz = self.horiz_val_axis

        # If there are no axis_ids then we don't need to write this element.
        if axis_ids is None or not len(axis_ids):
            return

        # Overwrite the default axis position with a user supplied value.
        position = y_axis.get('position') or position

        self._xml_start_tag('c:valAx')

        self._write_axis_id(axis_ids[1])

        # Write the c:scaling element.
        self._write_scaling(y_axis.get('reverse'),
                            y_axis.get('min'),
                            y_axis.get('max'),
                            y_axis.get('log_base'))

        if not y_axis.get('visible'):
            self._write_delete(1)

        # Write the c:axPos element.
        self._write_axis_pos(position, x_axis.get('reverse'))

        # Write the c:majorGridlines element.
        self._write_major_gridlines(y_axis.get('major_gridlines'))

        # Write the c:minorGridlines element.
        self._write_minor_gridlines(y_axis.get('minor_gridlines'))

        # Write the axis title elements.
        if y_axis['formula'] is not None:
            self._write_title_formula(y_axis['formula'],
                                      y_axis['data_id'],
                                      horiz,
                                      y_axis['name_font'],
                                      y_axis['name_layout'])
        elif y_axis['name'] is not None:
            self._write_title_rich(y_axis['name'],
                                   horiz,
                                   y_axis.get('name_font'),
                                   y_axis.get('name_layout'))

        # Write the c:numberFormat element.
        self._write_number_format(y_axis)

        # Write the c:majorTickMark element.
        self._write_major_tick_mark(y_axis.get('major_tick_mark'))

        # Write the c:tickLblPos element.
        self._write_tick_label_pos(y_axis.get('label_position'))

        # Write the c:spPr element for the axis line.
        self._write_sp_pr(y_axis)

        # Write the axis font elements.
        self._write_axis_font(y_axis.get('num_font'))

        # Write the c:crossAx element.
        self._write_cross_axis(axis_ids[0])

        # Note, the category crossing comes from the value axis.
        if x_axis.get('crossing') is None or x_axis['crossing'] == 'max':

            # Write the c:crosses element.
            self._write_crosses(x_axis.get('crossing'))
        else:

            # Write the c:crossesAt element.
            self._write_c_crosses_at(x_axis.get('crossing'))

        # Write the c:crossBetween element.
        self._write_cross_between(x_axis.get('position_axis'))

        # Write the c:majorUnit element.
        self._write_c_major_unit(y_axis.get('major_unit'))

        # Write the c:minorUnit element.
        self._write_c_minor_unit(y_axis.get('minor_unit'))

        # Write the c:dispUnits element.
        self._write_disp_units(y_axis.get('display_units'),
                               y_axis.get('display_units_visible'))

        self._xml_end_tag('c:valAx')

    def _write_cat_val_axis(self, args):
        # Write the <c:valAx> element. This is for the second valAx
        # in scatter plots. Usually the X axis.
        x_axis = args['x_axis']
        y_axis = args['y_axis']
        axis_ids = args['axis_ids']
        position = args['position'] or self.val_axis_position
        horiz = self.horiz_val_axis

        # If there are no axis_ids then we don't need to write this element.
        if axis_ids is None or not len(axis_ids):
            return

        # Overwrite the default axis position with a user supplied value.
        position = x_axis.get('position') or position

        self._xml_start_tag('c:valAx')

        self._write_axis_id(axis_ids[0])

        # Write the c:scaling element.
        self._write_scaling(x_axis.get('reverse'),
                            x_axis.get('min'),
                            x_axis.get('max'),
                            x_axis.get('log_base'))

        if not x_axis.get('visible'):
            self._write_delete(1)

        # Write the c:axPos element.
        self._write_axis_pos(position, y_axis.get('reverse'))

        # Write the c:majorGridlines element.
        self._write_major_gridlines(x_axis.get('major_gridlines'))

        # Write the c:minorGridlines element.
        self._write_minor_gridlines(x_axis.get('minor_gridlines'))

        # Write the axis title elements.
        if x_axis['formula'] is not None:
            self._write_title_formula(x_axis['formula'],
                                      x_axis['data_id'],
                                      horiz,
                                      x_axis['name_font'],
                                      x_axis['name_layout'])
        elif x_axis['name'] is not None:
            self._write_title_rich(x_axis['name'],
                                   horiz,
                                   x_axis['name_font'],
                                   x_axis['name_layout'])

        # Write the c:numberFormat element.
        self._write_number_format(x_axis)

        # Write the c:majorTickMark element.
        self._write_major_tick_mark(x_axis.get('major_tick_mark'))

        # Write the c:tickLblPos element.
        self._write_tick_label_pos(x_axis.get('label_position'))

        # Write the c:spPr element for the axis line.
        self._write_sp_pr(x_axis)

        # Write the axis font elements.
        self._write_axis_font(x_axis.get('num_font'))

        # Write the c:crossAx element.
        self._write_cross_axis(axis_ids[1])

        # Note, the category crossing comes from the value axis.
        if y_axis.get('crossing') is None or y_axis['crossing'] == 'max':

            # Write the c:crosses element.
            self._write_crosses(y_axis.get('crossing'))
        else:

            # Write the c:crossesAt element.
            self._write_c_crosses_at(y_axis.get('crossing'))

        # Write the c:crossBetween element.
        self._write_cross_between(y_axis.get('position_axis'))

        # Write the c:majorUnit element.
        self._write_c_major_unit(x_axis.get('major_unit'))

        # Write the c:minorUnit element.
        self._write_c_minor_unit(x_axis.get('minor_unit'))

        # Write the c:dispUnits element.
        self._write_disp_units(x_axis.get('display_units'),
                               x_axis.get('display_units_visible'))

        self._xml_end_tag('c:valAx')

    def _write_date_axis(self, args):
        # Write the <c:dateAx> element. Usually the X axis.
        x_axis = args['x_axis']
        y_axis = args['y_axis']
        axis_ids = args['axis_ids']

        # If there are no axis_ids then we don't need to write this element.
        if axis_ids is None or not len(axis_ids):
            return

        position = self.cat_axis_position

        # Overwrite the default axis position with a user supplied value.
        position = x_axis.get('position') or position

        self._xml_start_tag('c:dateAx')

        self._write_axis_id(axis_ids[0])

        # Write the c:scaling element.
        self._write_scaling(x_axis.get('reverse'),
                            x_axis.get('min'),
                            x_axis.get('max'),
                            x_axis.get('log_base'))

        if not x_axis.get('visible'):
            self._write_delete(1)

        # Write the c:axPos element.
        self._write_axis_pos(position, y_axis.get('reverse'))

        # Write the c:majorGridlines element.
        self._write_major_gridlines(x_axis.get('major_gridlines'))

        # Write the c:minorGridlines element.
        self._write_minor_gridlines(x_axis.get('minor_gridlines'))

        # Write the axis title elements.
        if x_axis['formula'] is not None:
            self._write_title_formula(x_axis['formula'],
                                      x_axis['data_id'],
                                      None,
                                      x_axis['name_font'],
                                      x_axis['name_layout'])
        elif x_axis['name'] is not None:
            self._write_title_rich(x_axis['name'],
                                   None,
                                   x_axis['name_font'],
                                   x_axis['name_layout'])

        # Write the c:numFmt element.
        self._write_number_format(x_axis)

        # Write the c:majorTickMark element.
        self._write_major_tick_mark(x_axis.get('major_tick_mark'))

        # Write the c:tickLblPos element.
        self._write_tick_label_pos(x_axis.get('label_position'))

        # Write the c:spPr element for the axis line.
        self._write_sp_pr(x_axis)

        # Write the axis font elements.
        self._write_axis_font(x_axis.get('num_font'))

        # Write the c:crossAx element.
        self._write_cross_axis(axis_ids[1])

        if self.show_crosses or x_axis.get('visible'):

            # Note, the category crossing comes from the value axis.
            if (y_axis.get('crossing') is None
                    or y_axis.get('crossing') == 'max'):

                # Write the c:crosses element.
                self._write_crosses(y_axis.get('crossing'))
            else:

                # Write the c:crossesAt element.
                self._write_c_crosses_at(y_axis.get('crossing'))

        # Write the c:auto element.
        self._write_auto(1)

        # Write the c:labelOffset element.
        self._write_label_offset(100)

        # Write the c:tickLblSkip element.
        self._write_c_tick_lbl_skip(x_axis.get('interval_unit'))

        # Write the c:majorUnit element.
        self._write_c_major_unit(x_axis.get('major_unit'))

        # Write the c:majorTimeUnit element.
        if x_axis.get('major_unit'):
            self._write_c_major_time_unit(x_axis['major_unit_type'])

        # Write the c:minorUnit element.
        self._write_c_minor_unit(x_axis.get('minor_unit'))

        # Write the c:minorTimeUnit element.
        if x_axis.get('minor_unit'):
            self._write_c_minor_time_unit(x_axis['minor_unit_type'])

        self._xml_end_tag('c:dateAx')

    def _write_scaling(self, reverse, min_val, max_val, log_base):
        # Write the <c:scaling> element.

        self._xml_start_tag('c:scaling')

        # Write the c:logBase element.
        self._write_c_log_base(log_base)

        # Write the c:orientation element.
        self._write_orientation(reverse)

        # Write the c:max element.
        self._write_c_max(max_val)

        # Write the c:min element.
        self._write_c_min(min_val)

        self._xml_end_tag('c:scaling')

    def _write_c_log_base(self, val):
        # Write the <c:logBase> element.

        if not val:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:logBase', attributes)

    def _write_orientation(self, reverse):
        # Write the <c:orientation> element.
        val = 'minMax'

        if reverse:
            val = 'maxMin'

        attributes = [('val', val)]

        self._xml_empty_tag('c:orientation', attributes)

    def _write_c_max(self, max_val):
        # Write the <c:max_val> element.

        if max_val is None:
            return

        attributes = [('val', max_val)]

        self._xml_empty_tag('c:max', attributes)

    def _write_c_min(self, min_val):
        # Write the <c:min_val> element.

        if min_val is None:
            return

        attributes = [('val', min_val)]

        self._xml_empty_tag('c:min', attributes)

    def _write_axis_pos(self, val, reverse):
        # Write the <c:axPos> element.

        if reverse:
            if val == 'l':
                val = 'r'
            if val == 'b':
                val = 't'

        attributes = [('val', val)]

        self._xml_empty_tag('c:axPos', attributes)

    def _write_number_format(self, axis):
        # Write the <c:numberFormat> element. Note: It is assumed that if
        # a user defined number format is supplied (i.e., non-default) then
        # the sourceLinked attribute is 0.
        # The user can override this if required.
        format_code = axis.get('num_format')
        source_linked = 1

        # Check if a user defined number format has been set.
        if (format_code is not None
                and format_code != axis['defaults']['num_format']):
            source_linked = 0

        # User override of sourceLinked.
        if axis.get('num_format_linked'):
            source_linked = 1

        attributes = [
            ('formatCode', format_code),
            ('sourceLinked', source_linked),
        ]

        self._xml_empty_tag('c:numFmt', attributes)

    def _write_cat_number_format(self, axis):
        # Write the <c:numFmt> element. Special case handler for category
        # axes which don't always have a number format.
        format_code = axis.get('num_format')
        source_linked = 1
        default_format = 1

        # Check if a user defined number format has been set.
        if (format_code is not None
                and format_code != axis['defaults']['num_format']):
            source_linked = 0
            default_format = 0

        # User override of linkedSource.
        if axis.get('num_format_linked'):
            source_linked = 1

        # Skip if cat doesn't have a num format (unless it is non-default).
        if not self.cat_has_num_fmt and default_format:
            return

        attributes = [
            ('formatCode', format_code),
            ('sourceLinked', source_linked),
        ]

        self._xml_empty_tag('c:numFmt', attributes)

    def _write_data_label_number_format(self, format_code):
        # Write the <c:numberFormat> element for data labels.
        source_linked = 0

        attributes = [
            ('formatCode', format_code),
            ('sourceLinked', source_linked),
        ]

        self._xml_empty_tag('c:numFmt', attributes)

    def _write_major_tick_mark(self, val):
        # Write the <c:majorTickMark> element.

        if not val:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:majorTickMark', attributes)

    def _write_tick_label_pos(self, val=None):
        # Write the <c:tickLblPos> element.
        if val is None or val == 'next_to':
            val = 'nextTo'

        attributes = [('val', val)]

        self._xml_empty_tag('c:tickLblPos', attributes)

    def _write_cross_axis(self, val):
        # Write the <c:crossAx> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:crossAx', attributes)

    def _write_crosses(self, val=None):
        # Write the <c:crosses> element.
        if val is None:
            val = 'autoZero'

        attributes = [('val', val)]

        self._xml_empty_tag('c:crosses', attributes)

    def _write_c_crosses_at(self, val):
        # Write the <c:crossesAt> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:crossesAt', attributes)

    def _write_auto(self, val):
        # Write the <c:auto> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:auto', attributes)

    def _write_label_align(self, val):
        # Write the <c:labelAlign> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:lblAlgn', attributes)

    def _write_label_offset(self, val):
        # Write the <c:labelOffset> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:lblOffset', attributes)

    def _write_c_tick_lbl_skip(self, val):
        # Write the <c:tickLblSkip> element.
        if val is None:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:tickLblSkip', attributes)

    def _write_major_gridlines(self, gridlines):
        # Write the <c:majorGridlines> element.

        if not gridlines:
            return

        if not gridlines['visible']:
            return

        if gridlines['line']['defined']:
            self._xml_start_tag('c:majorGridlines')

            # Write the c:spPr element.
            self._write_sp_pr(gridlines)

            self._xml_end_tag('c:majorGridlines')
        else:
            self._xml_empty_tag('c:majorGridlines')

    def _write_minor_gridlines(self, gridlines):
        # Write the <c:minorGridlines> element.

        if not gridlines:
            return

        if not gridlines['visible']:
            return

        if gridlines['line']['defined']:
            self._xml_start_tag('c:minorGridlines')

            # Write the c:spPr element.
            self._write_sp_pr(gridlines)

            self._xml_end_tag('c:minorGridlines')
        else:
            self._xml_empty_tag('c:minorGridlines')

    def _write_cross_between(self, val):
        # Write the <c:crossBetween> element.
        if val is None:
            val = self.cross_between

        attributes = [('val', val)]

        self._xml_empty_tag('c:crossBetween', attributes)

    def _write_c_major_unit(self, val):
        # Write the <c:majorUnit> element.

        if not val:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:majorUnit', attributes)

    def _write_c_minor_unit(self, val):
        # Write the <c:minorUnit> element.

        if not val:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:minorUnit', attributes)

    def _write_c_major_time_unit(self, val=None):
        # Write the <c:majorTimeUnit> element.
        if val is None:
            val = 'days'

        attributes = [('val', val)]

        self._xml_empty_tag('c:majorTimeUnit', attributes)

    def _write_c_minor_time_unit(self, val=None):
        # Write the <c:minorTimeUnit> element.
        if val is None:
            val = 'days'

        attributes = [('val', val)]

        self._xml_empty_tag('c:minorTimeUnit', attributes)

    def _write_legend(self):
        # Write the <c:legend> element.
        position = self.legend_position
        font = self.legend_font
        delete_series = []
        overlay = 0

        if (self.legend_delete_series is not None
                and type(self.legend_delete_series) is list):
            delete_series = self.legend_delete_series

        if position.startswith('overlay_'):
            position = position.replace('overlay_', '')
            overlay = 1

        allowed = {
            'right': 'r',
            'left': 'l',
            'top': 't',
            'bottom': 'b',
        }

        if position == 'none':
            return

        if position not in allowed:
            return

        position = allowed[position]

        self._xml_start_tag('c:legend')

        # Write the c:legendPos element.
        self._write_legend_pos(position)

        # Remove series labels from the legend.
        for index in delete_series:
            # Write the c:legendEntry element.
            self._write_legend_entry(index)

        # Write the c:layout element.
        self._write_layout(self.legend_layout, 'legend')

        if font:
            self._write_tx_pr(None, font)

        # Write the c:overlay element.
        if overlay:
            self._write_overlay()

        self._xml_end_tag('c:legend')

    def _write_legend_pos(self, val):
        # Write the <c:legendPos> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:legendPos', attributes)

    def _write_legend_entry(self, index):
        # Write the <c:legendEntry> element.

        self._xml_start_tag('c:legendEntry')

        # Write the c:idx element.
        self._write_idx(index)

        # Write the c:delete element.
        self._write_delete(1)

        self._xml_end_tag('c:legendEntry')

    def _write_overlay(self):
        # Write the <c:overlay> element.
        val = 1

        attributes = [('val', val)]

        self._xml_empty_tag('c:overlay', attributes)

    def _write_plot_vis_only(self):
        # Write the <c:plotVisOnly> element.
        val = 1

        # Ignore this element if we are plotting hidden data.
        if self.show_hidden:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:plotVisOnly', attributes)

    def _write_print_settings(self):
        # Write the <c:printSettings> element.
        self._xml_start_tag('c:printSettings')

        # Write the c:headerFooter element.
        self._write_header_footer()

        # Write the c:pageMargins element.
        self._write_page_margins()

        # Write the c:pageSetup element.
        self._write_page_setup()

        self._xml_end_tag('c:printSettings')

    def _write_header_footer(self):
        # Write the <c:headerFooter> element.
        self._xml_empty_tag('c:headerFooter')

    def _write_page_margins(self):
        # Write the <c:pageMargins> element.
        b = 0.75
        l = 0.7
        r = 0.7
        t = 0.75
        header = 0.3
        footer = 0.3

        attributes = [
            ('b', b),
            ('l', l),
            ('r', r),
            ('t', t),
            ('header', header),
            ('footer', footer),
        ]

        self._xml_empty_tag('c:pageMargins', attributes)

    def _write_page_setup(self):
        # Write the <c:pageSetup> element.
        self._xml_empty_tag('c:pageSetup')

    def _write_c_auto_title_deleted(self):
        # Write the <c:autoTitleDeleted> element.
        self._xml_empty_tag('c:autoTitleDeleted', [('val', 1)])

    def _write_title_rich(self, title, horiz, font, layout, overlay=False):
        # Write the <c:title> element for a rich string.

        self._xml_start_tag('c:title')

        # Write the c:tx element.
        self._write_tx_rich(title, horiz, font)

        # Write the c:layout element.
        self._write_layout(layout, 'text')

        # Write the c:overlay element.
        if overlay:
            self._write_overlay()

        self._xml_end_tag('c:title')

    def _write_title_formula(self, title, data_id, horiz, font, layout,
                             overlay=False):
        # Write the <c:title> element for a rich string.

        self._xml_start_tag('c:title')

        # Write the c:tx element.
        self._write_tx_formula(title, data_id)

        # Write the c:layout element.
        self._write_layout(layout, 'text')

        # Write the c:overlay element.
        if overlay:
            self._write_overlay()

        # Write the c:txPr element.
        self._write_tx_pr(horiz, font)

        self._xml_end_tag('c:title')

    def _write_tx_rich(self, title, horiz, font):
        # Write the <c:tx> element.

        self._xml_start_tag('c:tx')

        # Write the c:rich element.
        self._write_rich(title, horiz, font)

        self._xml_end_tag('c:tx')

    def _write_tx_value(self, title):
        # Write the <c:tx> element with a value such as for series names.

        self._xml_start_tag('c:tx')

        # Write the c:v element.
        self._write_v(title)

        self._xml_end_tag('c:tx')

    def _write_tx_formula(self, title, data_id):
        # Write the <c:tx> element.
        data = None

        if data_id is not None:
            data = self.formula_data[data_id]

        self._xml_start_tag('c:tx')

        # Write the c:strRef element.
        self._write_str_ref(title, data, 'str')

        self._xml_end_tag('c:tx')

    def _write_rich(self, title, horiz, font):
        # Write the <c:rich> element.

        if font and font.get('rotation'):
            rotation = font['rotation']
        else:
            rotation = None

        self._xml_start_tag('c:rich')

        # Write the a:bodyPr element.
        self._write_a_body_pr(rotation, horiz)

        # Write the a:lstStyle element.
        self._write_a_lst_style()

        # Write the a:p element.
        self._write_a_p_rich(title, font)

        self._xml_end_tag('c:rich')

    def _write_a_body_pr(self, rotation, horiz):
        # Write the <a:bodyPr> element.
        attributes = []

        if rotation is None and horiz:
            rotation = -5400000

        if rotation is not None:
            attributes.append(('rot', rotation))

        if horiz:
            attributes.append(('vert', 'horz'))

        self._xml_empty_tag('a:bodyPr', attributes)

    def _write_a_lst_style(self):
        # Write the <a:lstStyle> element.
        self._xml_empty_tag('a:lstStyle')

    def _write_a_p_rich(self, title, font):
        # Write the <a:p> element for rich string titles.

        self._xml_start_tag('a:p')

        # Write the a:pPr element.
        self._write_a_p_pr_rich(font)

        # Write the a:r element.
        self._write_a_r(title, font)

        self._xml_end_tag('a:p')

    def _write_a_p_formula(self, font):
        # Write the <a:p> element for formula titles.

        self._xml_start_tag('a:p')

        # Write the a:pPr element.
        self._write_a_p_pr_formula(font)

        # Write the a:endParaRPr element.
        self._write_a_end_para_rpr()

        self._xml_end_tag('a:p')

    def _write_a_p_pr_rich(self, font):
        # Write the <a:pPr> element for rich string titles.

        self._xml_start_tag('a:pPr')

        # Write the a:defRPr element.
        self._write_a_def_rpr(font)

        self._xml_end_tag('a:pPr')

    def _write_a_p_pr_formula(self, font):
        # Write the <a:pPr> element for formula titles.

        self._xml_start_tag('a:pPr')

        # Write the a:defRPr element.
        self._write_a_def_rpr(font)

        self._xml_end_tag('a:pPr')

    def _write_a_def_rpr(self, font):
        # Write the <a:defRPr> element.
        has_color = 0

        style_attributes = Shape._get_font_style_attributes(font)
        latin_attributes = Shape._get_font_latin_attributes(font)

        if font and font.get('color') is not None:
            has_color = 1

        if latin_attributes or has_color:
            self._xml_start_tag('a:defRPr', style_attributes)

            if has_color:
                self._write_a_solid_fill({'color': font['color']})

            if latin_attributes:
                self._write_a_latin(latin_attributes)

            self._xml_end_tag('a:defRPr')
        else:
            self._xml_empty_tag('a:defRPr', style_attributes)

    def _write_a_end_para_rpr(self):
        # Write the <a:endParaRPr> element.
        lang = 'en-US'

        attributes = [('lang', lang)]

        self._xml_empty_tag('a:endParaRPr', attributes)

    def _write_a_r(self, title, font):
        # Write the <a:r> element.

        self._xml_start_tag('a:r')

        # Write the a:rPr element.
        self._write_a_r_pr(font)

        # Write the a:t element.
        self._write_a_t(title)

        self._xml_end_tag('a:r')

    def _write_a_r_pr(self, font):
        # Write the <a:rPr> element.
        has_color = 0
        lang = 'en-US'

        style_attributes = Shape._get_font_style_attributes(font)
        latin_attributes = Shape._get_font_latin_attributes(font)

        if font and font['color'] is not None:
            has_color = 1

        # Add the lang type to the attributes.
        style_attributes.insert(0, ('lang', lang))

        if latin_attributes or has_color:
            self._xml_start_tag('a:rPr', style_attributes)

            if has_color:
                self._write_a_solid_fill({'color': font['color']})

            if latin_attributes:
                self._write_a_latin(latin_attributes)

            self._xml_end_tag('a:rPr')
        else:
            self._xml_empty_tag('a:rPr', style_attributes)

    def _write_a_t(self, title):
        # Write the <a:t> element.

        self._xml_data_element('a:t', title)

    def _write_tx_pr(self, horiz, font):
        # Write the <c:txPr> element.

        if font and font.get('rotation'):
            rotation = font['rotation']
        else:
            rotation = None

        self._xml_start_tag('c:txPr')

        # Write the a:bodyPr element.
        self._write_a_body_pr(rotation, horiz)

        # Write the a:lstStyle element.
        self._write_a_lst_style()

        # Write the a:p element.
        self._write_a_p_formula(font)

        self._xml_end_tag('c:txPr')

    def _write_marker(self, marker):
        # Write the <c:marker> element.
        if marker is None:
            marker = self.default_marker

        if not marker:
            return
        if 'automatic' in marker:
            return

        self._xml_start_tag('c:marker')

        # Write the c:symbol element.
        self._write_symbol(marker['type'])

        # Write the c:size element.
        if marker.get('size'):
            self._write_marker_size(marker['size'])

        # Write the c:spPr element.
        self._write_sp_pr(marker)

        self._xml_end_tag('c:marker')

    def _write_marker_value(self):
        # Write the <c:marker> element without a sub-element.
        style = self.default_marker

        if not style:
            return

        attributes = [('val', 1)]

        self._xml_empty_tag('c:marker', attributes)

    def _write_marker_size(self, val):
        # Write the <c:size> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:size', attributes)

    def _write_symbol(self, val):
        # Write the <c:symbol> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:symbol', attributes)

    def _write_sp_pr(self, series):
        # Write the <c:spPr> element.

        has_fill = False
        has_line = False
        has_gradient = series.get('gradient')

        if series.get('fill') and series['fill']['defined']:
            has_fill = True

        if series.get('line') and series['line']['defined']:
            has_line = True

        if not has_fill and not has_line and not has_gradient:
            return

        self._xml_start_tag('c:spPr')

        # Write the fill elements for solid charts such as pie and bar.
        if series.get('fill') and series['fill']['defined']:
            if 'none' in series['fill']:
                # Write the a:noFill element.
                self._write_a_no_fill()
            else:
                # Write the a:solidFill element.
                self._write_a_solid_fill(series['fill'])

        if series.get('gradient'):
            # Write the a:gradFill element.
            self._write_a_grad_fill(series['gradient'])

        # Write the a:ln element.
        if series.get('line') and series['line']['defined']:
            self._write_a_ln(series['line'])

        self._xml_end_tag('c:spPr')

    def _write_a_ln(self, line):
        # Write the <a:ln> element.
        attributes = []

        # Add the line width as an attribute.
        width = line.get('width')

        if width:
            # Round width to nearest 0.25, like Excel.
            width = int((width + 0.125) * 4) / 4.0

            # Convert to internal units.
            width = int(0.5 + (12700 * width))

            attributes = [('w', width)]

        self._xml_start_tag('a:ln', attributes)

        # Write the line fill.
        if 'none' in line:
            # Write the a:noFill element.
            self._write_a_no_fill()
        elif 'color' in line:
            # Write the a:solidFill element.
            self._write_a_solid_fill(line)

        # Write the line/dash type.
        line_type = line.get('dash_type')
        if line_type:
            # Write the a:prstDash element.
            self._write_a_prst_dash(line_type)

        self._xml_end_tag('a:ln')

    def _write_a_no_fill(self):
        # Write the <a:noFill> element.
        self._xml_empty_tag('a:noFill')

    def _write_a_solid_fill(self, line):
        # Write the <a:solidFill> element.

        self._xml_start_tag('a:solidFill')

        if 'color' in line:
            color = get_rgb_color(line['color'])

            # Write the a:srgbClr element.
            self._write_a_srgb_clr(color)

        self._xml_end_tag('a:solidFill')

    def _write_a_srgb_clr(self, val):
        # Write the <a:srgbClr> element.

        attributes = [('val', val)]

        self._xml_empty_tag('a:srgbClr', attributes)

    def _write_a_prst_dash(self, val):
        # Write the <a:prstDash> element.

        attributes = [('val', val)]

        self._xml_empty_tag('a:prstDash', attributes)

    def _write_trendline(self, trendline):
        # Write the <c:trendline> element.

        if not trendline:
            return

        self._xml_start_tag('c:trendline')

        # Write the c:name element.
        self._write_name(trendline.get('name'))

        # Write the c:spPr element.
        self._write_sp_pr(trendline)

        # Write the c:trendlineType element.
        self._write_trendline_type(trendline['type'])

        # Write the c:order element for polynomial trendlines.
        if trendline['type'] == 'poly':
            self._write_trendline_order(trendline.get('order'))

        # Write the c:period element for moving average trendlines.
        if trendline['type'] == 'movingAvg':
            self._write_period(trendline.get('period'))

        # Write the c:forward element.
        self._write_forward(trendline.get('forward'))

        # Write the c:backward element.
        self._write_backward(trendline.get('backward'))

        self._xml_end_tag('c:trendline')

    def _write_trendline_type(self, val):
        # Write the <c:trendlineType> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:trendlineType', attributes)

    def _write_name(self, data):
        # Write the <c:name> element.

        if data is None:
            return

        self._xml_data_element('c:name', data)

    def _write_trendline_order(self, val):
        # Write the <c:order> element.
        # val = _[0] is not None ? _[0]: 2

        attributes = [('val', val)]

        self._xml_empty_tag('c:order', attributes)

    def _write_period(self, val):
        # Write the <c:period> element.
        # val = _[0] is not None ? _[0]: 2

        attributes = [('val', val)]

        self._xml_empty_tag('c:period', attributes)

    def _write_forward(self, val):
        # Write the <c:forward> element.

        if not val:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:forward', attributes)

    def _write_backward(self, val):
        # Write the <c:backward> element.

        if not val:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:backward', attributes)

    def _write_hi_low_lines(self):
        # Write the <c:hiLowLines> element.
        hi_low_lines = self.hi_low_lines

        if hi_low_lines is None:
            return

        if 'line' in hi_low_lines and hi_low_lines['line']['defined']:

            self._xml_start_tag('c:hiLowLines')

            # Write the c:spPr element.
            self._write_sp_pr(hi_low_lines)

            self._xml_end_tag('c:hiLowLines')
        else:
            self._xml_empty_tag('c:hiLowLines')

    def _write_drop_lines(self):
        # Write the <c:dropLines> element.
        drop_lines = self.drop_lines

        if drop_lines is None:
            return

        if drop_lines['line']['defined']:

            self._xml_start_tag('c:dropLines')

            # Write the c:spPr element.
            self._write_sp_pr(drop_lines)

            self._xml_end_tag('c:dropLines')
        else:
            self._xml_empty_tag('c:dropLines')

    def _write_overlap(self, val):
        # Write the <c:overlap> element.

        if val is None:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:overlap', attributes)

    def _write_num_cache(self, data):
        # Write the <c:numCache> element.
        if data:
            count = len(data)
        else:
            count = 0

        self._xml_start_tag('c:numCache')

        # Write the c:formatCode element.
        self._write_format_code('General')

        # Write the c:ptCount element.
        self._write_pt_count(count)

        for i in range(count):
            token = data[i]

            if token is None:
                continue

            try:
                float(token)
            except ValueError:
                # Write non-numeric data as 0.
                token = 0

            # Write the c:pt element.
            self._write_pt(i, token)

        self._xml_end_tag('c:numCache')

    def _write_str_cache(self, data):
        # Write the <c:strCache> element.
        count = len(data)

        self._xml_start_tag('c:strCache')

        # Write the c:ptCount element.
        self._write_pt_count(count)

        for i in range(count):
            # Write the c:pt element.
            self._write_pt(i, data[i])

        self._xml_end_tag('c:strCache')

    def _write_format_code(self, data):
        # Write the <c:formatCode> element.

        self._xml_data_element('c:formatCode', data)

    def _write_pt_count(self, val):
        # Write the <c:ptCount> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:ptCount', attributes)

    def _write_pt(self, idx, value):
        # Write the <c:pt> element.

        if value is None:
            return

        attributes = [('idx', idx)]

        self._xml_start_tag('c:pt', attributes)

        # Write the c:v element.
        self._write_v(value)

        self._xml_end_tag('c:pt')

    def _write_v(self, data):
        # Write the <c:v> element.

        self._xml_data_element('c:v', data)

    def _write_protection(self):
        # Write the <c:protection> element.
        if not self.protection:
            return

        self._xml_empty_tag('c:protection')

    def _write_d_pt(self, points):
        # Write the <c:dPt> elements.
        index = -1

        if not points:
            return

        for point in points:
            index += 1
            if not point:
                continue

            self._write_d_pt_point(index, point)

    def _write_d_pt_point(self, index, point):
        # Write an individual <c:dPt> element.

            self._xml_start_tag('c:dPt')

            # Write the c:idx element.
            self._write_idx(index)

            # Write the c:spPr element.
            self._write_sp_pr(point)

            self._xml_end_tag('c:dPt')

    def _write_d_lbls(self, labels):
        # Write the <c:dLbls> element.

        if not labels:
            return

        self._xml_start_tag('c:dLbls')

        # Write the c:numFmt element.
        if labels.get('num_format'):
            self._write_data_label_number_format(labels['num_format'])

        # Write the data label font elements.
        if labels.get('font'):
            self._write_axis_font(labels['font'])

        # Write the c:dLblPos element.
        if labels.get('position'):
            self._write_d_lbl_pos(labels['position'])

        # Write the c:showLegendKey element.
        if labels.get('legend_key'):
            self._write_show_legend_key()

        # Write the c:showVal element.
        if labels.get('value'):
            self._write_show_val()

        # Write the c:showCatName element.
        if labels.get('category'):
            self._write_show_cat_name()

        # Write the c:showSerName element.
        if labels.get('series_name'):
            self._write_show_ser_name()

        # Write the c:showPercent element.
        if labels.get('percentage'):
            self._write_show_percent()

        # Write the c:separator element.
        if labels.get('separator'):
            self._write_separator(labels['separator'])

        # Write the c:showLeaderLines element.
        if labels.get('leader_lines'):
            self._write_show_leader_lines()

        self._xml_end_tag('c:dLbls')

    def _write_show_legend_key(self):
        # Write the <c:showLegendKey> element.
        val = '1'

        attributes = [('val', val)]

        self._xml_empty_tag('c:showLegendKey', attributes)

    def _write_show_val(self):
        # Write the <c:showVal> element.
        val = 1

        attributes = [('val', val)]

        self._xml_empty_tag('c:showVal', attributes)

    def _write_show_cat_name(self):
        # Write the <c:showCatName> element.
        val = 1

        attributes = [('val', val)]

        self._xml_empty_tag('c:showCatName', attributes)

    def _write_show_ser_name(self):
        # Write the <c:showSerName> element.
        val = 1

        attributes = [('val', val)]

        self._xml_empty_tag('c:showSerName', attributes)

    def _write_show_percent(self):
        # Write the <c:showPercent> element.
        val = 1

        attributes = [('val', val)]

        self._xml_empty_tag('c:showPercent', attributes)

    def _write_separator(self, data):
        # Write the <c:separator> element.
        self._xml_data_element('c:separator', data)

    def _write_show_leader_lines(self):
        # Write the <c:showLeaderLines> element.
        val = 1

        attributes = [('val', val)]

        self._xml_empty_tag('c:showLeaderLines', attributes)

    def _write_d_lbl_pos(self, val):
        # Write the <c:dLblPos> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:dLblPos', attributes)

    def _write_delete(self, val):
        # Write the <c:delete> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:delete', attributes)

    def _write_c_invert_if_negative(self, invert):
        # Write the <c:invertIfNegative> element.
        val = 1

        if not invert:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:invertIfNegative', attributes)

    def _write_axis_font(self, font):
        # Write the axis font elements.

        if not font:
            return

        self._xml_start_tag('c:txPr')
        self._write_a_body_pr(font.get('rotation'), None)
        self._write_a_lst_style()
        self._xml_start_tag('a:p')

        self._write_a_p_pr_rich(font)

        self._write_a_end_para_rpr()
        self._xml_end_tag('a:p')
        self._xml_end_tag('c:txPr')

    def _write_a_latin(self, attributes):
        # Write the <a:latin> element.
        self._xml_empty_tag('a:latin', attributes)

    def _write_d_table(self):
        # Write the <c:dTable> element.
        table = self.table

        if not table:
            return

        self._xml_start_tag('c:dTable')

        if table['horizontal']:
            # Write the c:showHorzBorder element.
            self._write_show_horz_border()

        if table['vertical']:
            # Write the c:showVertBorder element.
            self._write_show_vert_border()

        if table['outline']:
            # Write the c:showOutline element.
            self._write_show_outline()

        if table['show_keys']:
            # Write the c:showKeys element.
            self._write_show_keys()

        self._xml_end_tag('c:dTable')

    def _write_show_horz_border(self):
        # Write the <c:showHorzBorder> element.
        attributes = [('val', 1)]

        self._xml_empty_tag('c:showHorzBorder', attributes)

    def _write_show_vert_border(self):
        # Write the <c:showVertBorder> element.
        attributes = [('val', 1)]

        self._xml_empty_tag('c:showVertBorder', attributes)

    def _write_show_outline(self):
        # Write the <c:showOutline> element.
        attributes = [('val', 1)]

        self._xml_empty_tag('c:showOutline', attributes)

    def _write_show_keys(self):
        # Write the <c:showKeys> element.
        attributes = [('val', 1)]

        self._xml_empty_tag('c:showKeys', attributes)

    def _write_error_bars(self, error_bars):
        # Write the X and Y error bars.

        if not error_bars:
            return

        if error_bars['x_error_bars']:
            self._write_err_bars('x', error_bars['x_error_bars'])

        if error_bars['y_error_bars']:
            self._write_err_bars('y', error_bars['y_error_bars'])

    def _write_err_bars(self, direction, error_bars):
        # Write the <c:errBars> element.

        if not error_bars:
            return

        self._xml_start_tag('c:errBars')

        # Write the c:errDir element.
        self._write_err_dir(direction)

        # Write the c:errBarType element.
        self._write_err_bar_type(error_bars['direction'])

        # Write the c:errValType element.
        self._write_err_val_type(error_bars['type'])

        if not error_bars['endcap']:
            # Write the c:noEndCap element.
            self._write_no_end_cap()

        if error_bars['type'] == 'stdErr':
            # Don't need to write a c:errValType tag.
            pass
        elif error_bars['type'] == 'cust':
            # Write the custom error tags.
            self._write_custom_error(error_bars)
        else:
            # Write the c:val element.
            self._write_error_val(error_bars['value'])

        # Write the c:spPr element.
        self._write_sp_pr(error_bars)

        self._xml_end_tag('c:errBars')

    def _write_err_dir(self, val):
        # Write the <c:errDir> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:errDir', attributes)

    def _write_err_bar_type(self, val):
        # Write the <c:errBarType> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:errBarType', attributes)

    def _write_err_val_type(self, val):
        # Write the <c:errValType> element.

        attributes = [('val', val)]

        self._xml_empty_tag('c:errValType', attributes)

    def _write_no_end_cap(self):
        # Write the <c:noEndCap> element.
        attributes = [('val', 1)]

        self._xml_empty_tag('c:noEndCap', attributes)

    def _write_error_val(self, val):
        # Write the <c:val> element for error bars.

        attributes = [('val', val)]

        self._xml_empty_tag('c:val', attributes)

    def _write_custom_error(self, error_bars):
        # Write the custom error bars tags.

        if error_bars['plus_values']:
            # Write the c:plus element.
            self._xml_start_tag('c:plus')

            if isinstance(error_bars['plus_values'], list):
                self._write_num_lit(error_bars['plus_values'])
            else:
                self._write_num_ref(error_bars['plus_values'],
                                    error_bars['plus_data'],
                                    'num')
            self._xml_end_tag('c:plus')

        if error_bars['minus_values']:
            # Write the c:minus element.
            self._xml_start_tag('c:minus')

            if isinstance(error_bars['minus_values'], list):
                self._write_num_lit(error_bars['minus_values'])
            else:
                self._write_num_ref(error_bars['minus_values'],
                                    error_bars['minus_data'],
                                    'num')
            self._xml_end_tag('c:minus')

    def _write_num_lit(self, data):
        # Write the <c:numLit> element for literal number list elements.
        count = len(data)

        # Write the c:numLit element.
        self._xml_start_tag('c:numLit')

        # Write the c:formatCode element.
        self._write_format_code('General')

        # Write the c:ptCount element.
        self._write_pt_count(count)

        for i in range(count):
            token = data[i]

            if token is None:
                continue

            try:
                float(token)
            except ValueError:
                # Write non-numeric data as 0.
                token = 0

            # Write the c:pt element.
            self._write_pt(i, token)

        self._xml_end_tag('c:numLit')

    def _write_up_down_bars(self):
        # Write the <c:upDownBars> element.
        up_down_bars = self.up_down_bars

        if up_down_bars is None:
            return

        self._xml_start_tag('c:upDownBars')

        # Write the c:gapWidth element.
        self._write_gap_width(150)

        # Write the c:upBars element.
        self._write_up_bars(up_down_bars.get('up'))

        # Write the c:downBars element.
        self._write_down_bars(up_down_bars.get('down'))

        self._xml_end_tag('c:upDownBars')

    def _write_gap_width(self, val):
        # Write the <c:gapWidth> element.

        if val is None:
            return

        attributes = [('val', val)]

        self._xml_empty_tag('c:gapWidth', attributes)

    def _write_up_bars(self, bar_format):
        # Write the <c:upBars> element.

        if bar_format['line'] and bar_format['line']['defined']:
            self._xml_start_tag('c:upBars')

            # Write the c:spPr element.
            self._write_sp_pr(bar_format)

            self._xml_end_tag('c:upBars')
        else:
            self._xml_empty_tag('c:upBars')

    def _write_down_bars(self, bar_format):
        # Write the <c:downBars> element.

        if bar_format['line'] and bar_format['line']['defined']:
            self._xml_start_tag('c:downBars')

            # Write the c:spPr element.
            self._write_sp_pr(bar_format)

            self._xml_end_tag('c:downBars')
        else:
            self._xml_empty_tag('c:downBars')

    def _write_disp_units(self, units, display):
        # Write the <c:dispUnits> element.

        if not units:
            return

        attributes = [('val', units)]

        self._xml_start_tag('c:dispUnits')
        self._xml_empty_tag('c:builtInUnit', attributes)

        if display:
            self._xml_start_tag('c:dispUnitsLbl')
            self._xml_empty_tag('c:layout')
            self._xml_end_tag('c:dispUnitsLbl')

        self._xml_end_tag('c:dispUnits')

    def _write_a_grad_fill(self, gradient):
        # Write the <a:gradFill> element.

        attributes = [('flip', 'none'), ('rotWithShape', '1')]

        if gradient['type'] == 'linear':
            attributes = []

        self._xml_start_tag('a:gradFill', attributes)

        # Write the a:gsLst element.
        self._write_a_gs_lst(gradient)

        if gradient['type'] == 'linear':
            # Write the a:lin element.
            self._write_a_lin(gradient['angle'])
        else:
            # Write the a:path element.
            self._write_a_path(gradient['type'])

            # Write the a:tileRect element.
            self._write_a_tile_rect(gradient['type'])

        self._xml_end_tag('a:gradFill')

    def _write_a_gs_lst(self, gradient):
        # Write the <a:gsLst> element.
        positions = gradient['positions']
        colors = gradient['colors']

        self._xml_start_tag('a:gsLst')

        for i in range(len(colors)):
            pos = int(positions[i] * 1000)
            attributes = [('pos', pos)]
            self._xml_start_tag('a:gs', attributes)

            # Write the a:srgbClr element.
            # TODO: Wait for a feature request to support transparency.
            color = get_rgb_color(colors[i])
            self._write_a_srgb_clr(color)

            self._xml_end_tag('a:gs')

        self._xml_end_tag('a:gsLst')

    def _write_a_lin(self, angle):
        # Write the <a:lin> element.

        angle = int(60000 * angle)

        attributes = [
            ('ang', angle),
            ('scaled', '0'),
        ]

        self._xml_empty_tag('a:lin', attributes)

    def _write_a_path(self, gradient_type):
        # Write the <a:path> element.

        attributes = [('path', gradient_type)]

        self._xml_start_tag('a:path', attributes)

        # Write the a:fillToRect element.
        self._write_a_fill_to_rect(gradient_type)

        self._xml_end_tag('a:path')

    def _write_a_fill_to_rect(self, gradient_type):
        # Write the <a:fillToRect> element.

        l = '100000'
        t = '100000'

        if gradient_type == 'shape':
            attributes = [
                ('l', '50000'),
                ('t', '50000'),
                ('r', '50000'),
                ('b', '50000'),
            ]
        else:
            attributes = [
                ('l', '100000'),
                ('t', '100000'),
            ]

        self._xml_empty_tag('a:fillToRect', attributes)

    def _write_a_tile_rect(self, gradient_type):
        # Write the <a:tileRect> element.

        if gradient_type == 'shape':
            attributes = []
        else:
            attributes = [
                ('r', '-100000'),
                ('b', '-100000'),
            ]

        self._xml_empty_tag('a:tileRect', attributes)