_base.py 132 KB
Newer Older
xuebingbing's avatar
xuebingbing committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from collections import OrderedDict

import six
from six.moves import xrange

import itertools
import warnings
import math
from operator import itemgetter

import numpy as np
from numpy import ma

import matplotlib

from matplotlib import cbook
from matplotlib.cbook import (_check_1d, _string_to_bool, iterable,
                              index_of, get_label)
from matplotlib import docstring
import matplotlib.colors as mcolors
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
import matplotlib.artist as martist
import matplotlib.transforms as mtransforms
import matplotlib.ticker as mticker
import matplotlib.axis as maxis
import matplotlib.scale as mscale
import matplotlib.spines as mspines
import matplotlib.font_manager as font_manager
import matplotlib.text as mtext
import matplotlib.image as mimage
from matplotlib.offsetbox import OffsetBox
from matplotlib.artist import allow_rasterization

from matplotlib.rcsetup import cycler
from matplotlib.rcsetup import validate_axisbelow

rcParams = matplotlib.rcParams

is_string_like = cbook.is_string_like
is_sequence_of_strings = cbook.is_sequence_of_strings

_hold_msg = """axes.hold is deprecated.
    See the API Changes document (http://matplotlib.org/api/api_changes.html)
    for more details."""


def _process_plot_format(fmt):
    """
    Process a MATLAB style color/line style format string.  Return a
    (*linestyle*, *color*) tuple as a result of the processing.  Default
    values are ('-', 'b').  Example format strings include:

    * 'ko': black circles
    * '.b': blue dots
    * 'r--': red dashed lines
    * 'C2--': the third color in the color cycle, dashed lines

    .. seealso::

        :func:`~matplotlib.Line2D.lineStyles` and
        :func:`~matplotlib.pyplot.colors`
            for all possible styles and color format string.
    """

    linestyle = None
    marker = None
    color = None

    # Is fmt just a colorspec?
    try:
        color = mcolors.to_rgba(fmt)

        # We need to differentiate grayscale '1.0' from tri_down marker '1'
        try:
            fmtint = str(int(fmt))
        except ValueError:
            return linestyle, marker, color  # Yes
        else:
            if fmt != fmtint:
                # user definitely doesn't want tri_down marker
                return linestyle, marker, color  # Yes
            else:
                # ignore converted color
                color = None
    except ValueError:
        pass  # No, not just a color.

    # handle the multi char special cases and strip them from the
    # string
    if fmt.find('--') >= 0:
        linestyle = '--'
        fmt = fmt.replace('--', '')
    if fmt.find('-.') >= 0:
        linestyle = '-.'
        fmt = fmt.replace('-.', '')
    if fmt.find(' ') >= 0:
        linestyle = 'None'
        fmt = fmt.replace(' ', '')

    chars = [c for c in fmt]

    i = 0
    while i < len(chars):
        c = chars[i]
        if c in mlines.lineStyles:
            if linestyle is not None:
                raise ValueError(
                    'Illegal format string "%s"; two linestyle symbols' % fmt)
            linestyle = c
        elif c in mlines.lineMarkers:
            if marker is not None:
                raise ValueError(
                    'Illegal format string "%s"; two marker symbols' % fmt)
            marker = c
        elif c in mcolors.get_named_colors_mapping():
            if color is not None:
                raise ValueError(
                    'Illegal format string "%s"; two color symbols' % fmt)
            color = c
        elif c == 'C' and i < len(chars) - 1:
            color_cycle_number = int(chars[i + 1])
            color = mcolors.to_rgba("C{}".format(color_cycle_number))
            i += 1
        else:
            raise ValueError(
                'Unrecognized character %c in format string' % c)
        i += 1

    if linestyle is None and marker is None:
        linestyle = rcParams['lines.linestyle']
    if linestyle is None:
        linestyle = 'None'
    if marker is None:
        marker = 'None'

    return linestyle, marker, color


class _process_plot_var_args(object):
    """
    Process variable length arguments to the plot command, so that
    plot commands like the following are supported::

      plot(t, s)
      plot(t1, s1, t2, s2)
      plot(t1, s1, 'ko', t2, s2)
      plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3)

    an arbitrary number of *x*, *y*, *fmt* are allowed
    """
    def __init__(self, axes, command='plot'):
        self.axes = axes
        self.command = command
        self.set_prop_cycle()

    def __getstate__(self):
        # note: it is not possible to pickle a itertools.cycle instance
        return {'axes': self.axes, 'command': self.command}

    def __setstate__(self, state):
        self.__dict__ = state.copy()
        self.set_prop_cycle()

    def set_prop_cycle(self, *args, **kwargs):
        if not (args or kwargs) or (len(args) == 1 and args[0] is None):
            prop_cycler = rcParams['axes.prop_cycle']
        else:
            prop_cycler = cycler(*args, **kwargs)

        self.prop_cycler = itertools.cycle(prop_cycler)
        # This should make a copy
        self._prop_keys = prop_cycler.keys

    def __call__(self, *args, **kwargs):
        if self.axes.xaxis is not None and self.axes.yaxis is not None:
            xunits = kwargs.pop('xunits', self.axes.xaxis.units)

            if self.axes.name == 'polar':
                xunits = kwargs.pop('thetaunits', xunits)

            yunits = kwargs.pop('yunits', self.axes.yaxis.units)

            if self.axes.name == 'polar':
                yunits = kwargs.pop('runits', yunits)

            if xunits != self.axes.xaxis.units:
                self.axes.xaxis.set_units(xunits)

            if yunits != self.axes.yaxis.units:
                self.axes.yaxis.set_units(yunits)

        ret = self._grab_next_args(*args, **kwargs)
        return ret

    def get_next_color(self):
        """
        Return the next color in the cycle.
        """
        if 'color' not in self._prop_keys:
            return 'k'
        return six.next(self.prop_cycler)['color']

    def set_lineprops(self, line, **kwargs):
        assert self.command == 'plot', 'set_lineprops only works with "plot"'
        line.set(**kwargs)

    def set_patchprops(self, fill_poly, **kwargs):
        assert self.command == 'fill', 'set_patchprops only works with "fill"'
        fill_poly.set(**kwargs)

    def _xy_from_xy(self, x, y):
        if self.axes.xaxis is not None and self.axes.yaxis is not None:
            bx = self.axes.xaxis.update_units(x)
            by = self.axes.yaxis.update_units(y)

            if self.command != 'plot':
                # the Line2D class can handle unitized data, with
                # support for post hoc unit changes etc.  Other mpl
                # artists, e.g., Polygon which _process_plot_var_args
                # also serves on calls to fill, cannot.  So this is a
                # hack to say: if you are not "plot", which is
                # creating Line2D, then convert the data now to
                # floats.  If you are plot, pass the raw data through
                # to Line2D which will handle the conversion.  So
                # polygons will not support post hoc conversions of
                # the unit type since they are not storing the orig
                # data.  Hopefully we can rationalize this at a later
                # date - JDH
                if bx:
                    x = self.axes.convert_xunits(x)
                if by:
                    y = self.axes.convert_yunits(y)

        # like asanyarray, but converts scalar to array, and doesn't change
        # existing compatible sequences
        x = _check_1d(x)
        y = _check_1d(y)
        if x.shape[0] != y.shape[0]:
            raise ValueError("x and y must have same first dimension, but "
                             "have shapes {} and {}".format(x.shape, y.shape))
        if x.ndim > 2 or y.ndim > 2:
            raise ValueError("x and y can be no greater than 2-D, but have "
                             "shapes {} and {}".format(x.shape, y.shape))

        if x.ndim == 1:
            x = x[:, np.newaxis]
        if y.ndim == 1:
            y = y[:, np.newaxis]
        return x, y

    def _getdefaults(self, ignore, *kwargs):
        """
        Only advance the cycler if the cycler has information that
        is not specified in any of the supplied tuple of dicts.
        Ignore any keys specified in the `ignore` set.

        Returns a copy of defaults dictionary if there are any
        keys that are not found in any of the supplied dictionaries.
        If the supplied dictionaries have non-None values for
        everything the property cycler has, then just return
        an empty dictionary. Ignored keys are excluded from the
        returned dictionary.

        """
        prop_keys = self._prop_keys
        if ignore is None:
            ignore = set([])
        prop_keys = prop_keys - ignore

        if any(all(kw.get(k, None) is None for kw in kwargs)
               for k in prop_keys):
            # Need to copy this dictionary or else the next time around
            # in the cycle, the dictionary could be missing entries.
            default_dict = six.next(self.prop_cycler).copy()
            for p in ignore:
                default_dict.pop(p, None)
        else:
            default_dict = {}
        return default_dict

    def _setdefaults(self, defaults, *kwargs):
        """
        Given a defaults dictionary, and any other dictionaries,
        update those other dictionaries with information in defaults if
        none of the other dictionaries contains that information.

        """
        for k in defaults:
            if all(kw.get(k, None) is None for kw in kwargs):
                for kw in kwargs:
                    kw[k] = defaults[k]

    def _makeline(self, x, y, kw, kwargs):
        kw = kw.copy()  # Don't modify the original kw.
        kw.update(kwargs)
        default_dict = self._getdefaults(None, kw)
        self._setdefaults(default_dict, kw)
        seg = mlines.Line2D(x, y, **kw)
        return seg

    def _makefill(self, x, y, kw, kwargs):
        kw = kw.copy()  # Don't modify the original kw.
        kwargs = kwargs.copy()

        # Ignore 'marker'-related properties as they aren't Polygon
        # properties, but they are Line2D properties, and so they are
        # likely to appear in the default cycler construction.
        # This is done here to the defaults dictionary as opposed to the
        # other two dictionaries because we do want to capture when a
        # *user* explicitly specifies a marker which should be an error.
        # We also want to prevent advancing the cycler if there are no
        # defaults needed after ignoring the given properties.
        ignores = set(['marker', 'markersize', 'markeredgecolor',
                       'markerfacecolor', 'markeredgewidth'])
        # Also ignore anything provided by *kwargs*.
        for k, v in six.iteritems(kwargs):
            if v is not None:
                ignores.add(k)

        # Only using the first dictionary to use as basis
        # for getting defaults for back-compat reasons.
        # Doing it with both seems to mess things up in
        # various places (probably due to logic bugs elsewhere).
        default_dict = self._getdefaults(ignores, kw)
        self._setdefaults(default_dict, kw)

        # Looks like we don't want "color" to be interpreted to
        # mean both facecolor and edgecolor for some reason.
        # So the "kw" dictionary is thrown out, and only its
        # 'color' value is kept and translated as a 'facecolor'.
        # This design should probably be revisited as it increases
        # complexity.
        facecolor = kw.get('color', None)

        # Throw out 'color' as it is now handled as a facecolor
        default_dict.pop('color', None)

        # To get other properties set from the cycler
        # modify the kwargs dictionary.
        self._setdefaults(default_dict, kwargs)

        seg = mpatches.Polygon(np.hstack((x[:, np.newaxis],
                                          y[:, np.newaxis])),
                               facecolor=facecolor,
                               fill=kwargs.get('fill', True),
                               closed=kw['closed'])
        self.set_patchprops(seg, **kwargs)
        return seg

    def _plot_args(self, tup, kwargs):
        ret = []
        if len(tup) > 1 and is_string_like(tup[-1]):
            linestyle, marker, color = _process_plot_format(tup[-1])
            tup = tup[:-1]
        elif len(tup) == 3:
            raise ValueError('third arg must be a format string')
        else:
            linestyle, marker, color = None, None, None

        # Don't allow any None value; These will be up-converted
        # to one element array of None which causes problems
        # downstream.
        if any(v is None for v in tup):
            raise ValueError("x and y must not be None")

        kw = {}
        for k, v in zip(('linestyle', 'marker', 'color'),
                        (linestyle, marker, color)):
            if v is not None:
                kw[k] = v

        if 'label' not in kwargs or kwargs['label'] is None:
            kwargs['label'] = get_label(tup[-1], None)

        if len(tup) == 2:
            x = _check_1d(tup[0])
            y = _check_1d(tup[-1])
        else:
            x, y = index_of(tup[-1])

        x, y = self._xy_from_xy(x, y)

        if self.command == 'plot':
            func = self._makeline
        else:
            kw['closed'] = kwargs.get('closed', True)
            func = self._makefill

        ncx, ncy = x.shape[1], y.shape[1]
        for j in xrange(max(ncx, ncy)):
            seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
            ret.append(seg)
        return ret

    def _grab_next_args(self, *args, **kwargs):

        remaining = args
        while 1:

            if len(remaining) == 0:
                return
            if len(remaining) <= 3:
                for seg in self._plot_args(remaining, kwargs):
                    yield seg
                return

            if is_string_like(remaining[2]):
                isplit = 3
            else:
                isplit = 2

            for seg in self._plot_args(remaining[:isplit], kwargs):
                yield seg
            remaining = remaining[isplit:]


class _AxesBase(martist.Artist):
    """
    """
    name = "rectilinear"

    _shared_x_axes = cbook.Grouper()
    _shared_y_axes = cbook.Grouper()

    def __str__(self):
        return "Axes(%g,%g;%gx%g)" % tuple(self._position.bounds)

    def __init__(self, fig, rect,
                 facecolor=None,  # defaults to rc axes.facecolor
                 frameon=True,
                 sharex=None,  # use Axes instance's xaxis info
                 sharey=None,  # use Axes instance's yaxis info
                 label='',
                 xscale=None,
                 yscale=None,
                 axisbg=None,  # This will be removed eventually
                 **kwargs
                 ):
        """
        Build an :class:`Axes` instance in
        :class:`~matplotlib.figure.Figure` *fig* with
        *rect=[left, bottom, width, height]* in
        :class:`~matplotlib.figure.Figure` coordinates

        Optional keyword arguments:

          ================   =========================================
          Keyword            Description
          ================   =========================================
          *adjustable*       [ 'box' | 'datalim' | 'box-forced']
          *alpha*            float: the alpha transparency (can be None)
          *anchor*           [ 'C', 'SW', 'S', 'SE', 'E', 'NE', 'N',
                               'NW', 'W' ]
          *aspect*           [ 'auto' | 'equal' | aspect_ratio ]
          *autoscale_on*     [ *True* | *False* ] whether or not to
                             autoscale the *viewlim*
          *axisbelow*        [ *True* | *False* | 'line'] draw the grids
                             and ticks below or above most other artists,
                             or below lines but above patches
          *cursor_props*     a (*float*, *color*) tuple
          *figure*           a :class:`~matplotlib.figure.Figure`
                             instance
          *frame_on*         a boolean - draw the axes frame
          *label*            the axes label
          *navigate*         [ *True* | *False* ]
          *navigate_mode*    [ 'PAN' | 'ZOOM' | None ] the navigation
                             toolbar button status
          *position*         [left, bottom, width, height] in
                             class:`~matplotlib.figure.Figure` coords
          *sharex*           an class:`~matplotlib.axes.Axes` instance
                             to share the x-axis with
          *sharey*           an class:`~matplotlib.axes.Axes` instance
                             to share the y-axis with
          *title*            the title string
          *visible*          [ *True* | *False* ] whether the axes is
                             visible
          *xlabel*           the xlabel
          *xlim*             (*xmin*, *xmax*) view limits
          *xscale*           [%(scale)s]
          *xticklabels*      sequence of strings
          *xticks*           sequence of floats
          *ylabel*           the ylabel strings
          *ylim*             (*ymin*, *ymax*) view limits
          *yscale*           [%(scale)s]
          *yticklabels*      sequence of strings
          *yticks*           sequence of floats
          ================   =========================================
        """ % {'scale': ' | '.join(
            [repr(x) for x in mscale.get_scale_names()])}
        martist.Artist.__init__(self)
        if isinstance(rect, mtransforms.Bbox):
            self._position = rect
        else:
            self._position = mtransforms.Bbox.from_bounds(*rect)
        self._originalPosition = self._position.frozen()
        # self.set_axes(self)
        self.axes = self
        self.set_aspect('auto')
        self._adjustable = 'box'
        self.set_anchor('C')
        self._sharex = sharex
        self._sharey = sharey
        if sharex is not None:
            self._shared_x_axes.join(self, sharex)
            if sharex._adjustable == 'box':
                sharex._adjustable = 'datalim'
                #warnings.warn(
                #    'shared axes: "adjustable" is being changed to "datalim"')
            self._adjustable = 'datalim'
        if sharey is not None:
            self._shared_y_axes.join(self, sharey)
            if sharey._adjustable == 'box':
                sharey._adjustable = 'datalim'
                #warnings.warn(
                #    'shared axes: "adjustable" is being changed to "datalim"')
            self._adjustable = 'datalim'
        self.set_label(label)
        self.set_figure(fig)

        self.set_axes_locator(kwargs.get("axes_locator", None))

        self.spines = self._gen_axes_spines()

        # this call may differ for non-sep axes, e.g., polar
        self._init_axis()
        if axisbg is not None and facecolor is not None:
            raise TypeError('Both axisbg and facecolor are not None. '
                            'These keywords are aliases, only one may be '
                            'provided.')
        if axisbg is not None:
            cbook.warn_deprecated(
                '2.0', name='axisbg', alternative='facecolor')
            facecolor = axisbg
        if facecolor is None:
            facecolor = rcParams['axes.facecolor']
        self._facecolor = facecolor
        self._frameon = frameon
        self._axisbelow = rcParams['axes.axisbelow']

        self._rasterization_zorder = None

        self._hold = rcParams['axes.hold']
        if self._hold is None:
            self._hold = True

        self._connected = {}  # a dict from events to (id, func)
        self.cla()
        # funcs used to format x and y - fall back on major formatters
        self.fmt_xdata = None
        self.fmt_ydata = None

        self.set_cursor_props((1, 'k'))  # set the cursor properties for axes

        self._cachedRenderer = None
        self.set_navigate(True)
        self.set_navigate_mode(None)

        if xscale:
            self.set_xscale(xscale)
        if yscale:
            self.set_yscale(yscale)

        if len(kwargs):
            self.update(kwargs)

        if self.xaxis is not None:
            self._xcid = self.xaxis.callbacks.connect('units finalize',
                                                      self.relim)

        if self.yaxis is not None:
            self._ycid = self.yaxis.callbacks.connect('units finalize',
                                                      self.relim)

        self.tick_params(
            top=rcParams['xtick.top'] and rcParams['xtick.minor.top'],
            bottom=rcParams['xtick.bottom'] and rcParams['xtick.minor.bottom'],
            left=rcParams['ytick.left'] and rcParams['ytick.minor.left'],
            right=rcParams['ytick.right'] and rcParams['ytick.minor.right'],
            which='minor')

        self.tick_params(
            top=rcParams['xtick.top'] and rcParams['xtick.major.top'],
            bottom=rcParams['xtick.bottom'] and rcParams['xtick.major.bottom'],
            left=rcParams['ytick.left'] and rcParams['ytick.major.left'],
            right=rcParams['ytick.right'] and rcParams['ytick.major.right'],
            which='major')

    def __getstate__(self):
        # The renderer should be re-created by the figure, and then cached at
        # that point.
        state = super(_AxesBase, self).__getstate__()
        state['_cachedRenderer'] = None
        return state

    def __setstate__(self, state):
        self.__dict__ = state
        # put the _remove_method back on all artists contained within the axes
        for container_name in ['lines', 'collections', 'tables', 'patches',
                               'texts', 'images']:
            container = getattr(self, container_name)
            for artist in container:
                artist._remove_method = container.remove
        self._stale = True

    def get_window_extent(self, *args, **kwargs):
        """
        get the axes bounding box in display space; *args* and
        *kwargs* are empty
        """
        bbox = self.bbox
        x_pad = self.xaxis.get_tick_padding()
        y_pad = self.yaxis.get_tick_padding()
        return mtransforms.Bbox([[bbox.x0 - x_pad, bbox.y0 - y_pad],
                                 [bbox.x1 + x_pad, bbox.y1 + y_pad]])

    def _init_axis(self):
        "move this out of __init__ because non-separable axes don't use it"
        self.xaxis = maxis.XAxis(self)
        self.spines['bottom'].register_axis(self.xaxis)
        self.spines['top'].register_axis(self.xaxis)
        self.yaxis = maxis.YAxis(self)
        self.spines['left'].register_axis(self.yaxis)
        self.spines['right'].register_axis(self.yaxis)
        self._update_transScale()

    def set_figure(self, fig):
        """
        Set the class:`~matplotlib.axes.Axes` figure

        accepts a class:`~matplotlib.figure.Figure` instance
        """
        martist.Artist.set_figure(self, fig)

        self.bbox = mtransforms.TransformedBbox(self._position,
                                                fig.transFigure)
        # these will be updated later as data is added
        self.dataLim = mtransforms.Bbox.null()
        self.viewLim = mtransforms.Bbox.unit()
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        self._set_lim_and_transforms()

    def _set_lim_and_transforms(self):
        """
        set the *dataLim* and *viewLim*
        :class:`~matplotlib.transforms.Bbox` attributes and the
        *transScale*, *transData*, *transLimits* and *transAxes*
        transformations.

        .. note::

            This method is primarily used by rectilinear projections
            of the :class:`~matplotlib.axes.Axes` class, and is meant
            to be overridden by new kinds of projection axes that need
            different transformations and limits. (See
            :class:`~matplotlib.projections.polar.PolarAxes` for an
            example.

        """
        self.transAxes = mtransforms.BboxTransformTo(self.bbox)

        # Transforms the x and y axis separately by a scale factor.
        # It is assumed that this part will have non-linear components
        # (e.g., for a log scale).
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        # An affine transformation on the data, generally to limit the
        # range of the axes
        self.transLimits = mtransforms.BboxTransformFrom(
            mtransforms.TransformedBbox(self.viewLim, self.transScale))

        # The parentheses are important for efficiency here -- they
        # group the last two (which are usually affines) separately
        # from the first (which, with log-scaling can be non-affine).
        self.transData = self.transScale + (self.transLimits + self.transAxes)

        self._xaxis_transform = mtransforms.blended_transform_factory(
            self.transData, self.transAxes)
        self._yaxis_transform = mtransforms.blended_transform_factory(
            self.transAxes, self.transData)

    def get_xaxis_transform(self, which='grid'):
        """
        Get the transformation used for drawing x-axis labels, ticks
        and gridlines.  The x-direction is in data coordinates and the
        y-direction is in axis coordinates.

        .. note::

            This transformation is primarily used by the
            :class:`~matplotlib.axis.Axis` class, and is meant to be
            overridden by new kinds of projections that may need to
            place axis elements in different locations.

        """
        if which == 'grid':
            return self._xaxis_transform
        elif which == 'tick1':
            # for cartesian projection, this is bottom spine
            return self.spines['bottom'].get_spine_transform()
        elif which == 'tick2':
            # for cartesian projection, this is top spine
            return self.spines['top'].get_spine_transform()
        else:
            raise ValueError('unknown value for which')

    def get_xaxis_text1_transform(self, pad_points):
        """
        Get the transformation used for drawing x-axis labels, which
        will add the given amount of padding (in points) between the
        axes and the label.  The x-direction is in data coordinates
        and the y-direction is in axis coordinates.  Returns a
        3-tuple of the form::

          (transform, valign, halign)

        where *valign* and *halign* are requested alignments for the
        text.

        .. note::

            This transformation is primarily used by the
            :class:`~matplotlib.axis.Axis` class, and is meant to be
            overridden by new kinds of projections that may need to
            place axis elements in different locations.

        """
        return (self.get_xaxis_transform(which='tick1') +
                mtransforms.ScaledTranslation(0, -1 * pad_points / 72.0,
                                              self.figure.dpi_scale_trans),
                "top", "center")

    def get_xaxis_text2_transform(self, pad_points):
        """
        Get the transformation used for drawing the secondary x-axis
        labels, which will add the given amount of padding (in points)
        between the axes and the label.  The x-direction is in data
        coordinates and the y-direction is in axis coordinates.
        Returns a 3-tuple of the form::

          (transform, valign, halign)

        where *valign* and *halign* are requested alignments for the
        text.

        .. note::

            This transformation is primarily used by the
            :class:`~matplotlib.axis.Axis` class, and is meant to be
            overridden by new kinds of projections that may need to
            place axis elements in different locations.

        """
        return (self.get_xaxis_transform(which='tick2') +
                mtransforms.ScaledTranslation(0, pad_points / 72.0,
                                              self.figure.dpi_scale_trans),
                "bottom", "center")

    def get_yaxis_transform(self, which='grid'):
        """
        Get the transformation used for drawing y-axis labels, ticks
        and gridlines.  The x-direction is in axis coordinates and the
        y-direction is in data coordinates.

        .. note::

            This transformation is primarily used by the
            :class:`~matplotlib.axis.Axis` class, and is meant to be
            overridden by new kinds of projections that may need to
            place axis elements in different locations.

        """
        if which == 'grid':
            return self._yaxis_transform
        elif which == 'tick1':
            # for cartesian projection, this is bottom spine
            return self.spines['left'].get_spine_transform()
        elif which == 'tick2':
            # for cartesian projection, this is top spine
            return self.spines['right'].get_spine_transform()
        else:
            raise ValueError('unknown value for which')

    def get_yaxis_text1_transform(self, pad_points):
        """
        Get the transformation used for drawing y-axis labels, which
        will add the given amount of padding (in points) between the
        axes and the label.  The x-direction is in axis coordinates
        and the y-direction is in data coordinates.  Returns a 3-tuple
        of the form::

          (transform, valign, halign)

        where *valign* and *halign* are requested alignments for the
        text.

        .. note::

            This transformation is primarily used by the
            :class:`~matplotlib.axis.Axis` class, and is meant to be
            overridden by new kinds of projections that may need to
            place axis elements in different locations.

        """
        return (self.get_yaxis_transform(which='tick1') +
                mtransforms.ScaledTranslation(-1 * pad_points / 72.0, 0,
                                              self.figure.dpi_scale_trans),
                "center_baseline", "right")

    def get_yaxis_text2_transform(self, pad_points):
        """
        Get the transformation used for drawing the secondary y-axis
        labels, which will add the given amount of padding (in points)
        between the axes and the label.  The x-direction is in axis
        coordinates and the y-direction is in data coordinates.
        Returns a 3-tuple of the form::

          (transform, valign, halign)

        where *valign* and *halign* are requested alignments for the
        text.

        .. note::

            This transformation is primarily used by the
            :class:`~matplotlib.axis.Axis` class, and is meant to be
            overridden by new kinds of projections that may need to
            place axis elements in different locations.

        """
        return (self.get_yaxis_transform(which='tick2') +
                mtransforms.ScaledTranslation(pad_points / 72.0, 0,
                                              self.figure.dpi_scale_trans),
                "center_baseline", "left")

    def _update_transScale(self):
        self.transScale.set(
            mtransforms.blended_transform_factory(
                self.xaxis.get_transform(), self.yaxis.get_transform()))
        if hasattr(self, "lines"):
            for line in self.lines:
                try:
                    line._transformed_path.invalidate()
                except AttributeError:
                    pass

    def get_position(self, original=False):
        'Return the a copy of the axes rectangle as a Bbox'
        if original:
            return self._originalPosition.frozen()
        else:
            return self._position.frozen()

    def set_position(self, pos, which='both'):
        """Set the axes position

        The expected shape of ``pos`` is::

          pos = [left, bottom, width, height]

        in relative 0,1 coords, or *pos* can be a
        :class:`~matplotlib.transforms.Bbox`

        There are two position variables: one which is ultimately
        used, but which may be modified by :meth:`apply_aspect`, and a
        second which is the starting point for :meth:`apply_aspect`.


        Optional keyword arguments:
          *which*

            ==========   ====================
            value        description
            ==========   ====================
            'active'     to change the first
            'original'   to change the second
            'both'       to change both
            ==========   ====================

        """
        if not isinstance(pos, mtransforms.BboxBase):
            pos = mtransforms.Bbox.from_bounds(*pos)
        if which in ('both', 'active'):
            self._position.set(pos)
        if which in ('both', 'original'):
            self._originalPosition.set(pos)
        self.stale = True

    def reset_position(self):
        """Make the original position the active position"""
        pos = self.get_position(original=True)
        self.set_position(pos, which='active')

    def set_axes_locator(self, locator):
        """
        set axes_locator

        ACCEPT: a callable object which takes an axes instance and renderer and
                 returns a bbox.
        """
        self._axes_locator = locator
        self.stale = True

    def get_axes_locator(self):
        """
        return axes_locator
        """
        return self._axes_locator

    def _set_artist_props(self, a):
        """set the boilerplate props for artists added to axes"""
        a.set_figure(self.figure)
        if not a.is_transform_set():
            a.set_transform(self.transData)

        a.axes = self
        if a.mouseover:
            self.mouseover_set.add(a)

    def _gen_axes_patch(self):
        """
        Returns the patch used to draw the background of the axes.  It
        is also used as the clipping path for any data elements on the
        axes.

        In the standard axes, this is a rectangle, but in other
        projections it may not be.

        .. note::

            Intended to be overridden by new projection types.

        """
        return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0)

    def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'):
        """
        Returns a dict whose keys are spine names and values are
        Line2D or Patch instances. Each element is used to draw a
        spine of the axes.

        In the standard axes, this is a single line segment, but in
        other projections it may not be.

        .. note::

            Intended to be overridden by new projection types.

        """
        return OrderedDict([
            ('left', mspines.Spine.linear_spine(self, 'left')),
            ('right', mspines.Spine.linear_spine(self, 'right')),
            ('bottom', mspines.Spine.linear_spine(self, 'bottom')),
            ('top', mspines.Spine.linear_spine(self, 'top'))])

    def cla(self):
        """Clear the current axes."""
        # Note: this is called by Axes.__init__()

        # stash the current visibility state
        if hasattr(self, 'patch'):
            patch_visible = self.patch.get_visible()
        else:
            patch_visible = True

        xaxis_visible = self.xaxis.get_visible()
        yaxis_visible = self.yaxis.get_visible()

        self.xaxis.cla()
        self.yaxis.cla()
        for name, spine in six.iteritems(self.spines):
            spine.cla()

        self.ignore_existing_data_limits = True
        self.callbacks = cbook.CallbackRegistry()

        if self._sharex is not None:
            # major and minor are class instances with
            # locator and formatter attributes
            self.xaxis.major = self._sharex.xaxis.major
            self.xaxis.minor = self._sharex.xaxis.minor
            x0, x1 = self._sharex.get_xlim()
            self.set_xlim(x0, x1, emit=False, auto=None)

            # Save the current formatter/locator so we don't lose it
            majf = self._sharex.xaxis.get_major_formatter()
            minf = self._sharex.xaxis.get_minor_formatter()
            majl = self._sharex.xaxis.get_major_locator()
            minl = self._sharex.xaxis.get_minor_locator()

            # This overwrites the current formatter/locator
            self.xaxis._set_scale(self._sharex.xaxis.get_scale())

            # Reset the formatter/locator
            self.xaxis.set_major_formatter(majf)
            self.xaxis.set_minor_formatter(minf)
            self.xaxis.set_major_locator(majl)
            self.xaxis.set_minor_locator(minl)
        else:
            self.xaxis._set_scale('linear')

        if self._sharey is not None:
            self.yaxis.major = self._sharey.yaxis.major
            self.yaxis.minor = self._sharey.yaxis.minor
            y0, y1 = self._sharey.get_ylim()
            self.set_ylim(y0, y1, emit=False, auto=None)

            # Save the current formatter/locator so we don't lose it
            majf = self._sharey.yaxis.get_major_formatter()
            minf = self._sharey.yaxis.get_minor_formatter()
            majl = self._sharey.yaxis.get_major_locator()
            minl = self._sharey.yaxis.get_minor_locator()

            # This overwrites the current formatter/locator
            self.yaxis._set_scale(self._sharey.yaxis.get_scale())

            # Reset the formatter/locator
            self.yaxis.set_major_formatter(majf)
            self.yaxis.set_minor_formatter(minf)
            self.yaxis.set_major_locator(majl)
            self.yaxis.set_minor_locator(minl)
        else:
            self.yaxis._set_scale('linear')

        # update the minor locator for x and y axis based on rcParams
        if (rcParams['xtick.minor.visible']):
            self.xaxis.set_minor_locator(mticker.AutoMinorLocator())

        if (rcParams['ytick.minor.visible']):
            self.yaxis.set_minor_locator(mticker.AutoMinorLocator())

        self._autoscaleXon = True
        self._autoscaleYon = True
        self._xmargin = rcParams['axes.xmargin']
        self._ymargin = rcParams['axes.ymargin']
        self._tight = None
        self._use_sticky_edges = True
        self._update_transScale()  # needed?

        self._get_lines = _process_plot_var_args(self)
        self._get_patches_for_fill = _process_plot_var_args(self, 'fill')

        self._gridOn = rcParams['axes.grid']
        self.lines = []
        self.patches = []
        self.texts = []
        self.tables = []
        self.artists = []
        self.images = []
        self.mouseover_set = set()
        self._current_image = None  # strictly for pyplot via _sci, _gci
        self.legend_ = None
        self.collections = []  # collection.Collection instances
        self.containers = []

        self.grid(False)  # Disable grid on init to use rcParameter
        self.grid(self._gridOn, which=rcParams['axes.grid.which'],
                    axis=rcParams['axes.grid.axis'])
        props = font_manager.FontProperties(
                    size=rcParams['axes.titlesize'],
                    weight=rcParams['axes.titleweight']
                )
        title_offset_points = rcParams['axes.titlepad']
        self.titleOffsetTrans = mtransforms.ScaledTranslation(
            0.0, title_offset_points / 72.0,
            self.figure.dpi_scale_trans)
        self.title = mtext.Text(
            x=0.5, y=1.0, text='',
            fontproperties=props,
            verticalalignment='baseline',
            horizontalalignment='center',
            )
        self._left_title = mtext.Text(
            x=0.0, y=1.0, text='',
            fontproperties=props.copy(),
            verticalalignment='baseline',
            horizontalalignment='left', )
        self._right_title = mtext.Text(
            x=1.0, y=1.0, text='',
            fontproperties=props.copy(),
            verticalalignment='baseline',
            horizontalalignment='right',
            )

        for _title in (self.title, self._left_title, self._right_title):
            _title.set_transform(self.transAxes + self.titleOffsetTrans)
            _title.set_clip_box(None)
            self._set_artist_props(_title)

        # the patch draws the background of the axes.  we want this to
        # be below the other artists; the axesPatch name is
        # deprecated.  We use the frame to draw the edges so we are
        # setting the edgecolor to None
        self.patch = self.axesPatch = self._gen_axes_patch()
        self.patch.set_figure(self.figure)
        self.patch.set_facecolor(self._facecolor)
        self.patch.set_edgecolor('None')
        self.patch.set_linewidth(0)
        self.patch.set_transform(self.transAxes)

        self.set_axis_on()

        self.xaxis.set_clip_path(self.patch)
        self.yaxis.set_clip_path(self.patch)

        self._shared_x_axes.clean()
        self._shared_y_axes.clean()
        if self._sharex:
            self.xaxis.set_visible(xaxis_visible)
            self.patch.set_visible(patch_visible)

        if self._sharey:
            self.yaxis.set_visible(yaxis_visible)
            self.patch.set_visible(patch_visible)
        self.stale = True

    def clear(self):
        """clear the axes"""
        self.cla()

    def get_facecolor(self):
        return self.patch.get_facecolor()
    get_fc = get_facecolor

    def set_facecolor(self, color):
        self._facecolor = color
        return self.patch.set_facecolor(color)
    set_fc = set_facecolor

    def set_prop_cycle(self, *args, **kwargs):
        """
        Set the property cycle for any future plot commands on this Axes.

        set_prop_cycle(arg)
        set_prop_cycle(label, itr)
        set_prop_cycle(label1=itr1[, label2=itr2[, ...]])

        Form 1 simply sets given `Cycler` object.

        Form 2 creates and sets  a `Cycler` from a label and an iterable.

        Form 3 composes and sets  a `Cycler` as an inner product of the
        pairs of keyword arguments. In other words, all of the
        iterables are cycled simultaneously, as if through zip().

        Parameters
        ----------
        arg : Cycler
            Set the given Cycler.
            Can also be `None` to reset to the cycle defined by the
            current style.

        label : str
            The property key. Must be a valid `Artist` property.
            For example, 'color' or 'linestyle'. Aliases are allowed,
            such as 'c' for 'color' and 'lw' for 'linewidth'.

        itr : iterable
            Finite-length iterable of the property values. These values
            are validated and will raise a ValueError if invalid.

        See Also
        --------
            :func:`cycler`      Convenience function for creating your
                                own cyclers.

        """
        if args and kwargs:
            raise TypeError("Cannot supply both positional and keyword "
                            "arguments to this method.")
        if len(args) == 1 and args[0] is None:
            prop_cycle = None
        else:
            prop_cycle = cycler(*args, **kwargs)
        self._get_lines.set_prop_cycle(prop_cycle)
        self._get_patches_for_fill.set_prop_cycle(prop_cycle)

    def set_color_cycle(self, clist):
        """
        Set the color cycle for any future plot commands on this Axes.

        *clist* is a list of mpl color specifiers.

        .. deprecated:: 1.5
        """
        cbook.warn_deprecated(
                '1.5', name='set_color_cycle', alternative='set_prop_cycle')
        if clist is None:
            # Calling set_color_cycle() or set_prop_cycle() with None
            # effectively resets the cycle, but you can't do
            # set_prop_cycle('color', None). So we are special-casing this.
            self.set_prop_cycle(None)
        else:
            self.set_prop_cycle('color', clist)

    @cbook.deprecated("2.0")
    def ishold(self):
        """return the HOLD status of the axes

        The `hold` mechanism is deprecated and will be removed in
        v3.0.
        """

        return self._hold

    @cbook.deprecated("2.0", message=_hold_msg)
    def hold(self, b=None):
        """
        Set the hold state

        The ``hold`` mechanism is deprecated and will be removed in
        v3.0.  The behavior will remain consistent with the
        long-time default value of True.

        If *hold* is *None* (default), toggle the *hold* state.  Else
        set the *hold* state to boolean value *b*.

        Examples::

          # toggle hold
          hold()

          # turn hold on
          hold(True)

          # turn hold off
          hold(False)

        When hold is *True*, subsequent plot commands will be added to
        the current axes.  When hold is *False*, the current axes and
        figure will be cleared on the next plot command

        """
        if b is None:
            self._hold = not self._hold
        else:
            self._hold = b

    def get_aspect(self):
        return self._aspect

    def set_aspect(self, aspect, adjustable=None, anchor=None):
        """
        *aspect*

          ========   ================================================
          value      description
          ========   ================================================
          'auto'     automatic; fill position rectangle with data
          'normal'   same as 'auto'; deprecated
          'equal'    same scaling from data to plot units for x and y
           num       a circle will be stretched such that the height
                     is num times the width. aspect=1 is the same as
                     aspect='equal'.
          ========   ================================================

        *adjustable*

          ============   =====================================
          value          description
          ============   =====================================
          'box'          change physical size of axes
          'datalim'      change xlim or ylim
          'box-forced'   same as 'box', but axes can be shared
          ============   =====================================

        'box' does not allow axes sharing, as this can cause
        unintended side effect. For cases when sharing axes is
        fine, use 'box-forced'.

        *anchor*

          =====   =====================
          value   description
          =====   =====================
          'C'     centered
          'SW'    lower left corner
          'S'     middle of bottom edge
          'SE'    lower right corner
          etc.
          =====   =====================

        .. deprecated:: 1.2
            the option 'normal' for aspect is deprecated. Use 'auto' instead.
        """
        if aspect == 'normal':
            cbook.warn_deprecated(
                '1.2', name='normal', alternative='auto', obj_type='aspect')
            self._aspect = 'auto'

        elif aspect in ('equal', 'auto'):
            self._aspect = aspect
        else:
            self._aspect = float(aspect)  # raise ValueError if necessary

        if adjustable is not None:
            self.set_adjustable(adjustable)
        if anchor is not None:
            self.set_anchor(anchor)
        self.stale = True

    def get_adjustable(self):
        return self._adjustable

    def set_adjustable(self, adjustable):
        """
        ACCEPTS: [ 'box' | 'datalim' | 'box-forced']
        """
        if adjustable in ('box', 'datalim', 'box-forced'):
            if self in self._shared_x_axes or self in self._shared_y_axes:
                if adjustable == 'box':
                    raise ValueError(
                        'adjustable must be "datalim" for shared axes')
            self._adjustable = adjustable
        else:
            raise ValueError('argument must be "box", or "datalim"')
        self.stale = True

    def get_anchor(self):
        return self._anchor

    def set_anchor(self, anchor):
        """
        *anchor*

          =====  ============
          value  description
          =====  ============
          'C'    Center
          'SW'   bottom left
          'S'    bottom
          'SE'   bottom right
          'E'    right
          'NE'   top right
          'N'    top
          'NW'   top left
          'W'    left
          =====  ============

        """
        if (anchor in list(six.iterkeys(mtransforms.Bbox.coefs)) or
                len(anchor) == 2):
            self._anchor = anchor
        else:
            raise ValueError('argument must be among %s' %
                             ', '.join(six.iterkeys(mtransforms.Bbox.coefs)))
        self.stale = True

    def get_data_ratio(self):
        """
        Returns the aspect ratio of the raw data.

        This method is intended to be overridden by new projection
        types.
        """
        xmin, xmax = self.get_xbound()
        ymin, ymax = self.get_ybound()

        xsize = max(math.fabs(xmax - xmin), 1e-30)
        ysize = max(math.fabs(ymax - ymin), 1e-30)

        return ysize / xsize

    def get_data_ratio_log(self):
        """
        Returns the aspect ratio of the raw data in log scale.
        Will be used when both axis scales are in log.
        """
        xmin, xmax = self.get_xbound()
        ymin, ymax = self.get_ybound()

        xsize = max(math.fabs(math.log10(xmax) - math.log10(xmin)), 1e-30)
        ysize = max(math.fabs(math.log10(ymax) - math.log10(ymin)), 1e-30)

        return ysize / xsize

    def apply_aspect(self, position=None):
        """
        Use :meth:`_aspect` and :meth:`_adjustable` to modify the
        axes box or the view limits.
        """
        if position is None:
            position = self.get_position(original=True)

        aspect = self.get_aspect()

        if self.name != 'polar':
            xscale, yscale = self.get_xscale(), self.get_yscale()
            if xscale == "linear" and yscale == "linear":
                aspect_scale_mode = "linear"
            elif xscale == "log" and yscale == "log":
                aspect_scale_mode = "log"
            elif ((xscale == "linear" and yscale == "log") or
                  (xscale == "log" and yscale == "linear")):
                if aspect != "auto":
                    warnings.warn(
                        'aspect is not supported for Axes with xscale=%s, '
                        'yscale=%s' % (xscale, yscale))
                    aspect = "auto"
            else:  # some custom projections have their own scales.
                pass
        else:
            aspect_scale_mode = "linear"

        if aspect == 'auto':
            self.set_position(position, which='active')
            return

        if aspect == 'equal':
            A = 1
        else:
            A = aspect

        # Ensure at drawing time that any Axes involved in axis-sharing
        # does not have its position changed.
        if self in self._shared_x_axes or self in self._shared_y_axes:
            if self._adjustable == 'box':
                self._adjustable = 'datalim'
                warnings.warn(
                    'shared axes: "adjustable" is being changed to "datalim"')

        figW, figH = self.get_figure().get_size_inches()
        fig_aspect = figH / figW
        if self._adjustable in ['box', 'box-forced']:
            if aspect_scale_mode == "log":
                box_aspect = A * self.get_data_ratio_log()
            else:
                box_aspect = A * self.get_data_ratio()
            pb = position.frozen()
            pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect)
            self.set_position(pb1.anchored(self.get_anchor(), pb), 'active')
            return

        # reset active to original in case it had been changed
        # by prior use of 'box'
        self.set_position(position, which='active')

        xmin, xmax = self.get_xbound()
        ymin, ymax = self.get_ybound()

        if aspect_scale_mode == "log":
            xmin, xmax = math.log10(xmin), math.log10(xmax)
            ymin, ymax = math.log10(ymin), math.log10(ymax)

        xsize = max(math.fabs(xmax - xmin), 1e-30)
        ysize = max(math.fabs(ymax - ymin), 1e-30)

        l, b, w, h = position.bounds
        box_aspect = fig_aspect * (h / w)
        data_ratio = box_aspect / A

        y_expander = (data_ratio * xsize / ysize - 1.0)
        # If y_expander > 0, the dy/dx viewLim ratio needs to increase
        if abs(y_expander) < 0.005:
            return

        if aspect_scale_mode == "log":
            dL = self.dataLim
            dL_width = math.log10(dL.x1) - math.log10(dL.x0)
            dL_height = math.log10(dL.y1) - math.log10(dL.y0)
            xr = 1.05 * dL_width
            yr = 1.05 * dL_height
        else:
            dL = self.dataLim
            xr = 1.05 * dL.width
            yr = 1.05 * dL.height

        xmarg = xsize - xr
        ymarg = ysize - yr
        Ysize = data_ratio * xsize
        Xsize = ysize / data_ratio
        Xmarg = Xsize - xr
        Ymarg = Ysize - yr
        # Setting these targets to, e.g., 0.05*xr does not seem to
        # help.
        xm = 0
        ym = 0

        changex = (self in self._shared_y_axes and
                   self not in self._shared_x_axes)
        changey = (self in self._shared_x_axes and
                   self not in self._shared_y_axes)
        if changex and changey:
            warnings.warn("adjustable='datalim' cannot work with shared "
                          "x and y axes")
            return
        if changex:
            adjust_y = False
        else:
            if xmarg > xm and ymarg > ym:
                adjy = ((Ymarg > 0 and y_expander < 0) or
                        (Xmarg < 0 and y_expander > 0))
            else:
                adjy = y_expander > 0
            adjust_y = changey or adjy  # (Ymarg > xmarg)
        if adjust_y:
            yc = 0.5 * (ymin + ymax)
            y0 = yc - Ysize / 2.0
            y1 = yc + Ysize / 2.0
            if aspect_scale_mode == "log":
                self.set_ybound((10. ** y0, 10. ** y1))
            else:
                self.set_ybound((y0, y1))
        else:
            xc = 0.5 * (xmin + xmax)
            x0 = xc - Xsize / 2.0
            x1 = xc + Xsize / 2.0
            if aspect_scale_mode == "log":
                self.set_xbound((10. ** x0, 10. ** x1))
            else:
                self.set_xbound((x0, x1))

    def axis(self, *v, **kwargs):
        """Set axis properties.

        Valid signatures::

          xmin, xmax, ymin, ymax = axis()
          xmin, xmax, ymin, ymax = axis(list_arg)
          xmin, xmax, ymin, ymax = axis(string_arg)
          xmin, xmax, ymin, ymax = axis(**kwargs)

        Parameters
        ----------
        v : list of float or {'on', 'off', 'equal', 'tight', 'scaled',\
            'normal', 'auto', 'image', 'square'}
            Optional positional argument

            Axis data limits set from a list; or a command relating to axes:

                ========== ================================================
                Value      Description
                ========== ================================================
                'on'       Toggle axis lines and labels on
                'off'      Toggle axis lines and labels off
                'equal'    Equal scaling by changing limits
                'scaled'   Equal scaling by changing box dimensions
                'tight'    Limits set such that all data is shown
                'auto'     Automatic scaling, fill rectangle with data
                'normal'   Same as 'auto'; deprecated
                'image'    'scaled' with axis limits equal to data limits
                'square'   Square plot; similar to 'scaled', but initially\
                           forcing xmax-xmin = ymax-ymin
                ========== ================================================

        emit : bool, optional
            Passed to set_{x,y}lim functions, if observers
            are notified of axis limit change

        xmin, ymin, xmax, ymax : float, optional
            The axis limits to be set

        Returns
        -------
        xmin, xmax, ymin, ymax : float
            The axis limits

        """

        if len(v) == 0 and len(kwargs) == 0:
            xmin, xmax = self.get_xlim()
            ymin, ymax = self.get_ylim()
            return xmin, xmax, ymin, ymax

        emit = kwargs.get('emit', True)

        if len(v) == 1 and is_string_like(v[0]):
            s = v[0].lower()
            if s == 'on':
                self.set_axis_on()
            elif s == 'off':
                self.set_axis_off()
            elif s in ('equal', 'tight', 'scaled', 'normal',
                       'auto', 'image', 'square'):
                self.set_autoscale_on(True)
                self.set_aspect('auto')
                self.autoscale_view(tight=False)
                # self.apply_aspect()
                if s == 'equal':
                    self.set_aspect('equal', adjustable='datalim')
                elif s == 'scaled':
                    self.set_aspect('equal', adjustable='box', anchor='C')
                    self.set_autoscale_on(False)  # Req. by Mark Bakker
                elif s == 'tight':
                    self.autoscale_view(tight=True)
                    self.set_autoscale_on(False)
                elif s == 'image':
                    self.autoscale_view(tight=True)
                    self.set_autoscale_on(False)
                    self.set_aspect('equal', adjustable='box', anchor='C')
                elif s == 'square':
                    self.set_aspect('equal', adjustable='box', anchor='C')
                    self.set_autoscale_on(False)
                    xlim = self.get_xlim()
                    ylim = self.get_ylim()
                    edge_size = max(np.diff(xlim), np.diff(ylim))
                    self.set_xlim([xlim[0], xlim[0] + edge_size],
                                  emit=emit, auto=False)
                    self.set_ylim([ylim[0], ylim[0] + edge_size],
                                  emit=emit, auto=False)
            else:
                raise ValueError('Unrecognized string %s to axis; '
                                 'try on or off' % s)
            xmin, xmax = self.get_xlim()
            ymin, ymax = self.get_ylim()
            return xmin, xmax, ymin, ymax

        try:
            v[0]
        except IndexError:
            xmin = kwargs.get('xmin', None)
            xmax = kwargs.get('xmax', None)
            auto = False  # turn off autoscaling, unless...
            if xmin is None and xmax is None:
                auto = None  # leave autoscaling state alone
            xmin, xmax = self.set_xlim(xmin, xmax, emit=emit, auto=auto)

            ymin = kwargs.get('ymin', None)
            ymax = kwargs.get('ymax', None)
            auto = False  # turn off autoscaling, unless...
            if ymin is None and ymax is None:
                auto = None  # leave autoscaling state alone
            ymin, ymax = self.set_ylim(ymin, ymax, emit=emit, auto=auto)
            return xmin, xmax, ymin, ymax

        v = v[0]
        if len(v) != 4:
            raise ValueError('v must contain [xmin xmax ymin ymax]')

        self.set_xlim([v[0], v[1]], emit=emit, auto=False)
        self.set_ylim([v[2], v[3]], emit=emit, auto=False)

        return v

    def get_legend(self):
        """
        Return the legend.Legend instance, or None if no legend is defined
        """
        return self.legend_

    def get_images(self):
        """return a list of Axes images contained by the Axes"""
        return cbook.silent_list('AxesImage', self.images)

    def get_lines(self):
        """Return a list of lines contained by the Axes"""
        return cbook.silent_list('Line2D', self.lines)

    def get_xaxis(self):
        """Return the XAxis instance"""
        return self.xaxis

    def get_xgridlines(self):
        """Get the x grid lines as a list of Line2D instances"""
        return cbook.silent_list('Line2D xgridline',
                                 self.xaxis.get_gridlines())

    def get_xticklines(self):
        """Get the xtick lines as a list of Line2D instances"""
        return cbook.silent_list('Text xtickline',
                                 self.xaxis.get_ticklines())

    def get_yaxis(self):
        """Return the YAxis instance"""
        return self.yaxis

    def get_ygridlines(self):
        """Get the y grid lines as a list of Line2D instances"""
        return cbook.silent_list('Line2D ygridline',
                                 self.yaxis.get_gridlines())

    def get_yticklines(self):
        """Get the ytick lines as a list of Line2D instances"""
        return cbook.silent_list('Line2D ytickline',
                                 self.yaxis.get_ticklines())

    # Adding and tracking artists

    def _sci(self, im):
        """
        helper for :func:`~matplotlib.pyplot.sci`;
        do not use elsewhere.
        """
        if isinstance(im, matplotlib.contour.ContourSet):
            if im.collections[0] not in self.collections:
                raise ValueError(
                    "ContourSet must be in current Axes")
        elif im not in self.images and im not in self.collections:
            raise ValueError(
                "Argument must be an image, collection, or ContourSet in "
                "this Axes")
        self._current_image = im

    def _gci(self):
        """
        Helper for :func:`~matplotlib.pyplot.gci`;
        do not use elsewhere.
        """
        return self._current_image

    def has_data(self):
        """
        Return *True* if any artists have been added to axes.

        This should not be used to determine whether the *dataLim*
        need to be updated, and may not actually be useful for
        anything.
        """
        return (
            len(self.collections) +
            len(self.images) +
            len(self.lines) +
            len(self.patches)) > 0

    def add_artist(self, a):
        """Add any :class:`~matplotlib.artist.Artist` to the axes.

        Use `add_artist` only for artists for which there is no dedicated
        "add" method; and if necessary, use a method such as
        `update_datalim` or `update_datalim_numerix` to manually update the
        dataLim if the artist is to be included in autoscaling.

        Returns the artist.
        """
        a.axes = self
        self.artists.append(a)
        self._set_artist_props(a)
        a.set_clip_path(self.patch)
        a._remove_method = lambda h: self.artists.remove(h)
        self.stale = True
        return a

    def add_collection(self, collection, autolim=True):
        """
        Add a :class:`~matplotlib.collections.Collection` instance
        to the axes.

        Returns the collection.
        """
        label = collection.get_label()
        if not label:
            collection.set_label('_collection%d' % len(self.collections))
        self.collections.append(collection)
        self._set_artist_props(collection)

        if collection.get_clip_path() is None:
            collection.set_clip_path(self.patch)

        if autolim:
            self.update_datalim(collection.get_datalim(self.transData))

        collection._remove_method = lambda h: self.collections.remove(h)
        self.stale = True
        return collection

    def add_image(self, image):
        """
        Add a :class:`~matplotlib.image.AxesImage` to the axes.

        Returns the image.
        """
        self._set_artist_props(image)
        if not image.get_label():
            image.set_label('_image%d' % len(self.images))
        self.images.append(image)
        image._remove_method = lambda h: self.images.remove(h)
        self.stale = True
        return image

    def add_line(self, line):
        """
        Add a :class:`~matplotlib.lines.Line2D` to the list of plot
        lines

        Returns the line.
        """
        self._set_artist_props(line)
        if line.get_clip_path() is None:
            line.set_clip_path(self.patch)

        self._update_line_limits(line)
        if not line.get_label():
            line.set_label('_line%d' % len(self.lines))
        self.lines.append(line)
        line._remove_method = lambda h: self.lines.remove(h)
        self.stale = True
        return line

    def _add_text(self, txt):
        """

        """
        self._set_artist_props(txt)
        self.texts.append(txt)
        txt._remove_method = lambda h: self.texts.remove(h)
        self.stale = True
        return txt

    def _update_line_limits(self, line):
        """
        Figures out the data limit of the given line, updating self.dataLim.
        """
        path = line.get_path()
        if path.vertices.size == 0:
            return

        line_trans = line.get_transform()

        if line_trans == self.transData:
            data_path = path

        elif any(line_trans.contains_branch_seperately(self.transData)):
            # identify the transform to go from line's coordinates
            # to data coordinates
            trans_to_data = line_trans - self.transData

            # if transData is affine we can use the cached non-affine component
            # of line's path. (since the non-affine part of line_trans is
            # entirely encapsulated in trans_to_data).
            if self.transData.is_affine:
                line_trans_path = line._get_transformed_path()
                na_path, _ = line_trans_path.get_transformed_path_and_affine()
                data_path = trans_to_data.transform_path_affine(na_path)
            else:
                data_path = trans_to_data.transform_path(path)
        else:
            # for backwards compatibility we update the dataLim with the
            # coordinate range of the given path, even though the coordinate
            # systems are completely different. This may occur in situations
            # such as when ax.transAxes is passed through for absolute
            # positioning.
            data_path = path

        if data_path.vertices.size > 0:
            updatex, updatey = line_trans.contains_branch_seperately(
                self.transData)
            self.dataLim.update_from_path(data_path,
                                          self.ignore_existing_data_limits,
                                          updatex=updatex,
                                          updatey=updatey)
            self.ignore_existing_data_limits = False

    def add_patch(self, p):
        """
        Add a :class:`~matplotlib.patches.Patch` *p* to the list of
        axes patches; the clipbox will be set to the Axes clipping
        box.  If the transform is not set, it will be set to
        :attr:`transData`.

        Returns the patch.
        """

        self._set_artist_props(p)
        if p.get_clip_path() is None:
            p.set_clip_path(self.patch)
        self._update_patch_limits(p)
        self.patches.append(p)
        p._remove_method = lambda h: self.patches.remove(h)
        return p

    def _update_patch_limits(self, patch):
        """update the data limits for patch *p*"""
        # hist can add zero height Rectangles, which is useful to keep
        # the bins, counts and patches lined up, but it throws off log
        # scaling.  We'll ignore rects with zero height or width in
        # the auto-scaling

        # cannot check for '==0' since unitized data may not compare to zero
        # issue #2150 - we update the limits if patch has non zero width
        # or height.
        if (isinstance(patch, mpatches.Rectangle) and
                ((not patch.get_width()) and (not patch.get_height()))):
            return
        vertices = patch.get_path().vertices
        if vertices.size > 0:
            xys = patch.get_patch_transform().transform(vertices)
            if patch.get_data_transform() != self.transData:
                patch_to_data = (patch.get_data_transform() -
                                 self.transData)
                xys = patch_to_data.transform(xys)

            updatex, updatey = patch.get_transform().\
                contains_branch_seperately(self.transData)
            self.update_datalim(xys, updatex=updatex,
                                updatey=updatey)

    def add_table(self, tab):
        """
        Add a :class:`~matplotlib.tables.Table` instance to the
        list of axes tables

        Returns the table.
        """
        self._set_artist_props(tab)
        self.tables.append(tab)
        tab.set_clip_path(self.patch)
        tab._remove_method = lambda h: self.tables.remove(h)
        return tab

    def add_container(self, container):
        """
        Add a :class:`~matplotlib.container.Container` instance
        to the axes.

        Returns the collection.
        """
        label = container.get_label()
        if not label:
            container.set_label('_container%d' % len(self.containers))
        self.containers.append(container)
        container.set_remove_method(lambda h: self.containers.remove(h))
        return container

    def relim(self, visible_only=False):
        """
        Recompute the data limits based on current artists. If you want to
        exclude invisible artists from the calculation, set
        ``visible_only=True``

        At present, :class:`~matplotlib.collections.Collection`
        instances are not supported.
        """
        # Collections are deliberately not supported (yet); see
        # the TODO note in artists.py.
        self.dataLim.ignore(True)
        self.dataLim.set_points(mtransforms.Bbox.null().get_points())
        self.ignore_existing_data_limits = True

        for line in self.lines:
            if not visible_only or line.get_visible():
                self._update_line_limits(line)

        for p in self.patches:
            if not visible_only or p.get_visible():
                self._update_patch_limits(p)

    def update_datalim(self, xys, updatex=True, updatey=True):
        """
        Update the data lim bbox with seq of xy tups or equiv. 2-D array
        """
        # if no data is set currently, the bbox will ignore its
        # limits and set the bound to be the bounds of the xydata.
        # Otherwise, it will compute the bounds of it's current data
        # and the data in xydata

        if iterable(xys) and not len(xys):
            return
        if not ma.isMaskedArray(xys):
            xys = np.asarray(xys)
        self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits,
                                         updatex=updatex, updatey=updatey)
        self.ignore_existing_data_limits = False

    @cbook.deprecated('2.0', alternative='update_datalim')
    def update_datalim_numerix(self, x, y):
        """
        Update the data lim bbox with seq of xy tups
        """
        # if no data is set currently, the bbox will ignore it's
        # limits and set the bound to be the bounds of the xydata.
        # Otherwise, it will compute the bounds of it's current data
        # and the data in xydata
        if iterable(x) and not len(x):
            return
        self.dataLim.update_from_data(x, y, self.ignore_existing_data_limits)
        self.ignore_existing_data_limits = False

    def update_datalim_bounds(self, bounds):
        """
        Update the datalim to include the given
        :class:`~matplotlib.transforms.Bbox` *bounds*
        """
        self.dataLim.set(mtransforms.Bbox.union([self.dataLim, bounds]))

    def _process_unit_info(self, xdata=None, ydata=None, kwargs=None):
        """Look for unit *kwargs* and update the axis instances as necessary"""

        if self.xaxis is None or self.yaxis is None:
            return

        if xdata is not None:
            # we only need to update if there is nothing set yet.
            if not self.xaxis.have_units():
                self.xaxis.update_units(xdata)

        if ydata is not None:
            # we only need to update if there is nothing set yet.
            if not self.yaxis.have_units():
                self.yaxis.update_units(ydata)

        # process kwargs 2nd since these will override default units
        if kwargs is not None:
            xunits = kwargs.pop('xunits', self.xaxis.units)
            if self.name == 'polar':
                xunits = kwargs.pop('thetaunits', xunits)
            if xunits != self.xaxis.units:
                self.xaxis.set_units(xunits)
                # If the units being set imply a different converter,
                # we need to update.
                if xdata is not None:
                    self.xaxis.update_units(xdata)

            yunits = kwargs.pop('yunits', self.yaxis.units)
            if self.name == 'polar':
                yunits = kwargs.pop('runits', yunits)
            if yunits != self.yaxis.units:
                self.yaxis.set_units(yunits)
                # If the units being set imply a different converter,
                # we need to update.
                if ydata is not None:
                    self.yaxis.update_units(ydata)

    def in_axes(self, mouseevent):
        """
        Return *True* if the given *mouseevent* (in display coords)
        is in the Axes
        """
        return self.patch.contains(mouseevent)[0]

    def get_autoscale_on(self):
        """
        Get whether autoscaling is applied for both axes on plot commands
        """
        return self._autoscaleXon and self._autoscaleYon

    def get_autoscalex_on(self):
        """
        Get whether autoscaling for the x-axis is applied on plot commands
        """
        return self._autoscaleXon

    def get_autoscaley_on(self):
        """
        Get whether autoscaling for the y-axis is applied on plot commands
        """
        return self._autoscaleYon

    def set_autoscale_on(self, b):
        """
        Set whether autoscaling is applied on plot commands

        accepts: [ *True* | *False* ]
        """
        self._autoscaleXon = b
        self._autoscaleYon = b

    def set_autoscalex_on(self, b):
        """
        Set whether autoscaling for the x-axis is applied on plot commands

        accepts: [ *True* | *False* ]
        """
        self._autoscaleXon = b

    def set_autoscaley_on(self, b):
        """
        Set whether autoscaling for the y-axis is applied on plot commands

        accepts: [ *True* | *False* ]
        """
        self._autoscaleYon = b

    @property
    def use_sticky_edges(self):
        """
        When autoscaling, whether to obey all `Artist.sticky_edges`.

        Default is ``True``.

        Setting this to ``False`` ensures that the specified margins
        will be applied, even if the plot includes an image, for
        example, which would otherwise force a view limit to coincide
        with its data limit.

        The changing this property does not change the plot until
        `autoscale` or `autoscale_view` is called.
        """
        return self._use_sticky_edges

    @use_sticky_edges.setter
    def use_sticky_edges(self, b):
        self._use_sticky_edges = bool(b)
        # No effect until next autoscaling, which will mark the axes as stale.

    def set_xmargin(self, m):
        """
        Set padding of X data limits prior to autoscaling.

        *m* times the data interval will be added to each
        end of that interval before it is used in autoscaling.

        accepts: float in range 0 to 1
        """
        if m < 0 or m > 1:
            raise ValueError("margin must be in range 0 to 1")
        self._xmargin = m
        self.stale = True

    def set_ymargin(self, m):
        """
        Set padding of Y data limits prior to autoscaling.

        *m* times the data interval will be added to each
        end of that interval before it is used in autoscaling.

        accepts: float in range 0 to 1
        """
        if m < 0 or m > 1:
            raise ValueError("margin must be in range 0 to 1")
        self._ymargin = m
        self.stale = True

    def margins(self, *args, **kw):
        """
        Set or retrieve autoscaling margins.

        signatures::

            margins()

        returns xmargin, ymargin

        ::

            margins(margin)

            margins(xmargin, ymargin)

            margins(x=xmargin, y=ymargin)

            margins(..., tight=False)

        All three forms above set the xmargin and ymargin parameters.
        All keyword parameters are optional.  A single argument
        specifies both xmargin and ymargin.  The *tight* parameter
        is passed to :meth:`autoscale_view`, which is executed after
        a margin is changed; the default here is *True*, on the
        assumption that when margins are specified, no additional
        padding to match tick marks is usually desired.  Setting
        *tight* to *None* will preserve the previous setting.

        Specifying any margin changes only the autoscaling; for example,
        if *xmargin* is not None, then *xmargin* times the X data
        interval will be added to each end of that interval before
        it is used in autoscaling.

        """
        if not args and not kw:
            return self._xmargin, self._ymargin

        tight = kw.pop('tight', True)
        mx = kw.pop('x', None)
        my = kw.pop('y', None)
        if len(args) == 1:
            mx = my = args[0]
        elif len(args) == 2:
            mx, my = args
        elif len(args) > 2:
            raise ValueError("more than two arguments were supplied")
        if mx is not None:
            self.set_xmargin(mx)
        if my is not None:
            self.set_ymargin(my)

        scalex = (mx is not None)
        scaley = (my is not None)

        self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley)

    def set_rasterization_zorder(self, z):
        """
        Set zorder value below which artists will be rasterized.  Set
        to `None` to disable rasterizing of artists below a particular
        zorder.
        """
        self._rasterization_zorder = z
        self.stale = True

    def get_rasterization_zorder(self):
        """
        Get zorder value below which artists will be rasterized
        """
        return self._rasterization_zorder

    def autoscale(self, enable=True, axis='both', tight=None):
        """
        Autoscale the axis view to the data (toggle).

        Convenience method for simple axis view autoscaling.
        It turns autoscaling on or off, and then,
        if autoscaling for either axis is on, it performs
        the autoscaling on the specified axis or axes.

        *enable*: [True | False | None]
            True (default) turns autoscaling on, False turns it off.
            None leaves the autoscaling state unchanged.

        *axis*: ['x' | 'y' | 'both']
            which axis to operate on; default is 'both'

        *tight*: [True | False | None]
            If True, set view limits to data limits;
            if False, let the locator and margins expand the view limits;
            if None, use tight scaling if the only artist is an image,
            otherwise treat *tight* as False.
            The *tight* setting is retained for future autoscaling
            until it is explicitly changed.


        Returns None.
        """
        if enable is None:
            scalex = True
            scaley = True
        else:
            scalex = False
            scaley = False
            if axis in ['x', 'both']:
                self._autoscaleXon = bool(enable)
                scalex = self._autoscaleXon
            if axis in ['y', 'both']:
                self._autoscaleYon = bool(enable)
                scaley = self._autoscaleYon
        if tight and scalex:
            self._xmargin = 0
        if tight and scaley:
            self._ymargin = 0
        self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley)

    def autoscale_view(self, tight=None, scalex=True, scaley=True):
        """
        Autoscale the view limits using the data limits. You can
        selectively autoscale only a single axis, e.g., the xaxis by
        setting *scaley* to *False*.  The autoscaling preserves any
        axis direction reversal that has already been done.

        If *tight* is *False*, the axis major locator will be used
        to expand the view limits if rcParams['axes.autolimit_mode']
        is 'round_numbers'.  Note that any margins that are in effect
        will be applied first, regardless of whether *tight* is
        *True* or *False*.  Specifying *tight* as *True* or *False*
        saves the setting as a private attribute of the Axes; specifying
        it as *None* (the default) applies the previously saved value.

        The data limits are not updated automatically when artist data are
        changed after the artist has been added to an Axes instance.  In that
        case, use :meth:`matplotlib.axes.Axes.relim` prior to calling
        autoscale_view.
        """
        if tight is not None:
            self._tight = bool(tight)

        if self.use_sticky_edges and (self._xmargin or self._ymargin):
            stickies = [artist.sticky_edges for artist in self.get_children()]
            x_stickies = sum([sticky.x for sticky in stickies], [])
            y_stickies = sum([sticky.y for sticky in stickies], [])
            if self.get_xscale().lower() == 'log':
                x_stickies = [xs for xs in x_stickies if xs > 0]
            if self.get_yscale().lower() == 'log':
                y_stickies = [ys for ys in y_stickies if ys > 0]
        else:  # Small optimization.
            x_stickies, y_stickies = [], []

        def handle_single_axis(scale, autoscaleon, shared_axes, interval,
                               minpos, axis, margin, stickies, set_bound):

            if not (scale and autoscaleon):
                return  # nothing to do...

            shared = shared_axes.get_siblings(self)
            dl = [ax.dataLim for ax in shared]
            # ignore non-finite data limits if good limits exist
            finite_dl = [d for d in dl if np.isfinite(d).all()]
            if len(finite_dl):
                dl = finite_dl

            bb = mtransforms.BboxBase.union(dl)
            x0, x1 = getattr(bb, interval)
            locator = axis.get_major_locator()
            try:
                # e.g., DateLocator has its own nonsingular()
                x0, x1 = locator.nonsingular(x0, x1)
            except AttributeError:
                # Default nonsingular for, e.g., MaxNLocator
                x0, x1 = mtransforms.nonsingular(
                    x0, x1, increasing=False, expander=0.05)

            # Add the margin in figure space and then transform back, to handle
            # non-linear scales.
            minpos = getattr(bb, minpos)
            transform = axis.get_transform()
            inverse_trans = transform.inverted()
            # We cannot use exact equality due to floating point issues e.g.
            # with streamplot.
            do_lower_margin = not np.any(np.isclose(x0, stickies))
            do_upper_margin = not np.any(np.isclose(x1, stickies))
            x0, x1 = axis._scale.limit_range_for_scale(x0, x1, minpos)
            x0t, x1t = transform.transform([x0, x1])
            delta = (x1t - x0t) * margin
            if do_lower_margin:
                x0t -= delta
            if do_upper_margin:
                x1t += delta
            x0, x1 = inverse_trans.transform([x0t, x1t])

            if not self._tight:
                x0, x1 = locator.view_limits(x0, x1)
            set_bound(x0, x1)
            # End of definition of internal function 'handle_single_axis'.

        handle_single_axis(
            scalex, self._autoscaleXon, self._shared_x_axes, 'intervalx',
            'minposx', self.xaxis, self._xmargin, x_stickies, self.set_xbound)
        handle_single_axis(
            scaley, self._autoscaleYon, self._shared_y_axes, 'intervaly',
            'minposy', self.yaxis, self._ymargin, y_stickies, self.set_ybound)

    def _get_axis_list(self):
        return (self.xaxis, self.yaxis)

    # Drawing

    @allow_rasterization
    def draw(self, renderer=None, inframe=False):
        """Draw everything (plot lines, axes, labels)"""
        if renderer is None:
            renderer = self._cachedRenderer

        if renderer is None:
            raise RuntimeError('No renderer defined')
        if not self.get_visible():
            return
        renderer.open_group('axes')
        # prevent triggering call backs during the draw process
        self._stale = True
        locator = self.get_axes_locator()
        if locator:
            pos = locator(self, renderer)
            self.apply_aspect(pos)
        else:
            self.apply_aspect()

        artists = self.get_children()
        artists.remove(self.patch)

        # the frame draws the edges around the axes patch -- we
        # decouple these so the patch can be in the background and the
        # frame in the foreground. Do this before drawing the axis
        # objects so that the spine has the opportunity to update them.
        if not (self.axison and self._frameon):
            for spine in six.itervalues(self.spines):
                artists.remove(spine)

        if self.axison and not inframe:
            if self._axisbelow is True:
                self.xaxis.set_zorder(0.5)
                self.yaxis.set_zorder(0.5)
            elif self._axisbelow is False:
                self.xaxis.set_zorder(2.5)
                self.yaxis.set_zorder(2.5)
            else:
                # 'line': above patches, below lines
                self.xaxis.set_zorder(1.5)
                self.yaxis.set_zorder(1.5)
        else:
            for _axis in self._get_axis_list():
                artists.remove(_axis)

        if inframe:
            artists.remove(self.title)
            artists.remove(self._left_title)
            artists.remove(self._right_title)

        if self.figure.canvas.is_saving():
            dsu = [(a.zorder, a) for a in artists]
        else:
            dsu = [(a.zorder, a) for a in artists
                   if (not a.get_animated() or a in self.images)]

        dsu.sort(key=itemgetter(0))

        # rasterize artists with negative zorder
        # if the minimum zorder is negative, start rasterization
        rasterization_zorder = self._rasterization_zorder
        if (rasterization_zorder is not None and
                len(dsu) > 0 and dsu[0][0] < rasterization_zorder):
            renderer.start_rasterizing()
            dsu_rasterized = [l for l in dsu if l[0] < rasterization_zorder]
            dsu = [l for l in dsu if l[0] >= rasterization_zorder]
        else:
            dsu_rasterized = []

        # the patch draws the background rectangle -- the frame below
        # will draw the edges
        if self.axison and self._frameon:
            self.patch.draw(renderer)

        if dsu_rasterized:
            for zorder, a in dsu_rasterized:
                a.draw(renderer)
            renderer.stop_rasterizing()

        mimage._draw_list_compositing_images(renderer, self, dsu)

        renderer.close_group('axes')
        self._cachedRenderer = renderer
        self.stale = False

    def draw_artist(self, a):
        """
        This method can only be used after an initial draw which
        caches the renderer.  It is used to efficiently update Axes
        data (axis ticks, labels, etc are not updated)
        """
        if self._cachedRenderer is None:
            msg = ('draw_artist can only be used after an initial draw which'
                   ' caches the render')
            raise AttributeError(msg)
        a.draw(self._cachedRenderer)

    def redraw_in_frame(self):
        """
        This method can only be used after an initial draw which
        caches the renderer.  It is used to efficiently update Axes
        data (axis ticks, labels, etc are not updated)
        """
        if self._cachedRenderer is None:
            msg = ('redraw_in_frame can only be used after an initial draw'
                   ' which caches the render')
            raise AttributeError(msg)
        self.draw(self._cachedRenderer, inframe=True)

    def get_renderer_cache(self):
        return self._cachedRenderer

    # Axes rectangle characteristics

    def get_frame_on(self):
        """
        Get whether the axes rectangle patch is drawn
        """
        return self._frameon

    def set_frame_on(self, b):
        """
        Set whether the axes rectangle patch is drawn

        ACCEPTS: [ *True* | *False* ]
        """
        self._frameon = b
        self.stale = True

    def get_axisbelow(self):
        """
        Get whether axis below is true or not
        """
        return self._axisbelow

    def set_axisbelow(self, b):
        """
        Set whether the axis ticks and gridlines are above or below most
        artists

        ACCEPTS: [ *True* | *False* | 'line' ]
        """
        self._axisbelow = validate_axisbelow(b)
        self.stale = True

    @docstring.dedent_interpd
    def grid(self, b=None, which='major', axis='both', **kwargs):
        """
        Turn the axes grids on or off.

        Set the axes grids on or off; *b* is a boolean.  (For MATLAB
        compatibility, *b* may also be a string, 'on' or 'off'.)

        If *b* is *None* and ``len(kwargs)==0``, toggle the grid state.  If
        *kwargs* are supplied, it is assumed that you want a grid and *b*
        is thus set to *True*.

        *which* can be 'major' (default), 'minor', or 'both' to control
        whether major tick grids, minor tick grids, or both are affected.

        *axis* can be 'both' (default), 'x', or 'y' to control which
        set of gridlines are drawn.

        *kwargs* are used to set the grid line properties, e.g.,::

           ax.grid(color='r', linestyle='-', linewidth=2)

        Valid :class:`~matplotlib.lines.Line2D` kwargs are

        %(Line2D)s

        """
        if len(kwargs):
            b = True
        b = _string_to_bool(b)

        if axis == 'x' or axis == 'both':
            self.xaxis.grid(b, which=which, **kwargs)
        if axis == 'y' or axis == 'both':
            self.yaxis.grid(b, which=which, **kwargs)

    def ticklabel_format(self, **kwargs):
        """
        Change the `~matplotlib.ticker.ScalarFormatter` used by
        default for linear axes.

        Optional keyword arguments:

          ============   =========================================
          Keyword        Description
          ============   =========================================
          *style*        [ 'sci' (or 'scientific') | 'plain' ]
                         plain turns off scientific notation
          *scilimits*    (m, n), pair of integers; if *style*
                         is 'sci', scientific notation will
                         be used for numbers outside the range
                         10`m`:sup: to 10`n`:sup:.
                         Use (0,0) to include all numbers.
          *useOffset*    [True | False | offset]; if True,
                         the offset will be calculated as needed;
                         if False, no offset will be used; if a
                         numeric offset is specified, it will be
                         used.
          *axis*         [ 'x' | 'y' | 'both' ]
          *useLocale*    If True, format the number according to
                         the current locale.  This affects things
                         such as the character used for the
                         decimal separator.  If False, use
                         C-style (English) formatting.  The
                         default setting is controlled by the
                         axes.formatter.use_locale rcparam.
          ============   =========================================

        Only the major ticks are affected.
        If the method is called when the
        :class:`~matplotlib.ticker.ScalarFormatter` is not the
        :class:`~matplotlib.ticker.Formatter` being used, an
        :exc:`AttributeError` will be raised.

        """
        style = kwargs.pop('style', '').lower()
        scilimits = kwargs.pop('scilimits', None)
        useOffset = kwargs.pop('useOffset', None)
        useLocale = kwargs.pop('useLocale', None)
        axis = kwargs.pop('axis', 'both').lower()
        if scilimits is not None:
            try:
                m, n = scilimits
                m + n + 1  # check that both are numbers
            except (ValueError, TypeError):
                raise ValueError("scilimits must be a sequence of 2 integers")
        if style[:3] == 'sci':
            sb = True
        elif style in ['plain', 'comma']:
            sb = False
            if style == 'plain':
                cb = False
            else:
                cb = True
                raise NotImplementedError("comma style remains to be added")
        elif style == '':
            sb = None
        else:
            raise ValueError("%s is not a valid style value")
        try:
            if sb is not None:
                if axis == 'both' or axis == 'x':
                    self.xaxis.major.formatter.set_scientific(sb)
                if axis == 'both' or axis == 'y':
                    self.yaxis.major.formatter.set_scientific(sb)
            if scilimits is not None:
                if axis == 'both' or axis == 'x':
                    self.xaxis.major.formatter.set_powerlimits(scilimits)
                if axis == 'both' or axis == 'y':
                    self.yaxis.major.formatter.set_powerlimits(scilimits)
            if useOffset is not None:
                if axis == 'both' or axis == 'x':
                    self.xaxis.major.formatter.set_useOffset(useOffset)
                if axis == 'both' or axis == 'y':
                    self.yaxis.major.formatter.set_useOffset(useOffset)
            if useLocale is not None:
                if axis == 'both' or axis == 'x':
                    self.xaxis.major.formatter.set_useLocale(useLocale)
                if axis == 'both' or axis == 'y':
                    self.yaxis.major.formatter.set_useLocale(useLocale)
        except AttributeError:
            raise AttributeError(
                "This method only works with the ScalarFormatter.")

    def locator_params(self, axis='both', tight=None, **kwargs):
        """
        Control behavior of tick locators.

        Keyword arguments:

        *axis*
            ['x' | 'y' | 'both']  Axis on which to operate;
            default is 'both'.

        *tight*
            [True | False | None] Parameter passed to :meth:`autoscale_view`.
            Default is None, for no change.

        Remaining keyword arguments are passed to directly to the
        :meth:`~matplotlib.ticker.MaxNLocator.set_params` method.

        Typically one might want to reduce the maximum number
        of ticks and use tight bounds when plotting small
        subplots, for example::

            ax.locator_params(tight=True, nbins=4)

        Because the locator is involved in autoscaling,
        :meth:`autoscale_view` is called automatically after
        the parameters are changed.

        This presently works only for the
        :class:`~matplotlib.ticker.MaxNLocator` used
        by default on linear axes, but it may be generalized.
        """
        _x = axis in ['x', 'both']
        _y = axis in ['y', 'both']
        if _x:
            self.xaxis.get_major_locator().set_params(**kwargs)
        if _y:
            self.yaxis.get_major_locator().set_params(**kwargs)
        self.autoscale_view(tight=tight, scalex=_x, scaley=_y)

    def tick_params(self, axis='both', **kwargs):
        """Change the appearance of ticks and tick labels.

        Parameters
        ----------
        axis : {'x', 'y', 'both'}, optional
            Which axis to apply the parameters to.

        Other Parameters
        ----------------

        axis : {'x', 'y', 'both'}
            Axis on which to operate; default is 'both'.

        reset : bool
            If *True*, set all parameters to defaults
            before processing other keyword arguments.  Default is
            *False*.

        which : {'major', 'minor', 'both'}
            Default is 'major'; apply arguments to *which* ticks.

        direction : {'in', 'out', 'inout'}
            Puts ticks inside the axes, outside the axes, or both.

        length : float
            Tick length in points.

        width : float
            Tick width in points.

        color : color
            Tick color; accepts any mpl color spec.

        pad : float
            Distance in points between tick and label.

        labelsize : float or str
            Tick label font size in points or as a string (e.g., 'large').

        labelcolor : color
            Tick label color; mpl color spec.

        colors : color
            Changes the tick color and the label color to the same value:
            mpl color spec.

        zorder : float
            Tick and label zorder.

        bottom, top, left, right : bool or  {'on', 'off'}
            controls whether to draw the respective ticks.

        labelbottom, labeltop, labelleft, labelright : bool or  {'on', 'off'}
            controls whether to draw the
            respective tick labels.

        Examples
        --------

        Usage ::

            ax.tick_params(direction='out', length=6, width=2, colors='r')

        This will make all major ticks be red, pointing out of the box,
        and with dimensions 6 points by 2 points.  Tick labels will
        also be red.

        """
        if axis in ['x', 'both']:
            xkw = dict(kwargs)
            xkw.pop('left', None)
            xkw.pop('right', None)
            xkw.pop('labelleft', None)
            xkw.pop('labelright', None)
            self.xaxis.set_tick_params(**xkw)
        if axis in ['y', 'both']:
            ykw = dict(kwargs)
            ykw.pop('top', None)
            ykw.pop('bottom', None)
            ykw.pop('labeltop', None)
            ykw.pop('labelbottom', None)
            self.yaxis.set_tick_params(**ykw)

    def set_axis_off(self):
        """turn off the axis"""
        self.axison = False
        self.stale = True

    def set_axis_on(self):
        """turn on the axis"""
        self.axison = True
        self.stale = True

    @cbook.deprecated('2.0', alternative='get_facecolor')
    def get_axis_bgcolor(self):
        """Return the axis background color"""
        return self.get_facecolor()

    @cbook.deprecated('2.0', alternative='set_facecolor')
    def set_axis_bgcolor(self, color):
        """
        set the axes background color

        ACCEPTS: any matplotlib color - see
        :func:`~matplotlib.pyplot.colors`
        """
        return self.set_facecolor(color)
    # data limits, ticks, tick labels, and formatting

    def invert_xaxis(self):
        "Invert the x-axis."
        left, right = self.get_xlim()
        self.set_xlim(right, left, auto=None)

    def xaxis_inverted(self):
        """Returns *True* if the x-axis is inverted."""
        left, right = self.get_xlim()
        return right < left

    def get_xbound(self):
        """Returns the x-axis numerical bounds

        This always returns::

          lowerBound < upperBound

        Returns
        -------
        lowerBound, upperBound : float

        """
        left, right = self.get_xlim()
        if left < right:
            return left, right
        else:
            return right, left

    def set_xbound(self, lower=None, upper=None):
        """
        Set the lower and upper numerical bounds of the x-axis.
        This method will honor axes inversion regardless of parameter order.
        It will not change the _autoscaleXon attribute.
        """
        if upper is None and iterable(lower):
            lower, upper = lower

        old_lower, old_upper = self.get_xbound()

        if lower is None:
            lower = old_lower
        if upper is None:
            upper = old_upper

        if self.xaxis_inverted():
            if lower < upper:
                self.set_xlim(upper, lower, auto=None)
            else:
                self.set_xlim(lower, upper, auto=None)
        else:
            if lower < upper:
                self.set_xlim(lower, upper, auto=None)
            else:
                self.set_xlim(upper, lower, auto=None)

    def get_xlim(self):
        """
        Get the x-axis range

        Returns
        -------
        xlimits : tuple
            Returns the current x-axis limits as the tuple
            (`left`, `right`).

        Notes
        -----
        The x-axis may be inverted, in which case the `left` value will
        be greater than the `right` value.

        """
        return tuple(self.viewLim.intervalx)

    def set_xlim(self, left=None, right=None, emit=True, auto=False, **kw):
        """
        Set the data limits for the x-axis

        Parameters
        ----------
        left : scalar, optional
            The left xlim (default: None, which leaves the left limit
            unchanged).

        right : scalar, optional
            The right xlim (default: None, which leaves the right limit
            unchanged).

        emit : bool, optional
            Whether to notify observers of limit change (default: True).

        auto : bool or None, optional
            Whether to turn on autoscaling of the x-axis. True turns on,
            False turns off (default action), None leaves unchanged.

        xlimits : tuple, optional
            The left and right xlims may be passed as the tuple
            (`left`, `right`) as the first positional argument (or as
            the `left` keyword argument).

        Returns
        -------
        xlimits : tuple
            Returns the new x-axis limits as (`left`, `right`).

        Notes
        -----
        The `left` value may be greater than the `right` value, in which
        case the x-axis values will decrease from left to right.

        Examples
        --------
        >>> set_xlim(left, right)
        >>> set_xlim((left, right))
        >>> left, right = set_xlim(left, right)

        One limit may be left unchanged.

        >>> set_xlim(right=right_lim)

        Limits may be passed in reverse order to flip the direction of
        the x-axis. For example, suppose `x` represents the number of
        years before present. The x-axis limits might be set like the
        following so 5000 years ago is on the left of the plot and the
        present is on the right.

        >>> set_xlim(5000, 0)

        """
        if 'xmin' in kw:
            left = kw.pop('xmin')
        if 'xmax' in kw:
            right = kw.pop('xmax')
        if kw:
            raise ValueError("unrecognized kwargs: %s" %
                             list(six.iterkeys(kw)))

        if right is None and iterable(left):
            left, right = left

        self._process_unit_info(xdata=(left, right))
        if left is not None:
            left = self.convert_xunits(left)
        if right is not None:
            right = self.convert_xunits(right)

        old_left, old_right = self.get_xlim()
        if left is None:
            left = old_left
        if right is None:
            right = old_right

        if left == right:
            warnings.warn(
                ('Attempting to set identical left==right results\n'
                 'in singular transformations; automatically expanding.\n'
                 'left=%s, right=%s') % (left, right))
        left, right = mtransforms.nonsingular(left, right, increasing=False)
        left, right = self.xaxis.limit_range_for_scale(left, right)

        self.viewLim.intervalx = (left, right)
        if auto is not None:
            self._autoscaleXon = bool(auto)

        if emit:
            self.callbacks.process('xlim_changed', self)
            # Call all of the other x-axes that are shared with this one
            for other in self._shared_x_axes.get_siblings(self):
                if other is not self:
                    other.set_xlim(self.viewLim.intervalx,
                                   emit=False, auto=auto)
                    if (other.figure != self.figure and
                            other.figure.canvas is not None):
                        other.figure.canvas.draw_idle()
        self.stale = True
        return left, right

    def get_xscale(self):
        return self.xaxis.get_scale()
    get_xscale.__doc__ = "Return the xaxis scale string: %s""" % (
        ", ".join(mscale.get_scale_names()))

    @docstring.dedent_interpd
    def set_xscale(self, value, **kwargs):
        """
        Set the x-axis scale

        Set the scaling of the x-axis: %(scale)s

        ACCEPTS: [%(scale)s]

        Different kwargs are accepted, depending on the scale:
        %(scale_docs)s
        """
        # If the scale is being set to log, clip nonposx to prevent headaches
        # around zero
        if value.lower() == 'log' and 'nonposx' not in kwargs.keys():
            kwargs['nonposx'] = 'clip'

        g = self.get_shared_x_axes()
        for ax in g.get_siblings(self):
            ax.xaxis._set_scale(value, **kwargs)
            ax._update_transScale()
            ax.stale = True

        self.autoscale_view(scaley=False)

    def get_xticks(self, minor=False):
        """Return the x ticks as a list of locations"""
        return self.xaxis.get_ticklocs(minor=minor)

    def set_xticks(self, ticks, minor=False):
        """
        Set the x ticks with list of *ticks*

        ACCEPTS: sequence of floats
        """
        ret = self.xaxis.set_ticks(ticks, minor=minor)
        self.stale = True
        return ret

    def get_xmajorticklabels(self):
        """
        Get the xtick labels as a list of :class:`~matplotlib.text.Text`
        instances.
        """
        return cbook.silent_list('Text xticklabel',
                                 self.xaxis.get_majorticklabels())

    def get_xminorticklabels(self):
        """
        Get the x minor tick labels as a list of
        :class:`matplotlib.text.Text` instances.
        """
        return cbook.silent_list('Text xticklabel',
                                 self.xaxis.get_minorticklabels())

    def get_xticklabels(self, minor=False, which=None):
        """
        Get the x tick labels as a list of :class:`~matplotlib.text.Text`
        instances.

        Parameters
        ----------
        minor : bool
           If True return the minor ticklabels,
           else return the major ticklabels

        which : None, ('minor', 'major', 'both')
           Overrides `minor`.

           Selects which ticklabels to return

        Returns
        -------
        ret : list
           List of :class:`~matplotlib.text.Text` instances.
        """
        return cbook.silent_list('Text xticklabel',
                                 self.xaxis.get_ticklabels(minor=minor,
                                                           which=which))

    @docstring.dedent_interpd
    def set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs):
        """
        Set the xtick labels with list of strings *labels*

        Return a list of axis text instances.

        *kwargs* set the :class:`~matplotlib.text.Text` properties.
        Valid properties are
        %(Text)s

        ACCEPTS: sequence of strings
        """
        if fontdict is not None:
            kwargs.update(fontdict)
        ret = self.xaxis.set_ticklabels(labels,
                                        minor=minor, **kwargs)
        self.stale = True
        return ret

    def invert_yaxis(self):
        """
        Invert the y-axis.
        """
        bottom, top = self.get_ylim()
        self.set_ylim(top, bottom, auto=None)

    def yaxis_inverted(self):
        """Returns *True* if the y-axis is inverted."""
        bottom, top = self.get_ylim()
        return top < bottom

    def get_ybound(self):
        """
        Return y-axis numerical bounds in the form of
        ``lowerBound < upperBound``
        """
        bottom, top = self.get_ylim()
        if bottom < top:
            return bottom, top
        else:
            return top, bottom

    def set_ybound(self, lower=None, upper=None):
        """
        Set the lower and upper numerical bounds of the y-axis.
        This method will honor axes inversion regardless of parameter order.
        It will not change the _autoscaleYon attribute.
        """
        if upper is None and iterable(lower):
            lower, upper = lower

        old_lower, old_upper = self.get_ybound()

        if lower is None:
            lower = old_lower
        if upper is None:
            upper = old_upper

        if self.yaxis_inverted():
            if lower < upper:
                self.set_ylim(upper, lower, auto=None)
            else:
                self.set_ylim(lower, upper, auto=None)
        else:
            if lower < upper:
                self.set_ylim(lower, upper, auto=None)
            else:
                self.set_ylim(upper, lower, auto=None)

    def get_ylim(self):
        """
        Get the y-axis range

        Returns
        -------
        ylimits : tuple
            Returns the current y-axis limits as the tuple
            (`bottom`, `top`).

        Notes
        -----
        The y-axis may be inverted, in which case the `bottom` value
        will be greater than the `top` value.

        """
        return tuple(self.viewLim.intervaly)

    def set_ylim(self, bottom=None, top=None, emit=True, auto=False, **kw):
        """
        Set the data limits for the y-axis

        Parameters
        ----------
        bottom : scalar, optional
            The bottom ylim (default: None, which leaves the bottom
            limit unchanged).

        top : scalar, optional
            The top ylim (default: None, which leaves the top limit
            unchanged).

        emit : bool, optional
            Whether to notify observers of limit change (default: True).

        auto : bool or None, optional
            Whether to turn on autoscaling of the y-axis. True turns on,
            False turns off (default action), None leaves unchanged.

        ylimits : tuple, optional
            The bottom and top yxlims may be passed as the tuple
            (`bottom`, `top`) as the first positional argument (or as
            the `bottom` keyword argument).

        Returns
        -------
        ylimits : tuple
            Returns the new y-axis limits as (`bottom`, `top`).

        Notes
        -----
        The `bottom` value may be greater than the `top` value, in which
        case the y-axis values will decrease from bottom to top.

        Examples
        --------
        >>> set_ylim(bottom, top)
        >>> set_ylim((bottom, top))
        >>> bottom, top = set_ylim(bottom, top)

        One limit may be left unchanged.

        >>> set_ylim(top=top_lim)

        Limits may be passed in reverse order to flip the direction of
        the y-axis. For example, suppose `y` represents depth of the
        ocean in m. The y-axis limits might be set like the following
        so 5000 m depth is at the bottom of the plot and the surface,
        0 m, is at the top.

        >>> set_ylim(5000, 0)

        """
        if 'ymin' in kw:
            bottom = kw.pop('ymin')
        if 'ymax' in kw:
            top = kw.pop('ymax')
        if kw:
            raise ValueError("unrecognized kwargs: %s" %
                             list(six.iterkeys(kw)))

        if top is None and iterable(bottom):
            bottom, top = bottom

        if bottom is not None:
            bottom = self.convert_yunits(bottom)
        if top is not None:
            top = self.convert_yunits(top)

        old_bottom, old_top = self.get_ylim()

        if bottom is None:
            bottom = old_bottom
        if top is None:
            top = old_top

        if bottom == top:
            warnings.warn(
                ('Attempting to set identical bottom==top results\n'
                 'in singular transformations; automatically expanding.\n'
                 'bottom=%s, top=%s') % (bottom, top))

        bottom, top = mtransforms.nonsingular(bottom, top, increasing=False)
        bottom, top = self.yaxis.limit_range_for_scale(bottom, top)

        self.viewLim.intervaly = (bottom, top)
        if auto is not None:
            self._autoscaleYon = bool(auto)

        if emit:
            self.callbacks.process('ylim_changed', self)
            # Call all of the other y-axes that are shared with this one
            for other in self._shared_y_axes.get_siblings(self):
                if other is not self:
                    other.set_ylim(self.viewLim.intervaly,
                                   emit=False, auto=auto)
                    if (other.figure != self.figure and
                            other.figure.canvas is not None):
                        other.figure.canvas.draw_idle()
        self.stale = True
        return bottom, top

    def get_yscale(self):
        return self.yaxis.get_scale()
    get_yscale.__doc__ = "Return the yaxis scale string: %s""" % (
        ", ".join(mscale.get_scale_names()))

    @docstring.dedent_interpd
    def set_yscale(self, value, **kwargs):
        """Set the y-axis scale

        Set the scaling of the y-axis: %(scale)s

        ACCEPTS: [%(scale)s]

        Different kwargs are accepted, depending on the scale:
        %(scale_docs)s
        """
        # If the scale is being set to log, clip nonposy to prevent headaches
        # around zero
        if value.lower() == 'log' and 'nonposy' not in kwargs.keys():
            kwargs['nonposy'] = 'clip'

        g = self.get_shared_y_axes()
        for ax in g.get_siblings(self):
            ax.yaxis._set_scale(value, **kwargs)
            ax._update_transScale()
            ax.stale = True
        self.autoscale_view(scalex=False)

    def get_yticks(self, minor=False):
        """Return the y ticks as a list of locations"""
        return self.yaxis.get_ticklocs(minor=minor)

    def set_yticks(self, ticks, minor=False):
        """
        Set the y ticks with list of *ticks*

        ACCEPTS: sequence of floats

        Keyword arguments:

          *minor*: [ *False* | *True* ]
            Sets the minor ticks if *True*
        """
        ret = self.yaxis.set_ticks(ticks, minor=minor)
        return ret

    def get_ymajorticklabels(self):
        """
        Get the major y tick labels as a list of
        :class:`~matplotlib.text.Text` instances.
        """
        return cbook.silent_list('Text yticklabel',
                                 self.yaxis.get_majorticklabels())

    def get_yminorticklabels(self):
        """
        Get the minor y tick labels as a list of
        :class:`~matplotlib.text.Text` instances.
        """
        return cbook.silent_list('Text yticklabel',
                                 self.yaxis.get_minorticklabels())

    def get_yticklabels(self, minor=False, which=None):
        """
        Get the x tick labels as a list of :class:`~matplotlib.text.Text`
        instances.

        Parameters
        ----------
        minor : bool
           If True return the minor ticklabels,
           else return the major ticklabels

        which : None, ('minor', 'major', 'both')
           Overrides `minor`.

           Selects which ticklabels to return

        Returns
        -------
        ret : list
           List of :class:`~matplotlib.text.Text` instances.
        """
        return cbook.silent_list('Text yticklabel',
                                 self.yaxis.get_ticklabels(minor=minor,
                                                           which=which))

    @docstring.dedent_interpd
    def set_yticklabels(self, labels, fontdict=None, minor=False, **kwargs):
        """
        Set the y tick labels with list of strings *labels*

        Return a list of :class:`~matplotlib.text.Text` instances.

        *kwargs* set :class:`~matplotlib.text.Text` properties for the labels.
        Valid properties are
        %(Text)s

        ACCEPTS: sequence of strings
        """
        if fontdict is not None:
            kwargs.update(fontdict)
        return self.yaxis.set_ticklabels(labels,
                                         minor=minor, **kwargs)

    def xaxis_date(self, tz=None):
        """
        Sets up x-axis ticks and labels that treat the x data as dates.

        *tz* is a timezone string or :class:`tzinfo` instance.
        Defaults to rc value.
        """
        # should be enough to inform the unit conversion interface
        # dates are coming in
        self.xaxis.axis_date(tz)

    def yaxis_date(self, tz=None):
        """
        Sets up y-axis ticks and labels that treat the y data as dates.

        *tz* is a timezone string or :class:`tzinfo` instance.
        Defaults to rc value.
        """
        self.yaxis.axis_date(tz)

    def format_xdata(self, x):
        """
        Return *x* string formatted.  This function will use the attribute
        self.fmt_xdata if it is callable, else will fall back on the xaxis
        major formatter
        """
        try:
            return self.fmt_xdata(x)
        except TypeError:
            func = self.xaxis.get_major_formatter().format_data_short
            val = func(x)
            return val

    def format_ydata(self, y):
        """
        Return y string formatted.  This function will use the
        :attr:`fmt_ydata` attribute if it is callable, else will fall
        back on the yaxis major formatter
        """
        try:
            return self.fmt_ydata(y)
        except TypeError:
            func = self.yaxis.get_major_formatter().format_data_short
            val = func(y)
            return val

    def format_coord(self, x, y):
        """Return a format string formatting the *x*, *y* coord"""
        if x is None:
            xs = '???'
        else:
            xs = self.format_xdata(x)
        if y is None:
            ys = '???'
        else:
            ys = self.format_ydata(y)
        return 'x=%s y=%s' % (xs, ys)

    def minorticks_on(self):
        'Add autoscaling minor ticks to the axes.'
        for ax in (self.xaxis, self.yaxis):
            scale = ax.get_scale()
            if scale == 'log':
                s = ax._scale
                ax.set_minor_locator(mticker.LogLocator(s.base, s.subs))
            elif scale == 'symlog':
                s = ax._scale
                ax.set_minor_locator(
                    mticker.SymmetricalLogLocator(s.base, s.subs))
            else:
                ax.set_minor_locator(mticker.AutoMinorLocator())

    def minorticks_off(self):
        """Remove minor ticks from the axes."""
        self.xaxis.set_minor_locator(mticker.NullLocator())
        self.yaxis.set_minor_locator(mticker.NullLocator())

    # Interactive manipulation

    def can_zoom(self):
        """
        Return *True* if this axes supports the zoom box button functionality.
        """
        return True

    def can_pan(self):
        """
        Return *True* if this axes supports any pan/zoom button functionality.
        """
        return True

    def get_navigate(self):
        """
        Get whether the axes responds to navigation commands
        """
        return self._navigate

    def set_navigate(self, b):
        """
        Set whether the axes responds to navigation toolbar commands

        ACCEPTS: [ *True* | *False* ]
        """
        self._navigate = b

    def get_navigate_mode(self):
        """
        Get the navigation toolbar button status: 'PAN', 'ZOOM', or None
        """
        return self._navigate_mode

    def set_navigate_mode(self, b):
        """
        Set the navigation toolbar button status;

        .. warning::
            this is not a user-API function.

        """
        self._navigate_mode = b

    def _get_view(self):
        """
        Save information required to reproduce the current view.

        Called before a view is changed, such as during a pan or zoom
        initiated by the user. You may return any information you deem
        necessary to describe the view.

        .. note::

            Intended to be overridden by new projection types, but if not, the
            default implementation saves the view limits. You *must* implement
            :meth:`_set_view` if you implement this method.
        """
        xmin, xmax = self.get_xlim()
        ymin, ymax = self.get_ylim()
        return (xmin, xmax, ymin, ymax)

    def _set_view(self, view):
        """
        Apply a previously saved view.

        Called when restoring a view, such as with the navigation buttons.

        .. note::

            Intended to be overridden by new projection types, but if not, the
            default implementation restores the view limits. You *must*
            implement :meth:`_get_view` if you implement this method.
        """
        xmin, xmax, ymin, ymax = view
        self.set_xlim((xmin, xmax))
        self.set_ylim((ymin, ymax))

    def _set_view_from_bbox(self, bbox, direction='in',
                            mode=None, twinx=False, twiny=False):
        """
        Update view from a selection bbox.

        .. note::

            Intended to be overridden by new projection types, but if not, the
            default implementation sets the view limits to the bbox directly.

        Parameters
        ----------

        bbox : tuple
            The selected bounding box limits, in *display* coordinates.

        direction : str
            The direction to apply the bounding box.
                * `'in'` - The bounding box describes the view directly, i.e.,
                           it zooms in.
                * `'out'` - The bounding box describes the size to make the
                            existing view, i.e., it zooms out.

        mode : str or None
            The selection mode, whether to apply the bounding box in only the
            `'x'` direction, `'y'` direction or both (`None`).

        twinx : bool
            Whether this axis is twinned in the *x*-direction.

        twiny : bool
            Whether this axis is twinned in the *y*-direction.
        """

        lastx, lasty, x, y = bbox

        # zoom to rect
        inverse = self.transData.inverted()
        lastx, lasty = inverse.transform_point((lastx, lasty))
        x, y = inverse.transform_point((x, y))
        Xmin, Xmax = self.get_xlim()
        Ymin, Ymax = self.get_ylim()

        if twinx:
            x0, x1 = Xmin, Xmax
        else:
            if Xmin < Xmax:
                if x < lastx:
                    x0, x1 = x, lastx
                else:
                    x0, x1 = lastx, x
                if x0 < Xmin:
                    x0 = Xmin
                if x1 > Xmax:
                    x1 = Xmax
            else:
                if x > lastx:
                    x0, x1 = x, lastx
                else:
                    x0, x1 = lastx, x
                if x0 > Xmin:
                    x0 = Xmin
                if x1 < Xmax:
                    x1 = Xmax

        if twiny:
            y0, y1 = Ymin, Ymax
        else:
            if Ymin < Ymax:
                if y < lasty:
                    y0, y1 = y, lasty
                else:
                    y0, y1 = lasty, y
                if y0 < Ymin:
                    y0 = Ymin
                if y1 > Ymax:
                    y1 = Ymax
            else:
                if y > lasty:
                    y0, y1 = y, lasty
                else:
                    y0, y1 = lasty, y
                if y0 > Ymin:
                    y0 = Ymin
                if y1 < Ymax:
                    y1 = Ymax

        if direction == 'in':
            if mode == 'x':
                self.set_xlim((x0, x1))
            elif mode == 'y':
                self.set_ylim((y0, y1))
            else:
                self.set_xlim((x0, x1))
                self.set_ylim((y0, y1))
        elif direction == 'out':
            if self.get_xscale() == 'log':
                alpha = np.log(Xmax / Xmin) / np.log(x1 / x0)
                rx1 = pow(Xmin / x0, alpha) * Xmin
                rx2 = pow(Xmax / x0, alpha) * Xmin
            else:
                alpha = (Xmax - Xmin) / (x1 - x0)
                rx1 = alpha * (Xmin - x0) + Xmin
                rx2 = alpha * (Xmax - x0) + Xmin
            if self.get_yscale() == 'log':
                alpha = np.log(Ymax / Ymin) / np.log(y1 / y0)
                ry1 = pow(Ymin / y0, alpha) * Ymin
                ry2 = pow(Ymax / y0, alpha) * Ymin
            else:
                alpha = (Ymax - Ymin) / (y1 - y0)
                ry1 = alpha * (Ymin - y0) + Ymin
                ry2 = alpha * (Ymax - y0) + Ymin

            if mode == 'x':
                self.set_xlim((rx1, rx2))
            elif mode == 'y':
                self.set_ylim((ry1, ry2))
            else:
                self.set_xlim((rx1, rx2))
                self.set_ylim((ry1, ry2))

    def start_pan(self, x, y, button):
        """
        Called when a pan operation has started.

        *x*, *y* are the mouse coordinates in display coords.
        button is the mouse button number:

        * 1: LEFT
        * 2: MIDDLE
        * 3: RIGHT

        .. note::

            Intended to be overridden by new projection types.

        """
        self._pan_start = cbook.Bunch(
            lim=self.viewLim.frozen(),
            trans=self.transData.frozen(),
            trans_inverse=self.transData.inverted().frozen(),
            bbox=self.bbox.frozen(),
            x=x,
            y=y)

    def end_pan(self):
        """
        Called when a pan operation completes (when the mouse button
        is up.)

        .. note::

            Intended to be overridden by new projection types.

        """
        del self._pan_start

    def drag_pan(self, button, key, x, y):
        """
        Called when the mouse moves during a pan operation.

        *button* is the mouse button number:

        * 1: LEFT
        * 2: MIDDLE
        * 3: RIGHT

        *key* is a "shift" key

        *x*, *y* are the mouse coordinates in display coords.

        .. note::

            Intended to be overridden by new projection types.

        """
        def format_deltas(key, dx, dy):
            if key == 'control':
                if abs(dx) > abs(dy):
                    dy = dx
                else:
                    dx = dy
            elif key == 'x':
                dy = 0
            elif key == 'y':
                dx = 0
            elif key == 'shift':
                if 2 * abs(dx) < abs(dy):
                    dx = 0
                elif 2 * abs(dy) < abs(dx):
                    dy = 0
                elif abs(dx) > abs(dy):
                    dy = dy / abs(dy) * abs(dx)
                else:
                    dx = dx / abs(dx) * abs(dy)
            return (dx, dy)

        p = self._pan_start
        dx = x - p.x
        dy = y - p.y
        if dx == 0 and dy == 0:
            return
        if button == 1:
            dx, dy = format_deltas(key, dx, dy)
            result = p.bbox.translated(-dx, -dy) \
                .transformed(p.trans_inverse)
        elif button == 3:
            try:
                dx = -dx / float(self.bbox.width)
                dy = -dy / float(self.bbox.height)
                dx, dy = format_deltas(key, dx, dy)
                if self.get_aspect() != 'auto':
                    dx = 0.5 * (dx + dy)
                    dy = dx

                alpha = np.power(10.0, (dx, dy))
                start = np.array([p.x, p.y])
                oldpoints = p.lim.transformed(p.trans)
                newpoints = start + alpha * (oldpoints - start)
                result = mtransforms.Bbox(newpoints) \
                    .transformed(p.trans_inverse)
            except OverflowError:
                warnings.warn('Overflow while panning')
                return

        self.set_xlim(*result.intervalx)
        self.set_ylim(*result.intervaly)

    def get_cursor_props(self):
        """
        Return the cursor propertiess as a (*linewidth*, *color*)
        tuple, where *linewidth* is a float and *color* is an RGBA
        tuple
        """
        return self._cursorProps

    def set_cursor_props(self, *args):
        """Set the cursor property as

        Call signature ::

          ax.set_cursor_props(linewidth, color)

        or::

          ax.set_cursor_props((linewidth, color))

        ACCEPTS: a (*float*, *color*) tuple
        """
        if len(args) == 1:
            lw, c = args[0]
        elif len(args) == 2:
            lw, c = args
        else:
            raise ValueError('args must be a (linewidth, color) tuple')
        c = mcolors.to_rgba(c)
        self._cursorProps = lw, c

    def get_children(self):
        """return a list of child artists"""
        children = []
        children.extend(self.collections)
        children.extend(self.patches)
        children.extend(self.lines)
        children.extend(self.texts)
        children.extend(self.artists)
        children.extend(six.itervalues(self.spines))
        children.append(self.xaxis)
        children.append(self.yaxis)
        children.append(self.title)
        children.append(self._left_title)
        children.append(self._right_title)
        children.extend(self.tables)
        children.extend(self.images)
        if self.legend_ is not None:
            children.append(self.legend_)
        children.append(self.patch)
        return children

    def contains(self, mouseevent):
        """
        Test whether the mouse event occured in the axes.

        Returns *True* / *False*, {}
        """
        if six.callable(self._contains):
            return self._contains(self, mouseevent)

        return self.patch.contains(mouseevent)

    def contains_point(self, point):
        """
        Returns *True* if the point (tuple of x,y) is inside the axes
        (the area defined by the its patch). A pixel coordinate is
        required.

        """
        return self.patch.contains_point(point, radius=1.0)

    def pick(self, *args):
        """Trigger pick event

        Call signature::

            pick(mouseevent)

        each child artist will fire a pick event if mouseevent is over
        the artist and the artist has picker set
        """
        martist.Artist.pick(self, args[0])

    def get_default_bbox_extra_artists(self):
        return [artist for artist in self.get_children()
                if artist.get_visible()]

    def get_tightbbox(self, renderer, call_axes_locator=True):
        """
        Return the tight bounding box of the axes.
        The dimension of the Bbox in canvas coordinate.

        If *call_axes_locator* is *False*, it does not call the
        _axes_locator attribute, which is necessary to get the correct
        bounding box. ``call_axes_locator==False`` can be used if the
        caller is only intereted in the relative size of the tightbbox
        compared to the axes bbox.
        """

        bb = []

        if not self.get_visible():
            return None

        locator = self.get_axes_locator()
        if locator and call_axes_locator:
            pos = locator(self, renderer)
            self.apply_aspect(pos)
        else:
            self.apply_aspect()

        bb.append(self.get_window_extent(renderer))

        if self.title.get_visible():
            bb.append(self.title.get_window_extent(renderer))
        if self._left_title.get_visible():
            bb.append(self._left_title.get_window_extent(renderer))
        if self._right_title.get_visible():
            bb.append(self._right_title.get_window_extent(renderer))

        bb_xaxis = self.xaxis.get_tightbbox(renderer)
        if bb_xaxis:
            bb.append(bb_xaxis)

        bb_yaxis = self.yaxis.get_tightbbox(renderer)
        if bb_yaxis:
            bb.append(bb_yaxis)

        for child in self.get_children():
            if isinstance(child, OffsetBox) and child.get_visible():
                bb.append(child.get_window_extent(renderer))

        _bbox = mtransforms.Bbox.union(
            [b for b in bb if b.width != 0 or b.height != 0])

        return _bbox

    def _make_twin_axes(self, *kl, **kwargs):
        """
        make a twinx axes of self. This is used for twinx and twiny.
        """
        ax2 = self.figure.add_axes(self.get_position(True), *kl, **kwargs)
        return ax2

    def twinx(self):
        """
        Create a twin Axes sharing the xaxis

        create a twin of Axes for generating a plot with a sharex
        x-axis but independent y axis.  The y-axis of self will have
        ticks on left and the returned axes will have ticks on the
        right. To ensure tick marks of both axis align, see
        :class:`~matplotlib.ticker.LinearLocator`

        .. note::
            For those who are 'picking' artists while using twinx, pick
            events are only called for the artists in the top-most axes.
        """
        ax2 = self._make_twin_axes(sharex=self)
        ax2.yaxis.tick_right()
        ax2.yaxis.set_label_position('right')
        ax2.yaxis.set_offset_position('right')
        self.yaxis.tick_left()
        ax2.xaxis.set_visible(False)
        ax2.patch.set_visible(False)
        return ax2

    def twiny(self):
        """
        Create a twin Axes sharing the yaxis

        create a twin of Axes for generating a plot with a shared
        y-axis but independent x axis.  The x-axis of self will have
        ticks on bottom and the returned axes will have ticks on the
        top.

        .. note::
            For those who are 'picking' artists while using twiny, pick
            events are only called for the artists in the top-most axes.
        """

        ax2 = self._make_twin_axes(sharey=self)
        ax2.xaxis.tick_top()
        ax2.xaxis.set_label_position('top')
        self.xaxis.tick_bottom()
        ax2.yaxis.set_visible(False)
        ax2.patch.set_visible(False)
        return ax2

    def get_shared_x_axes(self):
        'Return a copy of the shared axes Grouper object for x axes'
        return self._shared_x_axes

    def get_shared_y_axes(self):
        'Return a copy of the shared axes Grouper object for y axes'
        return self._shared_y_axes