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
|
#/*##########################################################################
#
# The PyMca X-Ray Fluorescence Toolkit
#
# Copyright (c) 2004-2022 European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#############################################################################*/
__author__ = "V.A. Sole - ESRF"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
__doc__ = """
Matplotlib Plot backend.
"""
from matplotlib import cbook
import matplotlib
# blitting enabled by default
# it provides faster response at the cost of missing minor updates
# during movement (only the bounding box of the moving object is updated)
# For instance, when moving a marker, the label is not updated during the
# movement.
BLITTING = True
import numpy
from numpy import vstack as numpyvstack
# Problem on debian6 numpy version 1.4.1 unsigned longs give infinity
#from numpy import nanmax, nanmin
def nanmax(x):
x = numpy.array(x, copy=False)
x = x[numpy.isfinite(x)]
if len(x):
return x.max()
else:
return 0
def nanmin(x):
x = numpy.array(x, copy=False)
x = x[numpy.isfinite(x)]
if len(x):
return x.min()
else:
return 0
import sys
import types
# This should be independent of Qt
TK = False
if ("tk" in sys.argv) or ("Tkinter" in sys.modules) or ("tkinter" in sys.modules):
TK = True
if TK and ("PyQt4.QtCore" not in sys.modules) and ("PyQt5.QtCore" not in sys.modules) and\
("PySide.QtCore" not in sys.modules):
if sys.version < '3.0':
import Tkinter as Tk
else:
import tkinter as Tk
elif ('PySide.QtCore' in sys.modules) or ('PySide' in sys.argv):
matplotlib.rcParams['backend'] = 'Qt4Agg'
if 'backend.qt4' in matplotlib.rcParams:
matplotlib.rcParams['backend.qt4'] = 'PySide'
from PySide import QtCore, QtGui
elif ("PyQt4.QtCore" in sys.modules) or ('PyQt4' in sys.argv):
from PyQt4 import QtCore, QtGui
matplotlib.rcParams['backend'] = 'Qt4Agg'
elif 'PySide2.QtCore' in sys.modules:
matplotlib.rcParams['backend'] = 'Qt5Agg'
from PySide2 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
elif 'PyQt5.QtCore' in sys.modules:
matplotlib.rcParams['backend'] = 'Qt5Agg'
from PyQt5 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
elif 'PySide6.QtCore' in sys.modules:
matplotlib.rcParams['backend'] = 'Qt5Agg'
from PySide6 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
else:
try:
from PyQt4 import QtCore, QtGui
matplotlib.rcParams['backend'] = 'Qt4Agg'
except ImportError:
try:
from PyQt5 import QtCore, QtGui, QtWidgets
QtGui.QApplication = QtWidgets.QApplication
matplotlib.rcParams['backend'] = 'Qt5Agg'
except ImportError:
from PySide import QtCore, QtGui
if ("PyQt4.QtCore" in sys.modules) or ("PySide.QtCore" in sys.modules):
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
TK = False
QT = True
elif ("PyQt5.QtCore" in sys.modules) or ("PySide2.QtCore" in sys.modules):
from ._patch_matplotlib import patch_backend_qt
patch_backend_qt()
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
TK = False
QT = True
elif ("PyQt6.QtCore" in sys.modules) or ("PySide6.QtCore" in sys.modules):
from ._patch_matplotlib import patch_backend_qt
patch_backend_qt()
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
TK = False
QT = True
elif ("Tkinter" in sys.modules) or ("tkinter" in sys.modules):
TK = True
QT = False
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas
try:
from .. import PlotBackend
except ImportError:
from PyMca5.PyMca import PlotBackend
from matplotlib import cm
from matplotlib.font_manager import FontProperties
try:
from matplotlib.widgets import Cursor
except:
print("matplotlib.widgets Cursor not available")
from matplotlib.figure import Figure
import matplotlib.patches as patches
Rectangle = patches.Rectangle
Polygon = patches.Polygon
from matplotlib.lines import Line2D
from matplotlib.collections import PathCollection
from matplotlib.text import Text
from matplotlib.image import AxesImage, NonUniformImage
from matplotlib.colors import LinearSegmentedColormap, LogNorm, Normalize
import time
try:
from . import _utils
except ImportError:
from PyMca5.PyMcaGraph.backends import _utils
DEBUG = 0
class ModestImage(AxesImage):
pass
class MatplotlibGraph(FigureCanvas):
def __init__(self, parent=None, **kw):
#self.figure = Figure(figsize=size, dpi=dpi) #in inches
self.fig = Figure()
if TK:
self._canvas = FigureCanvas.__init__(self, self.fig, master=parent)
else:
self._originalCursorShape = QtCore.Qt.ArrowCursor
self._canvas = FigureCanvas.__init__(self, self.fig)
# get the default widget color
color = self.palette().color(self.backgroundRole())
color = "#%x" % color.rgb()
if len(color) == 9:
color = "#" + color[3:]
#self.fig.set_facecolor(color)
self.fig.set_facecolor("w")
# that's it
if 1:
#this almost works
"""
def twinx(self):
call signature::
ax = twinx()
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
ax2 = self.fig.add_axes(self.get_position(True), sharex=self,
frameon=False)
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.yaxis.set_offset_position('right')
self.ax.yaxis.tick_left()
ax2.xaxis.set_visible(False)
return ax2
"""
self.ax = self.fig.add_axes([.15, .15, .75, .75], label="left")
self.ax2 = self.ax.twinx()
self.ax2.set_label("right")
# critical for picking!!!!
self.ax2.set_zorder(0)
self.ax2.set_autoscaley_on(True)
self.ax.set_zorder(1)
#this works but the figure color is left
if hasattr(self.ax, "set_facecolor"):
self.ax.set_facecolor('none')
else:
# this was deprecated in 2.0
self.ax.set_axis_bgcolor('none')
self.fig.sca(self.ax)
try:
# prevent use of offsets
self.ax.get_yaxis().get_major_formatter().set_useOffset(False)
self.ax.get_xaxis().get_major_formatter().set_useOffset(False)
except:
print("Error disabling matplotlib offsets")
else:
#this almost works
self.ax2 = self.fig.add_axes([.15, .15, .75, .75],
axisbg="w",
label="right",
frameon=False)
self.ax = self.fig.add_axes(self.ax2.get_position(),
sharex=self.ax2,
label="left",
frameon=True)
self.ax2.yaxis.tick_right()
self.ax2.xaxis.set_visible(False)
self.ax2.yaxis.set_label_position('right')
self.ax2.yaxis.set_offset_position('right')
if hasattr(self.ax, "set_facecolor"):
self.ax.set_facecolor('none')
else:
# this was deprecated in 2.0
self.ax.set_axis_bgcolor('none')
# this respects aspect size
# self.ax = self.fig.add_subplot(111, aspect='equal')
# This should be independent of Qt
if matplotlib.rcParams['backend'] == "Qt4Agg":
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
elif matplotlib.rcParams['backend'] == "Qt5Agg":
FigureCanvas.setSizePolicy(self,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
self.__lastMouseClick = ["middle", time.time()]
self._zoomEnabled = False
self._zoomColor = "black"
self.__zooming = False
self.__picking = False
self._background = None
self.__markerMoving = False
self._zoomStack = []
self.xAutoScale = True
self.yAutoScale = True
#info text
self._infoText = None
#drawingmode handling
self.setDrawModeEnabled(False)
self.__drawModeList = ['line', 'hline', 'vline', 'rectangle', 'polygon']
self.__drawing = False
self._drawingPatch = None
self._drawModePatch = 'line'
#event handling
self._callback = self._dummyCallback
self._x0 = None
self._y0 = None
self._zoomRectangle = None
self.fig.canvas.mpl_connect('button_press_event',
self.onMousePressed)
self.fig.canvas.mpl_connect('button_release_event',
self.onMouseReleased)
self.fig.canvas.mpl_connect('motion_notify_event',
self.onMouseMoved)
self.fig.canvas.mpl_connect('scroll_event',
self.onMouseWheel)
self.fig.canvas.mpl_connect('pick_event',
self.onPick)
def _dummyCallback(self, ddict):
if DEBUG:
print(ddict)
def setCallback(self, callbackFuntion):
self._callback = callbackFuntion
def onPick(self, event):
# Unfortunately only the artists on the top axes
# can be picked -> A legend handling widget is
# needed
middleButton = 2
rightButton = 3
button = event.mouseevent.button
if button == middleButton:
# do nothing with the midle button
return
elif button == rightButton:
button = "right"
else:
button = "left"
if self._drawModeEnabled:
# forget about picking or zooming
# should one disconnect when setting the mode?
return
self.__picking = False
self._pickingInfo = {}
if isinstance(event.artist, Line2D) or \
isinstance(event.artist, PathCollection):
# we only handle curves and markers for the time being
self.__picking = True
artist = event.artist
label = artist.get_label()
ind = event.ind
#xdata = thisline.get_xdata()
#ydata = thisline.get_ydata()
#print('onPick line:', zip(numpy.take(xdata, ind),
# numpy.take(ydata, ind)))
self._pickingInfo['artist'] = artist
self._pickingInfo['event_ind'] = ind
if label.startswith("__MARKER__"):
label = label[10:]
self._pickingInfo['type'] = 'marker'
self._pickingInfo['label'] = label
if 'draggable' in artist._plot_options:
self._pickingInfo['draggable'] = True
else:
self._pickingInfo['draggable'] = False
if 'selectable' in artist._plot_options:
self._pickingInfo['selectable'] = True
else:
self._pickingInfo['selectable'] = False
if hasattr(artist, "_infoText"):
self._pickingInfo['infoText'] = artist._infoText
else:
self._pickingInfo['infoText'] = None
elif isinstance(event.artist, PathCollection):
# almost identical to line 2D
self._pickingInfo['type'] = 'curve'
self._pickingInfo['label'] = label
self._pickingInfo['artist'] = artist
data = artist.get_offsets()
xdata = data[:, 0]
ydata = data[:, 1]
self._pickingInfo['xdata'] = xdata[ind]
self._pickingInfo['ydata'] = ydata[ind]
self._pickingInfo['infoText'] = None
else:
# line2D
self._pickingInfo['type'] = 'curve'
self._pickingInfo['label'] = label
self._pickingInfo['artist'] = artist
xdata = artist.get_xdata()
ydata = artist.get_ydata()
self._pickingInfo['xdata'] = xdata[ind]
self._pickingInfo['ydata'] = ydata[ind]
self._pickingInfo['infoText'] = None
if self._pickingInfo['infoText'] is None:
if self._infoText is None:
self._infoText = self.ax.text(event.mouseevent.xdata,
event.mouseevent.ydata,
label)
else:
self._infoText.set_position((event.mouseevent.xdata,
event.mouseevent.ydata))
self._infoText.set_text(label)
self._pickingInfo['infoText'] = self._infoText
self._pickingInfo['infoText'].set_visible(True)
if DEBUG:
print("%s %s selected" % (self._pickingInfo['type'].upper(),
self._pickingInfo['label']))
elif isinstance(event.artist, Rectangle):
patch = event.artist
print('onPick patch:', patch.get_path())
elif isinstance(event.artist, Text):
text = event.artist
print('onPick text:', text.get_text())
elif isinstance(event.artist, AxesImage):
self.__picking = True
artist = event.artist
#print dir(artist)
self._pickingInfo['artist'] = artist
#self._pickingInfo['event_ind'] = ind
label = artist.get_label()
self._pickingInfo['type'] = 'image'
self._pickingInfo['label'] = label
self._pickingInfo['draggable'] = False
self._pickingInfo['selectable'] = False
if hasattr(artist, "_plot_options"):
if 'draggable' in artist._plot_options:
self._pickingInfo['draggable'] = True
else:
self._pickingInfo['draggable'] = False
if 'selectable' in artist._plot_options:
self._pickingInfo['selectable'] = True
else:
self._pickingInfo['selectable'] = False
else:
print("unhandled event", event.artist)
def setDrawModeEnabled(self, flag=True, shape="polygon", label=None,
color=None, **kw):
if flag:
shape = shape.lower()
if shape not in self.__drawModeList:
self._drawModeEnabled = False
raise ValueError("Unsupported shape %s" % shape)
else:
self._drawModeEnabled = True
self.setZoomModeEnabled(False)
self._drawModePatch = shape
self._drawingParameters = kw
if color is not None:
self._drawingParameters['color'] = color
self._drawingParameters['shape'] = shape
self._drawingParameters['label'] = label
else:
self._drawModeEnabled = False
def setZoomModeEnabled(self, flag=True, color=None):
if color is None:
color = self._zoomColor
if len(color) == 4:
if type(color[3]) in [type(1), numpy.uint8, numpy.int8]:
color = numpy.array(color, dtype=numpy.float64)/255.
self._zoomColor = color
if flag:
self._zoomEnabled = True
self.setDrawModeEnabled(False)
else:
self._zoomEnabled = False
def isZoomModeEnabled(self):
return self._zoomEnabled
def isDrawModeEnabled(self):
return self._drawModeEnabled
def getDrawMode(self):
if self.isDrawModeEnabled():
return self._drawingParameters
else:
return None
def onMousePressed(self, event):
if DEBUG:
print("onMousePressed, event = ",event.xdata, event.ydata)
print("Mouse button = ", event.button)
self.__time0 = -1.0
if event.inaxes != self.ax:
if DEBUG:
print("RETURNING")
return
button = event.button
leftButton = 1
middleButton = 2
rightButton = 3
self._x0 = event.xdata
self._y0 = event.ydata
if button == middleButton:
# by default, do nothing with the middle button
return
self._x0Pixel = event.x
self._y0Pixel = event.y
self._x1 = event.xdata
self._y1 = event.ydata
self._x1Pixel = event.x
self._y1Pixel = event.y
self.__movingMarker = 0
# picking handling
if self.__picking:
if DEBUG:
print("PICKING, Ignoring zoom")
self.__zooming = False
self.__drawing = False
self.__markerMoving = False
if self._pickingInfo['type'] == "marker":
if button == rightButton:
# only selection or movement
self._pickingInfo = {}
return
artist = self._pickingInfo['artist']
if button == leftButton:
if self._pickingInfo['draggable']:
self.__markerMoving = True
if self._pickingInfo['selectable']:
self.__markerMoving = False
if self.__markerMoving:
if 'xmarker' in artist._plot_options:
artist.set_xdata(event.xdata)
elif 'ymarker' in artist._plot_options:
artist.set_ydata(event.ydata)
else:
xData, yData = event.xdata, event.ydata
if artist._constraint is not None:
# Apply marker constraint
xData, yData = artist._constraint(xData, yData)
artist.set_xdata(xData)
artist.set_ydata(yData)
if BLITTING and hasattr(artist.figure, "canvas"):
canvas = artist.figure.canvas
axes = artist.axes
artist.set_animated(True)
canvas.draw()
self._background = canvas.copy_from_bbox(self.fig.bbox)
axes.draw_artist(artist)
canvas.blit(self.fig.bbox)
else:
self.fig.canvas.draw()
ddict = {}
ddict['label'] = self._pickingInfo['label']
ddict['type'] = self._pickingInfo['type']
ddict['draggable'] = self._pickingInfo['draggable']
ddict['selectable'] = self._pickingInfo['selectable']
ddict['xpixel'] = self._x0Pixel
ddict['ypixel'] = self._y0Pixel
ddict['xdata'] = artist.get_xdata()
ddict['ydata'] = artist.get_ydata()
if self.__markerMoving:
ddict['event'] = "markerMoving"
ddict['x'] = self._x0
ddict['y'] = self._y0
else:
ddict['event'] = "markerClicked"
if hasattr(ddict['xdata'], "__len__"):
ddict['x'] = ddict['xdata'][-1]
else:
ddict['x'] = ddict['xdata']
if hasattr(ddict['ydata'], "__len__"):
ddict['y'] = ddict['ydata'][-1]
else:
ddict['y'] = ddict['ydata']
if button == leftButton:
ddict['button'] = "left"
else:
ddict['button'] = "right"
self._callback(ddict)
if ddict['event'] == "markerClicked":
self.__picking = False
return
elif self._pickingInfo['type'] == "curve":
ddict = {}
ddict['event'] = "curveClicked"
#ddict['event'] = "legendClicked"
ddict['label'] = self._pickingInfo['label']
ddict['type'] = self._pickingInfo['type']
ddict['x'] = self._x0
ddict['y'] = self._y0
ddict['xpixel'] = self._x0Pixel
ddict['ypixel'] = self._y0Pixel
ddict['xdata'] = self._pickingInfo['xdata']
ddict['ydata'] = self._pickingInfo['ydata']
if button == leftButton:
ddict['button'] = "left"
else:
ddict['button'] = "right"
self._callback(ddict)
return
elif self._pickingInfo['type'] == "image":
artist = self._pickingInfo['artist']
ddict = {}
ddict['event'] = "imageClicked"
#ddict['event'] = "legendClicked"
ddict['label'] = self._pickingInfo['label']
ddict['type'] = self._pickingInfo['type']
ddict['x'] = self._x0
ddict['y'] = self._y0
ddict['xpixel'] = self._x0Pixel
ddict['ypixel'] = self._y0Pixel
xScale = artist._plot_info['xScale']
yScale = artist._plot_info['yScale']
col = (ddict['x'] - xScale[0])/float(xScale[1])
row = (ddict['y'] - yScale[0])/float(yScale[1])
ddict['row'] = int(row)
ddict['col'] = int(col)
if button == leftButton:
ddict['button'] = "left"
else:
ddict['button'] = "right"
self.__picking = False
self._callback(ddict)
if event.button == rightButton:
#right click
self.__zooming = False
if self._drawingPatch is not None:
self._emitDrawingSignal("drawingFinished")
return
self.__time0 = time.time()
self.__zooming = self._zoomEnabled
self._zoomRect = None
self._xmin, self._xmax = self.ax.get_xlim()
self._ymin, self._ymax = self.ax.get_ylim()
# deal with inverted axis
if self._xmin > self._xmax:
tmpValue = self._xmin
self._xmin = self._xmax
self._xmax = tmpValue
if self._ymin > self._ymax:
tmpValue = self._ymin
self._ymin = self._ymax
self._ymax = tmpValue
if self.ax.get_aspect() != 'auto':
self._ratio = (self._ymax - self._ymin) / (self._xmax - self._xmin)
self.__drawing = self._drawModeEnabled
if self.__drawing:
if self._drawModePatch in ['hline', 'vline']:
if self._drawingPatch is None:
self._mouseData = numpy.zeros((2,2), numpy.float32)
if self._drawModePatch == "hline":
self._mouseData[0,0] = self._xmin
self._mouseData[0,1] = self._y0
self._mouseData[1,0] = self._xmax
self._mouseData[1,1] = self._y0
else:
self._mouseData[0,0] = self._x0
self._mouseData[0,1] = self._ymin
self._mouseData[1,0] = self._x0
self._mouseData[1,1] = self._ymax
color = self._getDrawingColor()
self._drawingPatch = Polygon(self._mouseData,
closed=True,
fill=False,
color=color)
self.ax.add_patch(self._drawingPatch)
def _getDrawingColor(self):
color = "black"
if "color" in self._drawingParameters:
color = self._drawingParameters["color"]
if len(color) == 4:
if type(color[3]) in [type(1), numpy.uint8, numpy.int8]:
color = numpy.array(color, dtype=numpy.float64)/255.
return color
def onMouseMoved(self, event):
if DEBUG:
print("onMouseMoved, event = ",event.xdata, event.ydata)
if event.inaxes != self.ax:
if DEBUG:
print("RETURNING")
return
button = event.button
if button == 1:
button = "left"
elif button == 2:
button = "middle"
elif button == 3:
button = "right"
else:
button = None
#as default, export the mouse in graph coordenates
self._x1 = event.xdata
self._y1 = event.ydata
self._x1Pixel = event.x
self._y1Pixel = event.y
ddict= {'event':'mouseMoved',
'x':self._x1,
'y':self._y1,
'xpixel':self._x1Pixel,
'ypixel':self._y1Pixel,
'button':button,
}
self._callback(ddict)
if button == "middle":
return
# should this be made by Plot1D with the previous call???
# The problem is Plot1D does not know if one is zooming or drawing
if not (self.__zooming or self.__drawing or self.__picking):
# this corresponds to moving without click
marker = None
for artist in self.ax.lines:
label = artist.get_label()
if label.startswith("__MARKER__"):
#data = artist.get_xydata()[0:1]
x, y = artist.get_xydata()[-1]
pixels = self.ax.transData.transform(numpyvstack([x,y]).T)
xPixel, yPixel = pixels.T
if 'xmarker' in artist._plot_options:
if abs(xPixel-event.x) < 5:
marker = artist
elif 'ymarker' in artist._plot_options:
if abs(yPixel-event.y) < 5:
marker = artist
elif (abs(xPixel-event.x) < 5) and \
(abs(yPixel-event.y) < 5):
marker = artist
if marker is not None:
break
if QT:
oldShape = self.cursor().shape()
if oldShape not in [QtCore.Qt.SizeHorCursor,
QtCore.Qt.SizeVerCursor,
QtCore.Qt.PointingHandCursor,
QtCore.Qt.OpenHandCursor,
QtCore.Qt.SizeAllCursor]:
self._originalCursorShape = oldShape
if marker is not None:
ddict = {}
ddict['event'] = 'hover'
ddict['type'] = 'marker'
ddict['label'] = marker.get_label()[10:]
if 'draggable' in marker._plot_options:
ddict['draggable'] = True
if QT:
if 'ymarker' in artist._plot_options:
self.setCursor(QtGui.QCursor(QtCore.Qt.SizeVerCursor))
elif 'xmarker' in artist._plot_options:
self.setCursor(QtGui.QCursor(QtCore.Qt.SizeHorCursor))
else:
self.setCursor(QtGui.QCursor(QtCore.Qt.SizeAllCursor))
else:
ddict['draggable'] = False
if 'selectable' in marker._plot_options:
ddict['selectable'] = True
if QT:
self.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
else:
ddict['selectable'] = False
ddict['x'] = self._x1
ddict['y'] = self._y1
ddict['xpixel'] = self._x1Pixel
ddict['ypixel'] = self._y1Pixel
self._callback(ddict)
elif QT:
if self._originalCursorShape in [QtCore.Qt.SizeHorCursor,
QtCore.Qt.SizeVerCursor,
QtCore.Qt.PointingHandCursor,
QtCore.Qt.OpenHandCursor,
QtCore.Qt.SizeAllCursor]:
self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
else:
self.setCursor(QtGui.QCursor(self._originalCursorShape))
return
if self.__picking:
if self.__markerMoving:
artist = self._pickingInfo['artist']
infoText = self._pickingInfo['infoText']
if 'xmarker' in artist._plot_options:
artist.set_xdata(event.xdata)
ymin, ymax = self.ax.get_ylim()
delta = abs(ymax - ymin)
ymax = max(ymax, ymin) - 0.005 * delta
if infoText is not None:
infoText.set_position((event.xdata, ymax))
elif 'ymarker' in artist._plot_options:
artist.set_ydata(event.ydata)
if infoText is not None:
infoText.set_position((event.xdata, event.ydata))
else:
xData, yData = event.xdata, event.ydata
if artist._constraint is not None:
# Apply marker constraint
xData, yData = artist._constraint(xData, yData)
artist.set_xdata(xData)
artist.set_ydata(yData)
if infoText is not None:
xtmp, ytmp = self.ax.transData.transform_point((xData,
yData))
inv = self.ax.transData.inverted()
xtmp, ytmp = inv.transform_point((xtmp, ytmp + 15))
infoText.set_position((xData, ytmp))
if BLITTING and (self._background is not None) and\
hasattr(artist.figure, "canvas"):
canvas = artist.figure.canvas
axes = artist.axes
artist.set_animated(True)
canvas.restore_region(self._background)
axes.draw_artist(artist)
canvas.blit(self.fig.bbox)
else:
self.fig.canvas.draw()
ddict = {}
ddict['event'] = "markerMoving"
ddict['button'] = "left"
ddict['label'] = self._pickingInfo['label']
ddict['type'] = self._pickingInfo['type']
ddict['draggable'] = self._pickingInfo['draggable']
ddict['selectable'] = self._pickingInfo['selectable']
ddict['x'] = self._x1
ddict['y'] = self._y1
ddict['xpixel'] = self._x1Pixel
ddict['ypixel'] = self._y1Pixel
ddict['xdata'] = artist.get_xdata()
ddict['ydata'] = artist.get_ydata()
self._callback(ddict)
return
if (not self.__zooming) and (not self.__drawing):
return
if self._x0 is None:
# this happened when using the middle button
return
if self.__zooming or \
(self.__drawing and (self._drawModePatch == 'rectangle')):
if self._x1 < self._xmin:
self._x1 = self._xmin
elif self._x1 > self._xmax:
self._x1 = self._xmax
if self._y1 < self._ymin:
self._y1 = self._ymin
elif self._y1 > self._ymax:
self._y1 = self._ymax
if self._x1 < self._x0:
x = self._x1
w = self._x0 - self._x1
else:
x = self._x0
w = self._x1 - self._x0
if self._y1 < self._y0:
y = self._y1
h = self._y0 - self._y1
else:
y = self._y0
h = self._y1 - self._y0
if w == 0:
return
if (not self.__drawing) and (self.ax.get_aspect() != 'auto'):
if (h / w) > self._ratio:
h = w * self._ratio
else:
w = h / self._ratio
if self._x1 > self._x0:
x = self._x0
else:
x = self._x0 - w
if self._y1 > self._y0:
y = self._y0
else:
y = self._y0 - h
if self.__zooming:
if self._zoomRectangle is None:
self._zoomRectangle = Rectangle(xy=(x,y),
width=w,
height=h,
color=self._zoomColor,
fill=False)
self.ax.add_patch(self._zoomRectangle)
else:
self._zoomRectangle.set_bounds(x, y, w, h)
#self._zoomRectangle._update_patch_transform()
if BLITTING:
artist = self._zoomRectangle
canvas = artist.figure.canvas
axes = artist.axes
artist.set_animated(True)
if self._background is None:
self._background = canvas.copy_from_bbox(self.fig.bbox)
canvas.restore_region(self._background)
axes.draw_artist(artist)
canvas.blit(self.fig.bbox)
else:
self.fig.canvas.draw()
return
else:
if self._drawingPatch is None:
color = self._getDrawingColor()
self._drawingPatch = Rectangle(xy=(x,y),
width=w,
height=h,
fill=False,
color=color)
self._drawingPatch.set_hatch('.')
self.ax.add_patch(self._drawingPatch)
else:
self._drawingPatch.set_bounds(x, y, w, h)
#self._zoomRectangle._update_patch_transform()
if self.__drawing:
if self._drawingPatch is None:
self._mouseData = numpy.zeros((2,2), numpy.float32)
self._mouseData[0,0] = self._x0
self._mouseData[0,1] = self._y0
self._mouseData[1,0] = self._x1
self._mouseData[1,1] = self._y1
color = self._getDrawingColor()
self._drawingPatch = Polygon(self._mouseData,
closed=True,
fill=False,
color=color)
self.ax.add_patch(self._drawingPatch)
elif self._drawModePatch == 'rectangle':
# already handled, just for compatibility
self._mouseData = numpy.zeros((2,2), numpy.float32)
self._mouseData[0,0] = self._x0
self._mouseData[0,1] = self._y0
self._mouseData[1,0] = self._x1
self._mouseData[1,1] = self._y1
elif self._drawModePatch == 'line':
self._mouseData[0,0] = self._x0
self._mouseData[0,1] = self._y0
self._mouseData[1,0] = self._x1
self._mouseData[1,1] = self._y1
self._drawingPatch.set_xy(self._mouseData)
elif self._drawModePatch == 'hline':
xmin, xmax = self.ax.get_xlim()
self._mouseData[0,0] = xmin
self._mouseData[0,1] = self._y1
self._mouseData[1,0] = xmax
self._mouseData[1,1] = self._y1
self._drawingPatch.set_xy(self._mouseData)
elif self._drawModePatch == 'vline':
ymin, ymax = self.ax.get_ylim()
self._mouseData[0,0] = self._x1
self._mouseData[0,1] = ymin
self._mouseData[1,0] = self._x1
self._mouseData[1,1] = ymax
self._drawingPatch.set_xy(self._mouseData)
elif self._drawModePatch == 'polygon':
self._mouseData[-1,0] = self._x1
self._mouseData[-1,1] = self._y1
self._drawingPatch.set_xy(self._mouseData)
if matplotlib.__version__.startswith('1.1.1'):
# Patch for Debian 7
# Workaround matplotlib issue with closed path
# Need to toggle closed path to rebuild points
self._drawingPatch.set_closed(False)
self._drawingPatch.set_closed(True)
self._drawingPatch.set_hatch('/')
if BLITTING:
if self._background is None:
artist = self._drawingPatch
canvas = artist.figure.canvas
axes = artist.axes
self._background = canvas.copy_from_bbox(self.fig.bbox)
artist = self._drawingPatch
canvas = artist.figure.canvas
axes = artist.axes
artist.set_animated(True)
canvas.restore_region(self._background)
axes.draw_artist(artist)
canvas.blit(self.fig.bbox)
else:
self.fig.canvas.draw()
self._emitDrawingSignal(event='drawingProgress')
def onMouseReleased(self, event):
if DEBUG:
print("onMouseReleased, event = ",event.xdata, event.ydata)
if self._infoText in self.ax.texts:
self._infoText.set_visible(False)
if self.__picking:
self.__picking = False
if self.__markerMoving:
self.__markerMoving = False
artist = self._pickingInfo['artist']
if BLITTING and hasattr(artist.figure, "canvas"):
artist.set_animated(False)
self._background = None
artist.figure.canvas.draw()
ddict = {}
ddict['event'] = "markerMoved"
ddict['label'] = self._pickingInfo['label']
ddict['type'] = self._pickingInfo['type']
ddict['draggable'] = self._pickingInfo['draggable']
ddict['selectable'] = self._pickingInfo['selectable']
# use this and not the current mouse position because
# it has to agree with the marker position
ddict['x'] = artist.get_xdata()
ddict['y'] = artist.get_ydata()
ddict['xdata'] = artist.get_xdata()
ddict['ydata'] = artist.get_ydata()
self._callback(ddict)
self._pickingInfo = {}
return
if not hasattr(self, "__zoomstack"):
self.__zoomstack = []
if event.button == 3:
#right click
if self.__drawing:
self.__drawing = False
#self._drawingPatch = None
ddict = {}
ddict['event'] = 'drawingFinished'
ddict['type'] = '%s' % self._drawModePatch
ddict['data'] = self._mouseData * 1
self._emitDrawingSignal(event='drawingFinished')
return
self.__zooming = False
if len(self._zoomStack):
xmin, xmax, ymin, ymax, y2min, y2max = self._zoomStack.pop()
self.setLimits(xmin, xmax, ymin, ymax, y2min, y2max)
self.draw()
if self.__drawing and (self._drawingPatch is not None):
nrows, ncols = self._mouseData.shape
if self._drawModePatch in ['polygon']:
self._mouseData = numpy.resize(self._mouseData, (nrows+1,2))
self._mouseData[-1,0] = self._x1
self._mouseData[-1,1] = self._y1
self._drawingPatch.set_xy(self._mouseData)
if self._drawModePatch not in ['polygon']:
self._emitDrawingSignal("drawingFinished")
if self._x0 is None:
if event.inaxes != self.ax:
if DEBUG:
print("on MouseReleased RETURNING")
else:
print("How can it be here???")
return
if self._zoomRectangle is None:
currentTime = time.time()
deltaT = currentTime - self.__time0
if (deltaT < 0.150) or (self.__time0 < 0) or (not self.__zooming) or\
((self._x1 == self._x0) and (self._y1 == self._y0)):
# single or double click, no zooming
self.__zooming = False
ddict = {'x':event.xdata,
'y':event.ydata,
'xpixel':event.x,
'ypixel':event.y}
leftButton = 1
middleButton = 2
rightButton = 3
button = event.button
if button == rightButton:
ddict['button'] = "right"
elif button == middleButton:
ddict['button'] = "middle"
else:
ddict['button'] = "left"
if (button == self.__lastMouseClick[0]) and\
((currentTime - self.__lastMouseClick[1]) < 0.6):
ddict['event'] = "mouseDoubleClicked"
else:
ddict['event'] = "mouseClicked"
self.__lastMouseClick = [button, time.time()]
self._callback(ddict)
return
if self._zoomRectangle is not None:
x, y = self._zoomRectangle.get_xy()
w = self._zoomRectangle.get_width()
h = self._zoomRectangle.get_height()
self._zoomRectangle.remove()
self._x0 = None
self._y0 = None
if BLITTING:
artist = self._zoomRectangle
axes = artist.axes
artist.set_animated(False)
self._background = None
self._zoomRectangle = None
if (w != 0) and (h != 0):
# don't do anything
xmin, xmax = self.ax.get_xlim()
ymin, ymax = self.ax.get_ylim()
if ymax < ymin:
ymin, ymax = ymax, ymin
if not self.ax2.get_yaxis().get_visible():
y2min, y2max = None, None
newY2Min, newY2Max = None, None
else:
bottom, top = self.ax2.get_ylim()
y2min, y2max = min(bottom, top), max(bottom, top)
# Convert corners from ax data to window
pt0 = self.ax.transData.transform_point((x, y))
pt1 = self.ax.transData.transform_point((x + w, y + h))
# Convert corners from window to ax2 data
pt0 = self.ax2.transData.inverted().transform_point(pt0)
pt1 = self.ax2.transData.inverted().transform_point(pt1)
# Get min and max on right Y axis
newY2Min, newY2Max = pt0[1], pt1[1]
if newY2Max < newY2Min:
newY2Min, newY2Max = newY2Max, newY2Min
self._zoomStack.append((xmin, xmax, ymin, ymax, y2min, y2max))
self.setLimits(x, x+w, y, y+h, newY2Min, newY2Max)
self.draw()
@staticmethod
def _newZoomRange(min_, max_, center, scale, isLog):
if isLog:
if min_ > 0.:
oldMin = numpy.log10(min_)
else:
# Happens when autoscale is off and switch to log scale
# while displaying area < 0.
oldMin = numpy.log10(numpy.nextafter(0, 1))
if center > 0.:
center = numpy.log10(center)
else:
center = numpy.log10(numpy.nextafter(0, 1))
if max_ > 0.:
oldMax = numpy.log10(max_)
else:
# Should not happen
oldMax = 0.
else:
oldMin, oldMax = min_, max_
offset = (center - oldMin) / (oldMax - oldMin)
range_ = (oldMax - oldMin) / scale
newMin = center - offset * range_
newMax = center + (1. - offset) * range_
if isLog:
try:
newMin, newMax = 10. ** float(newMin), 10. ** float(newMax)
except OverflowError: # Limit case
newMin, newMax = min_, max_
if newMin <= 0. or newMax <= 0.: # Limit case
newMin, newMax = min_, max_
return newMin, newMax
def onMouseWheel(self, event):
if not self.isZoomModeEnabled():
return
if event.xdata is None or event.ydata is None:
return
scaleF = 1.1 if event.step > 0 else 1 / 1.1
xLim = self.ax.get_xlim()
xMin, xMax = min(xLim), max(xLim)
isXLog = (self.ax.get_xscale() == 'log')
yLim = self.ax.get_ylim()
yMin, yMax = min(yLim), max(yLim)
isYLog = (self.ax.get_yscale() == 'log')
# If negative limit and log scale,
# try to get a positive limit from the data limits
if (isXLog and xMin <= 0.) or (isYLog and yMin <= 0.):
bounds = self.getDataLimits()
if isXLog:
if xMin <= 0. and bounds[0] > 0.:
xMin = bounds[0]
if xMax <= 0. and bounds[1] > 0.:
xMax = bounds[1]
if isYLog:
if yMin <= 0. and bounds[2] > 0.:
yMin = bounds[2]
if yMax <= 0. and bounds[3] > 0.:
yMax = bounds[3]
xMin, xMax = self._newZoomRange(xMin, xMax,
event.xdata, scaleF, isXLog)
yMin, yMax = self._newZoomRange(yMin, yMax,
event.ydata, scaleF, isYLog)
if self.ax2.get_yaxis().get_visible():
# Get y position in right axis coords
x, y2Data = self.ax2.transData.inverted().transform_point(
(event.x, event.y))
y2Lim = self.ax2.get_ylim()
y2Min, y2Max = min(y2Lim), max(y2Lim)
isY2Log = (self.ax2.get_yscale() == 'log')
# If negative limit and log scale,
# try to get a positive limit from the data limits
if isY2Log and y2Min <= 0.:
bounds = self.getDataLimits('right')
if yMin <= 0. and bounds[2] > 0.:
y2Min = bounds[2]
if yMax <= 0. and bounds[3] > 0.:
y2Max = bounds[3]
y2Min, y2Max = self._newZoomRange(y2Min, y2Max,
y2Data, scaleF, isYLog)
self.setLimits(xMin, xMax, yMin, yMax, y2Min, y2Max)
else:
self.setLimits(xMin, xMax, yMin, yMax)
self.draw()
def _emitDrawingSignal(self, event="drawingFinished"):
ddict = {}
ddict['event'] = event
ddict['type'] = '%s' % self._drawModePatch
#ddict['xdata'] = numpy.array(self._drawingPatch.get_x())
#ddict['ydata'] = numpy.array(self._drawingPatch.get_y())
#print(dir(self._drawingPatch))
a = self._drawingPatch.get_xy()
ddict['points'] = numpy.array(a)
ddict['points'].shape = -1, 2
ddict['xdata'] = ddict['points'][:, 0]
ddict['ydata'] = ddict['points'][:, 1]
#print(numpyvstack(a))
#pixels = self.ax.transData.transform(numpyvstack(a).T)
#xPixel, yPixels = pixels.T
if self._drawModePatch in ["rectangle", "circle"]:
# we need the rectangle containing it
ddict['x'] = ddict['points'][:, 0].min()
ddict['y'] = ddict['points'][:, 1].min()
ddict['width'] = self._drawingPatch.get_width()
ddict['height'] = self._drawingPatch.get_height()
elif self._drawModePatch in ["ellipse"]:
#we need the rectangle but given the four corners
pass
ddict['parameters'] = {}
for key in self._drawingParameters.keys():
ddict['parameters'][key] = self._drawingParameters[key]
if event == "drawingFinished":
self.__drawingParameters = None
self.__drawing = False
if self._drawingPatch is not None:
if BLITTING:
artist = self._drawingPatch
artist.set_animated(False)
self._background = None
self._drawingPatch.remove()
self._drawingPatch = None
self.draw()
self._callback(ddict)
def emitLimitsChangedSignal(self):
# Send event about limits changed
left, right = self.ax.get_xlim()
xRange = (left, right) if left < right else (right, left)
bottom, top = self.ax.get_ylim()
yRange = (bottom, top) if bottom < top else (top, bottom)
if hasattr(self.ax2, "get_visible") and self.ax2.get_visible():
bottom2, top2 = self.ax2.get_ylim()
y2Range = (bottom2, top2) if bottom2 < top2 else (top2, bottom2)
else:
y2Range = None
if hasattr(self, "get_tk_widget"):
sourceObj = self.get_tk_widget()
else:
sourceObj = self
eventDict = {
'event': 'limitsChanged',
'source': id(sourceObj),
'xdata': xRange,
'ydata': yRange,
'y2data': y2Range,
}
self._callback(eventDict)
def setLimits(self, xmin, xmax, ymin, ymax, y2min=None, y2max=None):
delta = 0.044
if xmin == xmax:
xmax += delta
xmin -= delta
self.ax.set_xlim(xmin, xmax)
if ymin == ymax:
ymax += delta
ymin -= delta
if ymax < ymin:
ymin, ymax = ymax, ymin
current = self.ax.get_ylim()
if self.ax.yaxis_inverted():
self.ax.set_ylim(ymax, ymin)
#top, bottom = current
else:
self.ax.set_ylim(ymin, ymax)
#bottom, top = current
if y2min is not None and y2max is not None:
if y2max < y2min:
y2min, y2max = y2max, y2min
if self.ax2.yaxis_inverted():
bottom, top = y2max, y2min
else:
bottom, top = y2min, y2max
self.ax2.set_ylim(bottom, top)
# if second axis was not properly initialized, this does not work
#if 0 and hasattr(self.ax2, "get_visible") and self.ax2.get_visible():
# #print("BOTTOM, TOP = ", bottom, top)
# bottom2, top2 = self.ax2.get_ylim()
# #print("BOTTOM2, TO2 = ", bottom2, top2)
# i2Range = top2 - bottom2
# if i2Range > 0:
# ymin2 = bottom2 + i2Range * (ymin - bottom)/(top - bottom)
# ymax2 = bottom2 + i2Range * (ymax - bottom)/(top - bottom)
# #print("OBTAINED = ", ymin2, ymax2)
# if self.ax2.yaxis_inverted():
# self.ax2.set_ylim(ymax2, ymin2)
# else:
# self.ax2.set_ylim(ymin2, ymax2)
# Next line forces a square display region
#self.ax.set_aspect((xmax-xmin)/float(ymax-ymin))
#self.draw()
self.emitLimitsChangedSignal()
def resetZoom(self, dataMargins=None):
xmin, xmax, ymin, ymax = self.getDataLimits('left')
if hasattr(self.ax2, "get_visible"):
if self.ax2.get_visible():
xmin2, xmax2, ymin2, ymax2 = self.getDataLimits('right')
else:
xmin2 = None
xmax2 = None
else:
xmin2, xmax2, ymin2, ymax2 = self.getDataLimits('right')
#self.ax2.set_ylim(ymin2, ymax2)
if (xmin2 is not None) and ((xmin2 != 0) or (xmax2 != 1)):
xmin = min(xmin, xmin2)
xmax = max(xmax, xmax2)
# Add margins around data inside the plot area
if xmin2 is None:
newLimits = _utils.addMarginsToLimits(
dataMargins,
self.ax.get_xscale() == 'log', self.ax.get_yscale() == 'log',
xmin, xmax, ymin, ymax)
self.setLimits(*newLimits)
else:
newLimits = _utils.addMarginsToLimits(
dataMargins,
self.ax.get_xscale() == 'log', self.ax.get_yscale() == 'log',
xmin, xmax, ymin, ymax, ymin2, ymax2)
self.setLimits(*newLimits)
#self.ax2.set_autoscaley_on(True)
self._zoomStack = []
def getDataLimits(self, axesLabel='left'):
if axesLabel == 'right':
axes = self.ax2
else:
axes = self.ax
if DEBUG:
print("CALCULATING limits ", axes.get_label())
xmin = None
for line2d in axes.lines:
label = line2d.get_label()
if label.startswith("__MARKER__"):
#it is a marker
continue
lineXMin = None
if hasattr(line2d, "_plot_info"):
if line2d._plot_info.get("axes", "left") != axesLabel:
continue
if "xmin" in line2d._plot_info:
lineXMin = line2d._plot_info["xmin"]
lineXMax = line2d._plot_info["xmax"]
lineYMin = line2d._plot_info["ymin"]
lineYMax = line2d._plot_info["ymax"]
if lineXMin is None:
x = line2d.get_xdata()
y = line2d.get_ydata()
if not len(x) or not len(y):
continue
lineXMin = nanmin(x)
lineXMax = nanmax(x)
lineYMin = nanmin(y)
lineYMax = nanmax(y)
if xmin is None:
xmin = lineXMin
xmax = lineXMax
ymin = lineYMin
ymax = lineYMax
continue
xmin = min(xmin, lineXMin)
xmax = max(xmax, lineXMax)
ymin = min(ymin, lineYMin)
ymax = max(ymax, lineYMax)
for line2d in axes.collections:
label = line2d.get_label()
if label.startswith("__MARKER__"):
#it is a marker
continue
lineXMin = None
if hasattr(line2d, "_plot_info"):
if line2d._plot_info.get("axes", "left") != axesLabel:
continue
if "xmin" in line2d._plot_info:
lineXMin = line2d._plot_info["xmin"]
lineXMax = line2d._plot_info["xmax"]
lineYMin = line2d._plot_info["ymin"]
lineYMax = line2d._plot_info["ymax"]
if lineXMin is None:
print("CANNOT CALCULATE LIMITS")
continue
if xmin is None:
xmin = lineXMin
xmax = lineXMax
ymin = lineYMin
ymax = lineYMax
continue
xmin = min(xmin, lineXMin)
xmax = max(xmax, lineXMax)
ymin = min(ymin, lineYMin)
ymax = max(ymax, lineYMax)
for artist in axes.images:
x0, x1, y0, y1 = artist.get_extent()
if (xmin is None):
xmin = x0
xmax = x1
ymin = min(y0, y1)
ymax = max(y0, y1)
xmin = min(xmin, x0)
xmax = max(xmax, x1)
ymin = min(ymin, y0)
ymax = max(ymax, y1)
for artist in axes.artists:
label = artist.get_label()
if label.startswith("__IMAGE__"):
if hasattr(artist, 'get_image_extent'):
x0, x1, y0, y1 = artist.get_image_extent()
else:
x0, x1, y0, y1 = artist.get_extent()
if (xmin is None):
xmin = x0
xmax = x1
ymin = min(y0, y1)
ymax = max(y0, y1)
ymin = min(ymin, y0, y1)
ymax = max(ymax, y1, y0)
xmin = min(xmin, x0)
xmax = max(xmax, x1)
if xmin is None:
xmin = 0
xmax = 1
ymin = 0
ymax = 1
if axesLabel == 'right':
return None, None, None, None
xSize = float(xmax - xmin)
ySize = float(ymax - ymin)
A = self.ax.get_aspect()
if A != 'auto':
figW, figH = self.ax.get_figure().get_size_inches()
figAspect = figH / figW
#l, b, w, h = self.ax.get_position(original=True).bounds
#box_aspect = figAspect * (h / float(w))
#dataRatio = box_aspect / A
dataRatio = (ySize / xSize) * A
y_expander = dataRatio - figAspect
# If y_expander > 0, the dy/dx viewLim ratio needs to increase
if abs(y_expander) < 0.005:
#good enough
pass
else:
# this works for any data ratio
if y_expander < 0:
#print("adjust_y")
deltaY = xSize * (figAspect / A) - ySize
yc = 0.5 * (ymin + ymax)
ymin = yc - (ySize + deltaY) * 0.5
ymax = yc + (ySize + deltaY) * 0.5
else:
#print("ADJUST X")
deltaX = ySize * (A / figAspect) - xSize
xc = 0.5 * (xmin + xmax)
xmin = xc - (xSize + deltaX) * 0.5
xmax = xc + (xSize + deltaX) * 0.5
if DEBUG:
print("CALCULATED LIMITS = ", xmin, xmax, ymin, ymax)
return xmin, xmax, ymin, ymax
def resizeEvent(self, ev):
# we have to get rid of the copy of the underlying image
self._background = None
FigureCanvas.resizeEvent(self, ev)
if DEBUG:
def draw(self):
print("Draw called")
super(MatplotlibGraph, self).draw()
class MatplotlibBackend(PlotBackend.PlotBackend):
def __init__(self, parent=None, **kw):
#self.figure = Figure(figsize=size, dpi=dpi) #in inches
self.graph = MatplotlibGraph(parent, **kw)
self.ax2 = self.graph.ax2
self.ax = self.graph.ax
PlotBackend.PlotBackend.__init__(self, parent)
self._parent = parent
self._logX = False
self._logY = False
self.setZoomModeEnabled = self.graph.setZoomModeEnabled
self.setDrawModeEnabled = self.graph.setDrawModeEnabled
self.isZoomModeEnabled = self.graph.isZoomModeEnabled
self.isDrawModeEnabled = self.graph.isDrawModeEnabled
self.getDrawMode = self.graph.getDrawMode
self._oldActiveCurve = None
self._oldActiveCurveLegend = None
# should one have two methods, for enable and for show
self._rightAxisEnabled = False
self.enableAxis('right', False)
self._graphCursor = None
self.matplotlibVersion = matplotlib.__version__
def setGraphCursor(self, flag=True, color=None, linewidth=None, linestyle=None):
if color is None:
color = "black"
if linewidth is None:
linewidth = 1
if linestyle is None:
linestyle="-"
self._graphCursorConfiguration = (color, linewidth, linestyle)
if flag:
if self._graphCursor is None:
self._graphCursor = Cursor(self.ax,
useblit=True,
color=color,
linewidth=linewidth,
linestyle=linestyle)
self.ax.get_figure().canvas.draw()
self._graphCursor.visible = True
else:
if self._graphCursor is not None:
self._graphCursor.visible = False
def getGraphCursor(self):
if self._graphCursor is None:
return None
elif not self._graphCursor.visible:
return None
else:
return self._graphCursorConfiguration * 1
def addCurve(self, x, y, legend=None, info=None, replace=False, replot=True,
color=None, symbol=None, linewidth=None, linestyle=None,
xlabel=None, ylabel=None, yaxis=None,
xerror=None, yerror=None, z=1, selectable=True, **kw):
if legend is None:
legend = "Unnamed curve"
if replace:
self.clearCurves()
else:
self.removeCurve(legend, replot=False)
if color is None:
color = self._activeCurveColor
if len(color) == 4:
if type(color[3]) in [type(1), numpy.uint8, numpy.int8]:
color = numpy.array(color, dtype=numpy.float64)/255.
brush = color
style = linestyle
if linewidth is None:
linewidth = 1
if yaxis == "right":
axisId = yaxis
else:
axisId = "left"
fill = kw.get('plot_fill', False)
if axisId == "right":
axes = self.ax2
if self._rightAxisEnabled is None:
# never initialized
self.enableAxis(axisId, True)
else:
axes = self.ax
pickradius = 3
if selectable:
picker = True
else:
picker = False
scatterPlot = False
if hasattr(color, "dtype"):
if len(color) == len(x):
scatterPlot = True
if scatterPlot:
# scatter plot
if color.dtype not in [numpy.float32, numpy.float]:
actualColor = color / 255.
else:
actualColor = color
pathObject = axes.scatter(x, y,
label=legend,
color=actualColor,
marker=symbol,
picker=picker,
pickradius=pickradius)
if style not in [" ", None]:
# scatter plot with an actual line ...
# we need to assign a color ...
curveList = axes.plot(x, y, label=legend,
linestyle=style,
color=actualColor[0],
linewidth=linewidth,
picker=picker,
marker=None,
pickradius=pickradius,
**kw)
curveList[-1]._plot_info = {'color':actualColor,
'linewidth':linewidth,
'brush':brush,
'style':style,
'symbol':symbol,
'label':legend,
'axes':axisId,
'fill':fill,
'xlabel':xlabel,
'ylabel':ylabel}
if hasattr(x, "min") and hasattr(y, "min"):
curveList[-1]._plot_info['xmin'] = nanmin(x)
curveList[-1]._plot_info['xmax'] = nanmax(x)
curveList[-1]._plot_info['ymin'] = nanmin(y)
curveList[-1]._plot_info['ymax'] = nanmax(y)
# scatter plot is a collection
curveList = [pathObject]
if self._logY:
axes.set_yscale('log')
elif self._logY:
curveList = axes.semilogy( x, y, label=legend,
linestyle=style,
color=color,
linewidth=linewidth,
picker=picker,
pickradius=pickradius,
**kw)
else:
curveList = axes.plot( x, y, label=legend,
linestyle=style,
color=color,
linewidth=linewidth,
picker=picker,
pickradius=pickradius,
**kw)
# errorbar is a container?
#axes.errorbar(x,y, label=legend,yerr=numpy.sqrt(y), linestyle=" ",color='b')
# nice effects:
#curveList[-1].set_drawstyle('steps-mid')
if fill:
axes.fill_between(x, 1.0e-8, y)
#curveList[-1].set_fillstyle('bottom')
if hasattr(curveList[-1], "set_marker"):
curveList[-1].set_marker(symbol)
curveList[-1]._plot_info = {'color':color,
'linewidth':linewidth,
'brush':brush,
'style':style,
'symbol':symbol,
'label':legend,
'axes':axisId,
'fill':fill,
'xlabel':xlabel,
'ylabel':ylabel}
if hasattr(x, "min") and hasattr(y, "min"):
# this is needed for scatter plots because I do not know
# how to recover the data yet, it can speed up limits too
curveList[-1]._plot_info['xmin'] = nanmin(x)
curveList[-1]._plot_info['xmax'] = nanmax(x)
curveList[-1]._plot_info['ymin'] = nanmin(y)
curveList[-1]._plot_info['ymax'] = nanmax(y)
if self._activeCurveHandling:
if self._oldActiveCurve in self.ax.lines:
if self._oldActiveCurve.get_label() == legend:
curveList[-1].set_color(self._activeCurveColor)
elif self._oldActiveCurveLegend == legend:
curveList[-1].set_color(self._activeCurveColor)
curveList[-1].axes = axes # set_axes(axes) deprecated in version 1.5
curveList[-1].set_zorder(z)
if replot:
self.replot()
# If I return the instance, later on cannot make a copy.deepcopy
# of the info and asks me to use "frozen" instead
#return curveList[-1]
return legend
def addItem(self, x, y, legend, info=None, replace=False, replot=True, **kw):
if replace:
self.clearItems()
else:
# make sure we do not cummulate images with same name
self.removeItem(legend, replot=False)
item = None
shape = kw.get('shape', "polygon")
if shape not in ['line', 'hline', 'vline', 'rectangle', 'polygon']:
raise NotImplemented("Unsupported item shape %s" % shape)
label = kw.get('label', legend)
color = kw.get('color', 'black')
fill = kw.get('fill', True)
xView = numpy.array(x, copy=False)
yView = numpy.array(y, copy=False)
label = "__ITEM__" + label
if shape in ["line", "hline", "vline"]:
print("Not implemented")
return legend
elif shape in ["hline"]:
if hasattr(y, "__len__"):
y = y[-1]
line = self.ax.axhline(y, label=label, color=color)
return line
elif shape in ["vline"]:
if hasattr(x, "__len__"):
x = x[-1]
line = self.ax.axvline(x, label=label, color=color)
return line
elif shape in ['rectangle']:
xMin = nanmin(xView)
xMax = nanmax(xView)
yMin = nanmin(yView)
yMax = nanmax(yView)
w = xMax - xMin
h = yMax - yMin
item = Rectangle(xy=(xMin,yMin),
width=w,
height=h,
fill=False,
color=color)
if fill:
item.set_hatch('.')
elif shape in ['polygon']:
xView.shape = 1, -1
yView.shape = 1, -1
item = Polygon(numpyvstack((xView, yView)).T,
closed=True,
fill=False,
label=label,
color=color)
if fill:
#item.set_hatch('+')
item.set_hatch('/')
if item is None:
print("Undefined item")
print("shape = ", shape)
print("legend = ", legend)
return
self.ax.add_patch(item)
if replot:
self.ax.figure.canvas.draw()
return item
def clear(self):
"""
Clear all curvers and other items from the plot
"""
n = list(range(len(self.ax.lines)))
n.reverse()
for i in n:
line2d = self.ax.lines[i]
line2d.remove()
del line2d
self.ax.clear()
def clearImages(self):
n = list(range(len(self.ax.images)))
n.reverse()
for i in n:
image = self.ax.images[i]
image.remove()
del image
# in versions of matplotlib prior to 3.5.0
# the content of the if block was needed
if i < len(self.ax.images):
del self.ax.images[i]
n = list(range(len(self.ax.artists)))
n.reverse()
for i in n:
artist = self.ax.artists[i]
label = artist.get_label()
if label.startswith("__IMAGE__"):
artist.remove()
del artist
def clearCurves(self):
"""
Clear all curves from the plot. Not the markers!!
"""
for axes in [self.ax, self.ax2]:
n = list(range(len(axes.lines)))
n.reverse()
for i in n:
line2d = axes.lines[i]
label = line2d.get_label()
if label.startswith("__MARKER__"):
#it is a marker
continue
line2d.remove()
del line2d
def clearMarkers(self):
"""
Clear all markers from the plot. Not the curves!!
"""
for axes in [self.ax, self.ax2]:
n = list(range(len(axes.lines)))
n.reverse()
for i in n:
line2d = axes.lines[i]
label = line2d.get_label()
if label.startswith("__MARKER__"):
#it is a marker
if hasattr(line2d, "_infoText"):
line2d._infoText.remove()
line2d.remove()
del line2d
def clearItems(self):
"""
Clear items, not markers, not curves
"""
for axes in [self.ax, self.ax2]:
n = list(range(len(axes.patches)))
n.reverse()
for i in n:
item = axes.patches[i]
label = item.get_label()
if label.startswith("__ITEM__"):
item.remove()
del item
def removeItem(self, handle, replot=True):
if hasattr(handle, "remove"):
for axes in [self.ax, self.ax2]:
if handle in axes.patches:
handle.remove()
del handle
break
else:
# we have received a legend!
# we have received a legend!
legend = handle
handle = None
for axes in [self.ax, self.ax2]:
if handle is not None:
break
for item in axes.patches:
label = item.get_label()
if label == ("__ITEM__"+legend):
handle = item
break
if handle is not None:
handle.remove()
del handle
if replot:
self.replot()
def getGraphXLimits(self):
"""
Get the graph X (bottom) limits.
:return: Minimum and maximum values of the X axis
"""
vmin, vmax = self.ax.get_xlim()
if vmin > vmax:
return vmax, vmin
else:
return vmin, vmax
def getGraphYLimits(self, axis="left"):
if axis == "right":
ax = self.ax2
else:
ax = self.ax
vmin, vmax = ax.get_ylim()
if vmin > vmax:
return vmax, vmin
else:
return vmin, vmax
def getWidgetHandle(self):
"""
:return: Backend widget.
"""
if hasattr(self.graph, "get_tk_widget"):
return self.graph.get_tk_widget()
else:
return self.graph
def enableAxis(self, axis, flag=True):
"""
:param axis: Axis to be shown or hidden
:type axis: string (left, right, top, bottom)
:param flag: Boolean (default, True)
"""
if axis == "right":
self.ax2.get_yaxis().set_visible(flag)
self._rightAxisEnabled = flag
elif axis == "left":
self.ax.get_yaxis().set_visible(flag)
else:
print("unhandled axis %s" % axis)
def insertMarker(self, x, y, legend=None, text=None, color='k',
selectable=False, draggable=False, replot=True,
symbol=None, constraint=None,
**kw):
"""
:param x: Horizontal position of the marker in graph coordenates
:type x: float
:param y: Vertical position of the marker in graph coordenates
:type y: float
:param label: Legend associated to the marker
:type label: string
:param color: Color to be used for instance 'blue', 'b', '#FF0000'
:type color: string, default 'k' (black)
:param selectable: Flag to indicate if the marker can be selected
:type selectable: boolean, default False
:param draggable: Flag to indicate if the marker can be moved
:type draggable: boolean, default False
:param replot: Flag to indicate if the plot is to be updated
:type replot: boolean, default True
:param str symbol: Symbol representing the marker
:param constraint: None or a function filtering marker displacements.
:return: Handle used by the backend to univocally access the marker
"""
#line = self.ax.axvline(x, picker=True)
xmin, xmax = self.getGraphXLimits()
ymin, ymax = self.getGraphYLimits()
if x is None:
x = 0.5 * (xmax + xmin)
if y is None:
y = 0.5 * (ymax + ymin)
# Apply constraint to provided position
if draggable and constraint is not None:
x, y = constraint(x, y)
if legend is None:
legend = "Unnamed marker"
if text is None:
text = kw.get("label", None)
if text is not None:
print("Deprecation warning: use 'text' instead of 'label'")
self.removeMarker(legend, replot=False)
legend = "__MARKER__" + legend
if symbol is None:
symbol = "+"
markersize=10.
if selectable or draggable:
line = self.ax.plot(x, y, label=legend,
linestyle=" ",
color=color,
picker=True,
pickradius=5,
marker=symbol,
markersize=markersize)[-1]
else:
line = self.ax.plot(x, y, label=legend,
linestyle=" ",
color=color,
picker=False,
marker=symbol,
markersize=markersize)[-1]
if text is not None:
xtmp, ytmp = self.ax.transData.transform((x, y))
inv = self.ax.transData.inverted()
xtmp, ytmp = inv.transform((xtmp, ytmp + 15))
text = " " + text
line._infoText = self.ax.text(x, ytmp, text,
color=color,
horizontalalignment='left',
verticalalignment='top')
line._constraint = constraint if draggable else None
#line.set_ydata(numpy.array([1.0, 10.], dtype=numpy.float32))
line._plot_options = ["marker"]
if selectable:
line._plot_options.append('selectable')
if draggable:
line._plot_options.append('draggable')
if replot:
self.replot()
return line
def insertXMarker(self, x, legend=None, text=None,
color='k', selectable=False, draggable=False,
replot=True, **kw):
"""
:param x: Horizontal position of the marker in graph coordenates
:type x: float
:param legend: Legend associated to the marker
:type legend: string
:param label: Text associated to the marker
:type label: string or None
:param color: Color to be used for instance 'blue', 'b', '#FF0000'
:type color: string, default 'k' (black)
:param selectable: Flag to indicate if the marker can be selected
:type selectable: boolean, default False
:param draggable: Flag to indicate if the marker can be moved
:type draggable: boolean, default False
:param replot: Flag to indicate if the plot is to be updated
:type replot: boolean, default True
:return: Handle used by the backend to univocally access the marker
"""
#line = self.ax.axvline(x, picker=True)
if legend is None:
legend = "Unnamed marker"
if text is None:
text = kw.get("label", None)
if text is not None:
print("Deprecation warning: use 'text' instead of 'label'")
self.removeMarker(legend, replot=False)
legend = "__MARKER__" + legend
if selectable or draggable:
line = self.ax.axvline(x, label=legend, color=color,
picker=True, pickradius=5)
else:
line = self.ax.axvline(x, label=legend, color=color)
if text is not None:
text = " " + text
ymin, ymax = self.getGraphYLimits()
delta = abs(ymax - ymin)
if ymin > ymax:
ymax = ymin
ymax -= 0.005 * delta
line._infoText = self.ax.text(x, ymax, text,
color=color,
horizontalalignment='left',
verticalalignment='top')
#line.set_ydata(numpy.array([1.0, 10.], dtype=numpy.float32))
line._plot_options = ["xmarker"]
if selectable:
line._plot_options.append('selectable')
if draggable:
line._plot_options.append('draggable')
if replot:
self.replot()
return line
def insertYMarker(self, y, legend=None, text=None,
color='k', selectable=False, draggable=False,
replot=True, **kw):
"""
:param y: Vertical position of the marker in graph coordenates
:type y: float
:param legend: Legend associated to the marker
:type legend: string
:param label: Text associated to the marker
:type label: string or None
:param color: Color to be used for instance 'blue', 'b', '#FF0000'
:type color: string, default 'k' (black)
:param selectable: Flag to indicate if the marker can be selected
:type selectable: boolean, default False
:param draggable: Flag to indicate if the marker can be moved
:type draggable: boolean, default False
:param replot: Flag to indicate if the plot is to be updated
:type replot: boolean, default True
:return: Handle used by the backend to univocally access the marker
"""
if legend is None:
legend = "Unnamed marker"
if text is None:
text = kw.get("label", None)
if text is not None:
print("Deprecation warning: use 'text' instead of 'label'")
legend = "__MARKER__" + legend
if selectable or draggable:
line = self.ax.axhline(y, label=legend, color=color,
picker=True, pickradius=5)
else:
line = self.ax.axhline(y, label=legend, color=color)
if text is not None:
text = " " + text
xmin, xmax = self.getGraphXLimits()
delta = abs(xmax - xmin)
if xmin > xmax:
xmax = xmin
xmax -= 0.005 * delta
line._infoText = self.ax.text(y, xmax, text,
color=color,
horizontalalignment='left',
verticalalignment='top')
line._plot_options = ["ymarker"]
if selectable:
line._plot_options.append('selectable')
if draggable:
line._plot_options.append('draggable')
if replot:
self.replot()
return line
def isXAxisAutoScale(self):
if self._xAutoScale:
return True
else:
return False
def isYAxisAutoScale(self):
if self._yAutoScale:
return True
else:
return False
def removeCurve(self, handle, replot=True):
if hasattr(handle, "remove"):
if handle in self.ax.lines:
handle.remove()
if handle in self.ax2.lines:
handle.remove()
if handle in self.ax.collections:
handle.remove()
if handle in self.ax2.collections:
handle.remove()
else:
# we have received a legend!
legend = handle
testLists = [self.ax.lines, self.ax2.lines,
self.ax.collections, self.ax2.collections]
for container in testLists:
for line2d in container:
handle = None
label = line2d.get_label()
if label == legend:
handle = line2d
if handle is not None:
handle.remove()
del handle
if replot:
self.replot()
def removeImage(self, handle, replot=True):
if hasattr(handle, "remove"):
if (handle in self.ax.images) or (handle in self.ax.artists):
handle.remove()
else:
# we have received a legend!
legend = handle
handle = None
for item in self.ax.artists:
label = item.get_label()
if label == ("__IMAGE__" + legend):
handle = item
if handle is None:
for item in self.ax.images:
label = item.get_label()
if label == legend:
handle = item
if handle is not None:
handle.remove()
del handle
if replot:
self.replot()
def removeMarker(self, handle, replot=True):
if hasattr(handle, "remove"):
self._removeInfoText(handle)
try:
handle.remove()
except ValueError:
# it seems it was already removed
pass
del handle
else:
# we have received a legend!
legend = handle
done = False
for axes in [self.ax, self.ax2]:
for line2d in axes.lines:
if done:
break
label = line2d.get_label()
if label == ("__MARKER__" + legend):
if hasattr(line2d, "_infoText"):
line2d._infoText.remove()
line2d.remove()
del line2d
done = True
if replot:
self.replot()
def _removeInfoText(self, handle):
if hasattr(handle, "_infoText"):
t = handle._infoText
handle._infoText = None
try:
t.remove()
except ValueError:
# it seems it was already removed
pass
del t
def resetZoom(self, dataMargins=None):
"""
It should autoscale any axis that is in autoscale mode
"""
xmin, xmax = self.getGraphXLimits()
ymin, ymax = self.getGraphYLimits()
xAuto = self.isXAxisAutoScale()
yAuto = self.isYAxisAutoScale()
if xAuto and yAuto:
self.graph.resetZoom(dataMargins)
elif yAuto:
self.graph.resetZoom(dataMargins)
self.setGraphXLimits(xmin, xmax)
elif xAuto:
self.graph.resetZoom(dataMargins)
self.setGraphYLimits(ymin, ymax)
else:
if DEBUG:
print("Nothing to autoscale")
#xmin2, xmax2, ymin2, ymax2 = self.graph.getDataLimits('right')
#self.ax2.figure.sca(self.ax2)
#self.ax2.set_ylim(10., 100.)
#self.ax2.figure.sca(self.ax)
self._zoomStack = []
self.replot()
return
def replot(self):
"""
Update plot
"""
if self._rightAxisEnabled is not None:
# the right axis was initialized at a certain point
# so, we have to see if there is something still mapped
# to that axis.
# For the time being we only check lines
if not len(self.ax2.lines):
self.enableAxis('right', False)
self._rightAxisEnabled = None
try:
self.graph.draw()
except ValueError:
# TODO: Understand why matplotlib 2.1.0rc0 raises an
# error when toggling semilogarithmic axes and previous
# versions not.
if DEBUG:
print("MatplotlibBackend ERROR", sys.exc_info())
return
def saveGraph(self, fileName, fileFormat='svg', dpi=None , **kw):
# fileName can be also a StringIO or file instance
fig = self.ax.figure
if dpi is not None:
fig.savefig(fileName, format=fileFormat, dpi=dpi)
else:
fig.savefig(fileName, format=fileFormat)
fig = None
return
def setActiveCurve(self, legend, replot=True):
if not self._activeCurveHandling:
return
if hasattr(legend, "_plot_info"):
# we have received an actual item
handle = legend
else:
# we have received a legend
handle = None
for line2d in self.ax.lines:
label = line2d.get_label()
if label.startswith("__MARKER__"):
continue
if label == legend:
handle = line2d
axes = self.ax
break
if handle is None:
for line2d in self.ax2.lines:
label = line2d.get_label()
if label.startswith("__MARKER__"):
continue
if label == legend:
handle = line2d
axes = self.ax2
break
if handle is not None:
handle.set_color(self._activeCurveColor)
else:
raise KeyError("Curve %s not found" % legend)
if self._oldActiveCurve in self.ax.lines:
if self._oldActiveCurve._plot_info['label'] != legend:
color = self._oldActiveCurve._plot_info['color']
self._oldActiveCurve.set_color(color)
elif self._oldActiveCurve in self.ax2.lines:
if self._oldActiveCurve._plot_info['label'] != legend:
color = self._oldActiveCurve._plot_info['color']
self._oldActiveCurve.set_color(color)
elif self._oldActiveCurveLegend is not None:
if self._oldActiveCurveLegend != handle._plot_info['label']:
done = False
for line2d in self.ax.lines:
label = line2d.get_label()
if label == self._oldActiveCurveLegend:
color = line2d._plot_info['color']
line2d.set_color(color)
done = True
break
if not done:
for line2d in self.ax2.lines:
label = line2d.get_label()
if label == self._oldActiveCurveLegend:
color = line2d._plot_info['color']
line2d.set_color(color)
break
#update labels according to active curve???
if hasattr(handle, "_plot_info"):
xLabel = handle._plot_info.get("xlabel", None)
yLabel = handle._plot_info.get("ylabel", None)
if (xLabel is not None) and (yLabel is not None):
axes.set_xlabel(xLabel)
axes.set_ylabel(yLabel)
self._oldActiveCurve = handle
self._oldActiveCurveLegend = handle.get_label()
if replot:
self.replot()
def setCallback(self, callbackFunction):
self.graph.setCallback(callbackFunction)
# Should I call the base to keep a copy?
# It does not seem necessary since the graph will do it.
def getGraphTitle(self):
return self.ax.get_title()
def getGraphXLabel(self):
return self.ax.get_xlabel()
def getGraphYLabel(self):
return self.ax.get_ylabel()
def setGraphTitle(self, title=""):
self.ax.set_title(title)
def setGraphXLabel(self, label="X"):
self.ax.set_xlabel(label)
def setGraphXLimits(self, xmin, xmax):
if xmin == xmax:
delta = 0.044
xmax += delta
xmin -= delta
self.ax.set_xlim(xmin, xmax)
self.graph.emitLimitsChangedSignal()
def setGraphYLabel(self, label="Y"):
self.ax.set_ylabel(label)
def setGraphYLimits(self, ymin, ymax):
if ymin == ymax:
delta = 0.044
ymax += delta
ymin -= delta
if self.ax.yaxis_inverted():
self.ax.set_ylim(ymax, ymin)
else:
self.ax.set_ylim(ymin, ymax)
self.graph.emitLimitsChangedSignal()
def setLimits(self, xmin, xmax, ymin, ymax):
# Overrides PlotBackend to send a single limitsChanged event.
self.ax.set_xlim(xmin, xmax)
if self.ax.yaxis_inverted():
self.ax.set_ylim(ymax, ymin)
else:
self.ax.set_ylim(ymin, ymax)
self.graph.emitLimitsChangedSignal()
def setXAxisAutoScale(self, flag=True):
if flag:
self._xAutoScale = True
else:
self._xAutoScale = False
def setXAxisLogarithmic(self, flag):
if flag:
self._logX = True
if hasattr(self.ax2, "get_visible"):
if self.ax2.get_visible():
self.ax2.set_xscale('log')
self.ax.set_xscale('log')
else:
self._logX = False
if hasattr(self.ax2, "get_visible"):
if self.ax2.get_visible():
self.ax2.set_xscale('linear')
self.ax.set_xscale('linear')
def setYAxisAutoScale(self, flag=True):
if flag:
self._yAutoScale = True
else:
self._yAutoScale = False
def setYAxisLogarithmic(self, flag):
"""
:param flag: If True, the left axis will use a log scale
:type flag: boolean
"""
if flag:
self._logY = True
if hasattr(self.ax2, "get_visible"):
if self.ax2.get_visible():
self.ax2.set_yscale('log')
self.ax.set_yscale('log')
else:
self._logY = False
if hasattr(self.ax2, "get_visible"):
if self.ax2.get_visible():
self.ax2.set_yscale('linear')
self.ax.set_yscale('linear')
def addImage(self, data, legend=None, info=None,
replace=True, replot=True,
xScale=None, yScale=None, z=0,
selectable=False, draggable=False,
colormap=None, **kw):
"""
:param data: (nrows, ncolumns) data or (nrows, ncolumns, RGBA) ubyte array
:type data: numpy.ndarray
:param legend: The legend to be associated to the curve
:type legend: string or None
:param info: Dictionary of information associated to the image
:type info: dict or None
:param replace: Flag to indicate if already existing images are to be deleted
:type replace: boolean default True
:param replot: Flag to indicate plot is to be immediately updated
:type replot: boolean default True
:param xScale: Two floats defining the x scale
:type xScale: list or numpy.ndarray
:param yScale: Two floats defining the y scale
:type yScale: list or numpy.ndarray
:param z: level at which the image is to be located (to allow overlays).
:type z: A number bigger than or equal to zero (default)
:param selectable: Flag to indicate if the image can be selected
:type selectable: boolean, default False
:param draggable: Flag to indicate if the image can be moved
:type draggable: boolean, default False
:param colormap: Dictionary describing the colormap to use (or None)
:type colormap: Dictionary or None (default). Ignored if data is RGB(A)
:returns: The legend/handle used by the backend to univocally access it.
"""
# Non-uniform image
#http://wiki.scipy.org/Cookbook/Histograms
# Non-linear axes
#http://stackoverflow.com/questions/11488800/non-linear-axes-for-imshow-in-matplotlib
if legend is None:
legend = 'Unnamed image'
if replace:
self.clearImages()
else:
# make sure we do not cummulate images with same name
self.removeImage(legend, replot=False)
if xScale is None:
xScale = [0.0, 1.0]
if yScale is None:
yScale = [0.0, 1.0]
h, w = data.shape[0:2]
xmin = xScale[0]
xmax = xmin + xScale[1] * w
ymin = yScale[0]
ymax = ymin + yScale[1] * h
extent = (xmin, xmax, ymax, ymin)
if selectable or draggable:
picker = True
else:
picker = False
shape = data.shape
if 0:
# this supports non regularly spaced coordenates!!!!
x = xmin + numpy.arange(w) * xScale[1]
y = ymin + numpy.arange(h) * yScale[1]
image = NonUniformImage(self.ax,
interpolation='nearest',
#aspect='auto',
extent=extent,
picker=picker,
cmap=cmap)
image.set_data(x, y, data)
xmin, xmax = self.getGraphXLimits()
ymin, ymax = self.getGraphYLimits()
self.ax.images.append(image)
self.ax.set_xlim(xmin, xmax)
self.ax.set_ylim(ymin, ymax)
elif 1:
#the normalization can be a source of time waste
# Two possibilities, we receive data or a ready to show image
if len(data.shape) == 3:
if data.shape[-1] == 4:
# force alpha(?)
# data[:,:,3] = 255
pass
if len(shape) == 3:
# RGBA image
# TODO: Possibility to mirror the image
# in case of pixmaps just setting
# extend = (xmin, xmax, ymax, ymin)
# instead of (xmin, xmax, ymin, ymax)
extent = (xmin, xmax, ymin, ymax)
if tuple(xScale) != (0., 1.) or tuple(yScale) != (0., 1.):
# for the time being not properly handled
imageClass = AxesImage
elif (shape[0] * shape[1]) > 5.0e5:
imageClass = ModestImage
else:
imageClass = AxesImage
image = imageClass(self.ax,
label="__IMAGE__"+legend,
interpolation='nearest',
picker=picker,
zorder=z)
if image.origin == 'upper':
image.set_extent((xmin, xmax, ymax, ymin))
else:
image.set_extent((xmin, xmax, ymin, ymax))
image.set_data(data)
else:
if colormap is None:
colormap = self.getDefaultColormap()
cmap = self.__getColormap(colormap['name'])
if colormap['normalization'].startswith('log'):
vmin, vmax = None, None
if not colormap['autoscale']:
if colormap['vmin'] > 0.:
vmin = colormap['vmin']
if colormap['vmax'] > 0.:
vmax = colormap['vmax']
if vmin is None or vmax is None:
print('Warning: ' +
'Log colormap with negative bounds, ' +
'changing bounds to positive ones.')
elif vmin > vmax:
print('Warning: Colormap bounds are inverted.')
vmin, vmax = vmax, vmin
# Set unset/negative bounds to positive bounds
if vmin is None or vmax is None:
posData = data[data > 0]
if vmax is None:
# 1. as an ultimate fallback
vmax = posData.max() if posData.size > 0 else 1.
if vmin is None:
vmin = posData.min() if posData.size > 0 else vmax
if vmin > vmax:
vmin = vmax
norm = LogNorm(vmin, vmax)
else: # Linear normalization
if colormap['autoscale']:
vmin = data.min()
vmax = data.max()
else:
vmin = colormap['vmin']
vmax = colormap['vmax']
if vmin > vmax:
print('Warning: Colormap bounds are inverted.')
vmin, vmax = vmax, vmin
norm = Normalize(vmin, vmax)
# try as data
if tuple(xScale) != (0., 1.) or tuple(yScale) != (0., 1.):
# for the time being not properly handled
imageClass = AxesImage
elif (shape[0] * shape[1]) > 5.0e5:
imageClass = ModestImage
else:
imageClass = AxesImage
image = imageClass(self.ax,
label="__IMAGE__"+legend,
interpolation='nearest',
#origin=
cmap=cmap,
extent=extent,
picker=picker,
zorder=z,
norm=norm)
if image.origin == 'upper':
image.set_extent((xmin, xmax, ymax, ymin))
else:
image.set_extent((xmin, xmax, ymin, ymax))
image.set_data(data)
self.ax.add_artist(image)
#self.ax.draw_artist(image)
image._plot_info = {'label':legend,
'type':'image',
'xScale':xScale,
'yScale':yScale,
'z':z}
image._plot_options = []
if draggable:
image._plot_options.append('draggable')
if selectable:
image._plot_options.append('selectable')
return image
def invertYAxis(self, flag=True):
if flag:
if not self.ax.yaxis_inverted():
self.ax.invert_yaxis()
else:
if self.ax.yaxis_inverted():
self.ax.invert_yaxis()
def isYAxisInverted(self):
return self.ax.yaxis_inverted()
def showGrid(self, flag=True):
if flag == 1:
if hasattr(self.ax.xaxis, "set_tick_params"):
self.ax.xaxis.set_tick_params(which='major')
self.ax.yaxis.set_tick_params(which='major')
self.ax.grid(which='major')
elif flag == 2:
if hasattr(self.ax.xaxis, "set_tick_params"):
self.ax.xaxis.set_tick_params(which='both')
self.ax.yaxis.set_tick_params(which='both')
self.ax.grid(which='both')
elif flag:
if hasattr(self.ax.xaxis, "set_tick_params"):
self.ax.xaxis.set_tick_params(which='major')
self.ax.yaxis.set_tick_params(which='major')
self.ax.grid(True)
else:
self.ax.grid(False)
self.replot()
def keepDataAspectRatio(self, flag=True):
"""
:param flag: True to respect data aspect ratio
:type flag: Boolean, default True
"""
if flag:
for axes in [self.ax]:
if axes.get_aspect() not in [1.0]:
axes.set_aspect(1.0)
self.resetZoom()
else:
for axes in [self.ax]:
if axes.get_aspect() not in ['auto', None]:
axes.set_aspect('auto')
self.resetZoom()
def isKeepDataAspectRatio(self):
return self.ax.get_aspect() in (1.0, 'equal')
def setDefaultColormap(self, colormap=None):
if colormap is None:
colormap = {'name': 'gray', 'normalization':'linear',
'autoscale':True, 'vmin':0.0, 'vmax':1.0,
'colors':256}
self._defaultColormap = colormap
def getDefaultColormap(self):
if not hasattr(self, "_defaultColormap"):
self.setDefaultColormap(None)
return self._defaultColormap
def getSupportedColormaps(self):
default = ['gray', 'reversed gray', 'temperature', 'red', 'green', 'blue']
maps = [m for m in cm.datad]
maps.sort()
return default + maps
def __getColormap(self, name):
if not hasattr(self, "__temperatureCmap"):
#initialize own colormaps
cdict = {'red': ((0.0, 0.0, 0.0),
(1.0, 1.0, 1.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0))}
self.__redCmap = LinearSegmentedColormap('red',cdict,256)
cdict = {'red': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 1.0, 1.0)),
'blue': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0))}
self.__greenCmap = LinearSegmentedColormap('green',cdict,256)
cdict = {'red': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(1.0, 1.0, 1.0))}
self.__blueCmap = LinearSegmentedColormap('blue',cdict,256)
# Temperature as defined in spslut
cdict = {'red': ((0.0, 0.0, 0.0),
(0.5, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)),
'green': ((0.0, 0.0, 0.0),
(0.25, 1.0, 1.0),
(0.75, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 1.0, 1.0),
(0.25, 1.0, 1.0),
(0.5, 0.0, 0.0),
(1.0, 0.0, 0.0))}
#but limited to 256 colors for a faster display (of the colorbar)
self.__temperatureCmap = LinearSegmentedColormap('temperature',
cdict, 256)
#reversed gray
cdict = {'red': ((0.0, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'green': ((0.0, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 1.0, 1.0),
(1.0, 0.0, 0.0))}
self.__reversedGrayCmap = LinearSegmentedColormap('yerg', cdict, 256)
if name == "reversed gray":
return self.__reversedGrayCmap
elif name == "temperature":
return self.__temperatureCmap
elif name == "red":
return self.__redCmap
elif name == "green":
return self.__greenCmap
elif name == "blue":
return self.__blueCmap
else:
# built in
return cm.get_cmap(name)
def dataToPixel(self, x=None, y=None, axis="left"):
"""
Convert a position in data space to a position in pixels in the widget.
:param float x: The X coordinate in data space. If None (default)
the middle position of the displayed data is used.
:param float y: The Y coordinate in data space. If None (default)
the middle position of the displayed data is used.
:param str axis: The Y axis to use for the conversion
('left' or 'right').
:returns: The corresponding position in pixels or
None if the data position is not in the displayed area.
:rtype: A tuple of 2 floats: (xPixel, yPixel) or None.
"""
assert axis in ("left", "right")
if "axis" == "right":
ax = self.ax2
else:
ax = self.ax
xmin, xmax = self.getGraphXLimits()
ymin, ymax = self.getGraphYLimits(axis=axis)
if x is None:
x = 0.5 * (xmax - xmin)
if y is None:
y = 0.5 * (ymax - ymin)
if (x > xmax) or (x < xmin):
return None
if (y > ymax) or (y < ymin):
return None
pixels = ax.transData.transform([x, y])
xPixel, yPixel = pixels.T
return xPixel, yPixel
def pixelToData(self, x=None, y=None, axis="left"):
assert axis in ("left", "right")
if "axis" == "right":
ax = self.ax2
else:
ax = self.ax
inv = ax.transData.inverted()
x, y = inv.transform((x, y))
xmin, xmax = self.getGraphXLimits()
ymin, ymax = self.getGraphYLimits(axis=axis)
if (x > xmax) or (x < xmin):
return None
if (y > ymax) or (y < ymin):
return None
return x, y
def main(parent=None):
from .. import Plot
x = numpy.arange(100.)
y = x * x
plot = Plot.Plot(parent, backend=MatplotlibBackend)
plot.addCurve(x, y, "dummy")
plot.addCurve(x + 100, -x * x, "To set Active")
#info = {}
#info['plot_yaxis'] = 'right'
#plot.addCurve(x + 100, -x * x + 500, "RIGHT", info=info)
#print("Active curve = ", plot.getActiveCurve())
print("X Limits) = ", plot.getGraphXLimits())
print("Y Limits = ", plot.getGraphYLimits())
#print("All curves = ", plot.getAllCurves())
#plot.removeCurve("dummy")
plot.setActiveCurve("To set Active")
#print("All curves = ", plot.getAllCurves())
#plot.resetZoom()
return plot
if __name__ == "__main__":
if ("tkinter" in sys.modules) or ("Tkinter" in sys.modules):
root = Tk.Tk()
parent=root
#w = MatplotlibGraph(root)
#Tk.mainloop()
#sys.exit(0)
w = main(parent)
widget = w._plot.graph
else:
app = QtGui.QApplication([])
parent = None
w = main(parent)
widget = w.getWidgetHandle()
#w.invertYAxis(True)
w.replot()
#w.invertYAxis(True)
data = numpy.arange(1000.*1000)
data.shape = 10000,100
#plot.replot()
#w.invertYAxis(True)
#w.replot()
#w.widget.show()
w.addImage(data, legend="image 0", xScale=(25, 1.0) , yScale=(-1000, 1.0),
selectable=True)
w.removeImage("image 0")
#w.invertYAxis(True)
#w.replot()
w.addImage(data, legend="image 1", xScale=(25, 1.0) , yScale=(-1000, 1.0),
replot=False, selectable=True)
#w.invertYAxis(True)
widget.ax.axis('auto') # appropriate for curves, no aspect ratio
#w.widget.ax.axis('equal') # candidate for keepting aspect ratio
#w.widget.ax.axis('scaled') # candidate for keepting aspect ratio
w.insertXMarker(50., text="Label", color='pink', draggable=True)
w.insertMarker(25, -5000, text="Label\n", color='pink', draggable=True)
w.resetZoom()
#print(w.widget.ax.get_images())
#print(w.widget.ax.get_lines())
if ("tkinter" in sys.modules) or ("Tkinter" in sys.modules):
tkWidget = w.getWidgetHandle()
tkWidget.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
Tk.mainloop()
else:
widget.show()
app.exec()
|