1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962
|
"""Module containing pyvista wrappers for the vtk Charts API."""
from __future__ import annotations
from functools import wraps
import inspect
import itertools
import re
from typing import TYPE_CHECKING
from typing import ClassVar
from typing import Sequence
import weakref
from matplotlib.backends.backend_agg import FigureCanvasAgg
import matplotlib.pyplot as plt
import numpy as np
import pyvista
from pyvista import vtk_version_info
from . import _vtk
from .colors import COLOR_SCHEMES
from .colors import SCHEME_NAMES
from .colors import Color
from .colors import color_synonyms
from .colors import hexcolors
if TYPE_CHECKING: # pragma: no cover
from ._typing import Chart
# region Some metaclass wrapping magic
class _vtkWrapperMeta(type):
def __init__(cls, clsname, bases, attrs):
# Restore the signature of classes inheriting from _vtkWrapper
# Based on https://stackoverflow.com/questions/49740290/call-from-metaclass-shadows-signature-of-init
sig = inspect.signature(cls.__init__)
params = list(sig.parameters.values())
params.insert(
len(params) - 1 if params[-1].kind == inspect.Parameter.VAR_KEYWORD else len(params),
inspect.Parameter("_wrap", inspect.Parameter.KEYWORD_ONLY, default=None),
)
cls.__signature__ = sig.replace(parameters=params[1:])
super().__init__(clsname, bases, attrs)
def __call__(cls, *args, _wrap=None, **kwargs):
obj = cls.__new__(cls, *args, **kwargs)
obj._wrapped = _wrap
obj.__init__(*args, **kwargs)
return obj
class _vtkWrapper(metaclass=_vtkWrapperMeta):
def __getattribute__(self, item):
unwrapped_attrs = ["_wrapped", "__class__", "__init__"]
wrapped = super().__getattribute__("_wrapped")
if item in unwrapped_attrs or wrapped is None:
return super().__getattribute__(item)
else:
try:
return wrapped.__getattribute__(item)
except AttributeError:
return super().__getattribute__(item)
def __str__(self):
if self._wrapped is None:
return super().__str__()
else:
return "Wrapped: " + self._wrapped.__str__()
# endregion
# region Documentation substitution
class DocSubs:
"""Helper class to easily substitute the docstrings of the listed member functions or properties."""
# The substitutions to use for this (sub)class
_DOC_SUBS: dict[str, str] | None = None
# Internal dictionary to store registered member functions/properties and their (to be substituted) docs.
_DOC_STORE = {} # type: ignore[var-annotated] # noqa: RUF012
# Tag used to mark members that require docstring substitutions.
_DOC_TAG = ":DOC_SUBS:"
def __init_subclass__(cls, **kwargs):
"""Initialize subclasses."""
# First substitute all members for this class (marked in a super class)
if cls._DOC_SUBS is not None:
subs = {**cls._DOC_SUBS}
if "cls" not in subs:
subs["cls"] = cls.__name__
for member_name, (m, d) in cls._DOC_STORE.items():
if member_name not in cls.__dict__:
# If the member is not part of the subclass' __dict__, we have to generate a wrapping
# function or property and add it to the subclass' __dict__. Otherwise, the docstring
# of the superclass would be used for the substitutions.
mem_sub = cls._wrap_member(m)
mem_sub.__doc__ = d
setattr(cls, member_name, mem_sub)
# Get the member function/property and substitute its docstring.
member = getattr(cls, member_name)
member.__doc__ = member.__doc__.format(**subs)
# Secondly, register all members of this class that require substitutions in subclasses
# Create copy of registered members so far
# TODO: B010
setattr(cls, "_DOC_STORE", {**cls._DOC_STORE}) # noqa: B010
for member_name, member in cls.__dict__.items():
if member.__doc__ and member.__doc__.startswith(cls._DOC_TAG):
# New method/property to register in this class (denoting their docstring should be
# substituted in subsequent child classes).
cls._DOC_STORE[member_name] = (member, member.__doc__[len(cls._DOC_TAG) :])
# Overwrite original docstring to prevent doctest issues
member.__doc__ = """Docstring to be specialized in subclasses."""
@staticmethod
def _wrap_member(member):
if callable(member):
@wraps(member)
def mem_sub(*args, **kwargs):
return member(*args, **kwargs)
elif isinstance(member, property):
mem_sub = property(member.fget, member.fset, member.fdel)
else:
raise NotImplementedError(
"Members other than methods and properties are currently not supported.",
)
return mem_sub
def doc_subs(member): # numpydoc ignore=PR01,RT01
"""Doc subs wrapper.
Only common attribute between methods and properties that we can
modify is __doc__, so use that to mark members that need doc
substitutions.
Still, only methods can be marked for doc substitution (as for
properties the docstring seems to be overwritten when specifying
setters or deleters), hence this decorator should be applied
before the property decorator.
"""
# Ensure we are operating on a method
if not callable(member): # pragma: no cover
raise ValueError('`member` must be a callable.')
member.__doc__ = DocSubs._DOC_TAG + member.__doc__
return member
# endregion
class Pen(_vtkWrapper, _vtk.vtkPen):
"""Pythonic wrapper for a VTK Pen, used to draw lines.
Parameters
----------
color : ColorLike, default: "k"
Color of the lines drawn using this pen. Any color parsable by
:class:`pyvista.Color` is allowed.
width : float, default: 1
Width of the lines drawn using this pen.
style : str, default: "-"
Style of the lines drawn using this pen. See
:ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed
line styles.
Notes
-----
.. _pen_line_styles:
LINE_STYLES : dict
Dictionary containing all allowed line styles as its keys.
.. include:: ../pen_line_styles.rst
"""
LINE_STYLES: ClassVar[
dict[str, dict[str, int | str]]
] = { # descr is used in the documentation, set to None to hide it from the docs.
"": {"id": _vtk.vtkPen.NO_PEN, "descr": "Hidden"},
"-": {"id": _vtk.vtkPen.SOLID_LINE, "descr": "Solid"},
"--": {"id": _vtk.vtkPen.DASH_LINE, "descr": "Dashed"},
":": {"id": _vtk.vtkPen.DOT_LINE, "descr": "Dotted"},
"-.": {"id": _vtk.vtkPen.DASH_DOT_LINE, "descr": "Dash-dot"},
"-..": {"id": _vtk.vtkPen.DASH_DOT_DOT_LINE, "descr": "Dash-dot-dot"},
}
def __init__(self, color="k", width=1, style="-"):
"""Initialize a new Pen instance."""
super().__init__()
self.color = color
self.width = width
self.style = style
@property
def color(self): # numpydoc ignore=RT01
"""Return or set the pen's color.
Examples
--------
Set the pen's color to red.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.line([0, 1, 2], [2, 1, 3])
>>> plot.pen.color = 'r'
>>> chart.show()
"""
return self._color
@color.setter
def color(self, val): # numpydoc ignore=GL08
self._color = Color(val, default_color="black")
self.SetColor(*self._color.int_rgba)
@property
def width(self): # numpydoc ignore=RT01
"""Return or set the pen's width.
Examples
--------
Set the pen's width to 10
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.line([0, 1, 2], [2, 1, 3])
>>> plot.pen.width = 10
>>> chart.show()
"""
return self.GetWidth()
@width.setter
def width(self, val): # numpydoc ignore=GL08
self.SetWidth(float(val))
@property
def style(self): # numpydoc ignore=RT01
"""Return or set the pen's line style.
See :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed line styles.
Examples
--------
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.line([0, 1, 2], [2, 1, 3])
>>> plot.pen.style = '-.'
>>> chart.show()
"""
return self._line_style
@style.setter
def style(self, val): # numpydoc ignore=GL08
if val is None:
val = ""
try:
self.SetLineType(self.LINE_STYLES[val]["id"])
self._line_style = val
except KeyError:
formatted_styles = "\", \"".join(self.LINE_STYLES.keys())
raise ValueError(f"Invalid line style. Allowed line styles: \"{formatted_styles}\"")
class Brush(_vtkWrapper, _vtk.vtkBrush):
"""Pythonic wrapper for a VTK Brush, used to fill shapes.
Parameters
----------
color : ColorLike, default: "k"
Fill color of the shapes drawn using this brush. Any color
parsable by :class:`pyvista.Color` is allowed.
texture : pyvista.Texture, optional
Texture used to fill shapes drawn using this brush. Any object
convertible to a :class:`pyvista.Texture` is allowed. Defaults to
``None``.
"""
def __init__(self, color="k", texture=None):
"""Initialize a new Pen instance."""
super().__init__()
self.color = color
self.texture = texture
self._interpolate = True # vtkBrush textureProperties defaults to LINEAR & STRETCH
self._repeat = False
@property
def color(self): # numpydoc ignore=RT01
"""Return or set the brush's color.
Examples
--------
Set the brush's color to red.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
>>> plot.brush.color = 'r'
>>> chart.show()
"""
return self._color
@color.setter
def color(self, val): # numpydoc ignore=GL08
self._color = Color(val, default_color="black")
self.SetColor(*self._color.int_rgba)
@property
def texture(self): # numpydoc ignore=RT01
"""Return or set the brush's texture.
Examples
--------
Set the brush's texture to the sample puppy texture.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> from pyvista import examples
>>> chart = pv.Chart2D()
>>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
>>> plot.brush.texture = examples.download_puppy_texture()
>>> chart.show()
"""
return self._texture
@texture.setter
def texture(self, val): # numpydoc ignore=GL08
if val is None:
self._texture = None
self.SetTexture(None)
else:
self._texture = pyvista.Texture(val)
self.SetTexture(self._texture.to_image())
@property
def texture_interpolate(self): # numpydoc ignore=RT01
"""Set texture interpolation mode.
There are two modes:
* ``False`` - NEAREST
* ``True`` - LINEAR
Examples
--------
Set up a brush with a texture.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> from pyvista import examples
>>> chart = pv.Chart2D()
>>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
>>> plot.brush.texture = examples.download_puppy_texture()
>>> chart.show()
Disable linear interpolation.
>>> plot.brush.texture_interpolate = False
>>> chart.show()
"""
return self._interpolate
@texture_interpolate.setter
def texture_interpolate(self, val): # numpydoc ignore=GL08
self._interpolate = bool(val)
self._update_textureprops()
@property
def texture_repeat(self): # numpydoc ignore=RT01
"""Return or set the texture repeat mode.
There are two modes:
* ``False`` - STRETCH
* ``True`` - REPEAT
Examples
--------
Set up a brush with a texture.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> from pyvista import examples
>>> chart = pv.Chart2D()
>>> plot = chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])
>>> plot.brush.texture = examples.download_puppy_texture()
>>> chart.show()
Enable texture repeat.
>>> plot.brush.texture_repeat = True
>>> chart.show()
"""
return self._repeat
@texture_repeat.setter
def texture_repeat(self, val): # numpydoc ignore=GL08
self._repeat = bool(val)
self._update_textureprops()
def _update_textureprops(self):
# Interpolation: NEAREST = 0x01, LINEAR = 0x02
# Stretch/repeat: STRETCH = 0x04, REPEAT = 0x08
self.SetTextureProperties(1 + int(self._interpolate) + 4 * (1 + int(self._repeat)))
class Axis(_vtkWrapper, _vtk.vtkAxis):
"""Pythonic interface for a VTK Axis, used by 2D charts.
Parameters
----------
label : str, default: ""
Axis label.
range : sequence[float], optional
Axis range, denoting the minimum and maximum values
displayed on this axis. Setting this to any valid value
other than ``None`` will change this axis behavior to
``'fixed'``. Setting it to ``None`` will change the axis
behavior to ``'auto'``.
grid : bool, default: True
Flag to toggle grid lines visibility for this axis.
Attributes
----------
pen : Pen
Pen used to draw the axis.
grid_pen : Pen
Pen used to draw the grid lines.
"""
BEHAVIORS: ClassVar[dict[str, int]] = {"auto": _vtk.vtkAxis.AUTO, "fixed": _vtk.vtkAxis.FIXED}
def __init__(self, label="", range=None, grid=True): # noqa: A002
"""Initialize a new Axis instance."""
super().__init__()
self._tick_locs = _vtk.vtkDoubleArray()
self._tick_labels = _vtk.vtkStringArray()
if vtk_version_info < (9, 2, 0): # pragma: no cover
# SetPen and SetGridPen methods are not available for older VTK versions,
# so fallback to using wrapper objects.
self.pen = Pen(color=(0, 0, 0), _wrap=self.GetPen())
self.grid_pen = Pen(color=(0.95, 0.95, 0.95), _wrap=self.GetGridPen())
else:
self.pen = Pen(color=(0, 0, 0))
self.grid_pen = Pen(color=(0.95, 0.95, 0.95))
self.SetPen(self.pen)
self.SetGridPen(self.grid_pen)
self.label = label
self._behavior = None # Will be set by specifying the range below
self.range = range
self.grid = grid
@property
def label(self): # numpydoc ignore=RT01
"""Return or set the axis label.
Examples
--------
Set the axis label to ``"Axis Label"``.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.label = "Axis Label"
>>> chart.show()
"""
return self.GetTitle()
@label.setter
def label(self, val): # numpydoc ignore=GL08
self.SetTitle(val)
@property
def label_visible(self): # numpydoc ignore=RT01
"""Return or set the axis label's visibility.
Examples
--------
Hide the x-axis label of a 2D chart.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.label_visible = False
>>> chart.show()
"""
return self.GetTitleVisible()
@label_visible.setter
def label_visible(self, val): # numpydoc ignore=GL08
self.SetTitleVisible(bool(val))
@property
def label_size(self): # numpydoc ignore=RT01
"""Return or set the size of the axis label font.
Examples
--------
Set the x-axis label font size of a 2D chart to 20.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.label_size = 20
>>> chart.x_axis.label_size
20
>>> chart.show()
"""
return self.GetTitleProperties().GetFontSize()
@label_size.setter
def label_size(self, size): # numpydoc ignore=GL08
self.GetTitleProperties().SetFontSize(size)
@property
def range(self): # numpydoc ignore=RT01
"""Return or set the axis range.
This will automatically set the axis behavior to ``"fixed"``
when a valid range is given. Setting the range to ``None``
will set the axis behavior to ``"auto"``.
Examples
--------
Manually specify the x-axis range of a 2D chart.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.range = [0, 5]
>>> chart.show()
Revert to automatic axis scaling.
>>> chart.x_axis.range = None
>>> chart.show()
"""
r = [0.0, 0.0]
self.GetRange(r)
return r
@range.setter
def range(self, val): # numpydoc ignore=GL08
if val is None:
self.behavior = "auto"
else:
self.behavior = "fixed"
self.SetRange(*val)
@property
def behavior(self): # numpydoc ignore=RT01
"""Set the axis' scaling behavior.
Allowed behaviors are ``'auto'`` to automatically rescale the
axis to fit all visible datapoints in the plot, or ``'fixed'``
to use the user defined range.
Examples
--------
Manually specify the x-axis range of a 2D chart.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.range = [0, 5]
>>> chart.show()
Revert to automatic axis scaling.
>>> chart.x_axis.behavior = "auto"
>>> chart.show()
>>> chart.x_axis.range
[0.0, 2.0]
"""
return self._behavior
@behavior.setter
def behavior(self, val): # numpydoc ignore=GL08
try:
self.SetBehavior(self.BEHAVIORS[val])
self._behavior = val
except KeyError:
formatted_behaviors = "\", \"".join(self.BEHAVIORS.keys())
raise ValueError(f"Invalid behavior. Allowed behaviors: \"{formatted_behaviors}\"")
@property
def margin(self): # numpydoc ignore=RT01
"""Return or set the axis margin.
Examples
--------
Create a 2D chart.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> chart.background_color = 'c'
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.show()
Manually specify a larger (bottom) margin for the x-axis and a
larger (left) margin for the y-axis.
>>> chart.x_axis.margin = 50
>>> chart.y_axis.margin = 50
>>> chart.show()
"""
return self.GetMargins()[0]
@margin.setter
def margin(self, val): # numpydoc ignore=GL08
# Second margin doesn't seem to have any effect? So we only expose the first entry as 'the margin'.
m = self.GetMargins()
self.SetMargins(val, m[1])
@property
def log_scale(self): # numpydoc ignore=RT01
"""Flag denoting whether a log scale is used for this axis.
Note that setting this property to ``True`` will not guarantee
that the log scale will be enabled. Verify whether activating
the log scale succeeded by rereading this property.
Examples
--------
Create a 2D chart.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2, 3, 4], [1e0, 1e1, 1e2, 1e3, 1e4])
>>> chart.show()
Try to enable the log scale on the y-axis.
>>> chart.y_axis.log_scale = True
>>> chart.show()
>>> chart.y_axis.log_scale
True
"""
return self.GetLogScaleActive()
@log_scale.setter
def log_scale(self, val): # numpydoc ignore=GL08
# False: log_scale will be disabled, True: axis will attempt to activate log_scale if possible
self.SetLogScale(bool(val))
@property
def grid(self): # numpydoc ignore=RT01
"""Return or set the axis' grid line visibility.
Examples
--------
Create a 2D chart with grid lines disabled for the x-axis.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.grid = False
>>> chart.show()
"""
return self.GetGridVisible()
@grid.setter
def grid(self, val): # numpydoc ignore=GL08
self.SetGridVisible(bool(val))
@property
def visible(self): # numpydoc ignore=RT01
"""Return or set the axis' visibility.
Examples
--------
Create a 2D chart with no visible y-axis.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.y_axis.visible = False
>>> chart.show()
"""
return self.GetAxisVisible()
@visible.setter
def visible(self, val): # numpydoc ignore=GL08
self.SetAxisVisible(bool(val))
def toggle(self):
"""Toggle the axis' visibility.
Examples
--------
Create a 2D chart.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.show()
Toggle the visibility of the y-axis.
>>> chart.y_axis.toggle()
>>> chart.show()
"""
self.visible = not self.visible
# --- Ticks ---
@property
def tick_count(self): # numpydoc ignore=RT01
"""Return or set the number of ticks drawn on this axis.
Setting this property to a negative value or ``None`` will
automatically determine the appropriate amount of ticks to
draw.
Examples
--------
Create a 2D chart with a reduced number of ticks on the x-axis.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.tick_count = 5
>>> chart.show()
Revert back to automatic tick behavior.
>>> chart.x_axis.tick_count = None
>>> chart.show()
"""
return self.GetNumberOfTicks()
@tick_count.setter
def tick_count(self, val): # numpydoc ignore=GL08
if val is None or val < 0:
val = -1
self.SetNumberOfTicks(int(val))
@property
def tick_locations(self): # numpydoc ignore=RT01
"""Return or set the tick locations for this axis.
Setting this to ``None`` will revert back to the default,
automatically determined, tick locations.
Examples
--------
Create a 2D chart with custom tick locations and labels on the y-axis.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.y_axis.tick_locations = (0.2, 0.4, 0.6, 1, 1.5, 2, 3)
>>> chart.y_axis.tick_labels = ["Very small", "Small", "Still small",
... "Small?", "Not large", "Large?",
... "Very large"]
>>> chart.show()
Revert back to automatic tick placement.
>>> chart.y_axis.tick_locations = None
>>> chart.y_axis.tick_labels = None
>>> chart.show()
"""
positions = self.GetTickPositions()
return tuple(positions.GetValue(i) for i in range(positions.GetNumberOfValues()))
@tick_locations.setter
def tick_locations(self, val): # numpydoc ignore=GL08
self._tick_locs.Reset()
if val is not None:
for loc in val:
self._tick_locs.InsertNextValue(loc)
self._update_ticks()
@property
def tick_labels(self): # numpydoc ignore=RT01
"""Return or set the tick labels for this axis.
You can specify a sequence, to provide a unique label to every
tick position; a string, to describe the label format to use
for each label; or ``None``, which will revert back to the
default tick labels. A label format is a string consisting of
an integer part, denoting the precision to use, and a final
character, denoting the notation to use.
Allowed notations:
* ``"f"`` for fixed notation
* ``"e"`` for scientific notation.
Examples
--------
Create a 2D chart with custom tick locations and labels on the y-axis.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.y_axis.tick_locations = (0.2, 0.4, 0.6, 1, 1.5, 2, 3)
>>> chart.y_axis.tick_labels = ["Very small", "Small", "Still small",
... "Small?", "Not large", "Large?",
... "Very large"]
>>> chart.show()
Revert back to automatic tick placement.
>>> chart.y_axis.tick_locations = None
>>> chart.y_axis.tick_labels = None
>>> chart.show()
Specify a custom label format to use (fixed notation with precision 2).
>>> chart.y_axis.tick_labels = "2f"
>>> chart.show()
"""
labels = self.GetTickLabels()
return tuple(labels.GetValue(i) for i in range(labels.GetNumberOfValues()))
@tick_labels.setter
def tick_labels(self, val): # numpydoc ignore=GL08
self._tick_labels.Reset()
self.SetNotation(_vtk.vtkAxis.STANDARD_NOTATION)
if isinstance(val, str):
precision = int(val[:-1])
notation = val[-1].lower()
if notation == "f":
self.SetNotation(_vtk.vtkAxis.FIXED_NOTATION)
self.SetPrecision(precision)
elif notation == "e":
self.SetNotation(_vtk.vtkAxis.SCIENTIFIC_NOTATION)
self.SetPrecision(precision)
elif isinstance(val, Sequence):
for label in val:
self._tick_labels.InsertNextValue(label)
self._update_ticks()
@property
def tick_label_size(self): # numpydoc ignore=RT01
"""Return or set the size of the axis tick label font.
Examples
--------
Set the x-axis tick label font size of a 2D chart to 20.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.tick_label_size = 20
>>> chart.x_axis.tick_label_size
20
>>> chart.show()
"""
return self.GetLabelProperties().GetFontSize()
@tick_label_size.setter
def tick_label_size(self, size): # numpydoc ignore=GL08
self.GetLabelProperties().SetFontSize(size)
@property
def tick_size(self): # numpydoc ignore=RT01
"""Return or set the size of this axis' ticks.
Examples
--------
Create a 2D chart with an x-axis with an increased tick size
and adjusted offset for the tick labels.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.tick_size += 10
>>> chart.x_axis.tick_labels_offset += 12
>>> chart.show()
"""
return self.GetTickLength()
@tick_size.setter
def tick_size(self, val): # numpydoc ignore=GL08
self.SetTickLength(val)
@property
def tick_labels_offset(self): # numpydoc ignore=RT01
"""Return or set the offset of the tick labels for this axis.
Examples
--------
Create a 2D chart with an x-axis with an increased tick size
and adjusted offset for the tick labels.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.tick_size += 10
>>> chart.x_axis.tick_labels_offset += 12
>>> chart.show()
"""
return self.GetLabelOffset()
@tick_labels_offset.setter
def tick_labels_offset(self, val): # numpydoc ignore=GL08
self.SetLabelOffset(float(val))
@property
def tick_labels_visible(self): # numpydoc ignore=RT01
"""Return or set the tick label visibility for this axis.
Examples
--------
Create a 2D chart with hidden tick labels on the y-axis.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.y_axis.tick_labels_visible = False
>>> chart.show()
"""
return self.GetLabelsVisible()
@tick_labels_visible.setter
def tick_labels_visible(self, val): # numpydoc ignore=GL08
self.SetLabelsVisible(bool(val))
self.SetRangeLabelsVisible(bool(val))
@property
def ticks_visible(self): # numpydoc ignore=RT01
"""Return or set the tick visibility for this axis.
Examples
--------
Create a 2D chart with hidden ticks on the y-axis.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.y_axis.ticks_visible = False
>>> chart.show()
"""
return self.GetTicksVisible()
@ticks_visible.setter
def ticks_visible(self, val): # numpydoc ignore=GL08
self.SetTicksVisible(bool(val))
def _update_ticks(self):
locs = None if self._tick_locs.GetNumberOfValues() == 0 else self._tick_locs
labels = None if self._tick_labels.GetNumberOfValues() == 0 else self._tick_labels
self.SetCustomTickPositions(locs, labels)
class _CustomContextItem(_vtk.vtkPythonItem):
class ItemWrapper:
def Initialize(self, item):
# item is the _CustomContextItem subclass instance
return True
def Paint(self, item, painter):
# item is the _CustomContextItem subclass instance
return item.paint(painter)
def __init__(self):
super().__init__()
# This will also call ItemWrapper.Initialize
self.SetPythonObject(_CustomContextItem.ItemWrapper())
def paint(self, painter):
return True
class _ChartBackground(_CustomContextItem):
"""Utility class for chart backgrounds."""
def __init__(self, chart):
super().__init__()
# Note: This SHOULD be a weakref proxy, as otherwise the garbage collector will not clean up unused charts
# (because of the cyclic references between charts and their background).
self._chart = weakref.proxy(chart) # Weakref proxy to the chart to draw the background for
# Default background is translucent with black border line
self.BorderPen = Pen(color=(0, 0, 0))
self.BackgroundBrush = Brush(color=(0, 0, 0, 0))
# Default active background is slightly more opaque with yellow border line
self.ActiveBorderPen = Pen(color=(0.8, 0.8, 0.2))
self.ActiveBackgroundBrush = Brush(color=(1.0, 1.0, 1.0, 0.4))
def paint(self, painter):
if self._chart.visible:
painter.ApplyPen(self.ActiveBorderPen if self._chart._interactive else self.BorderPen)
painter.ApplyBrush(
self.ActiveBackgroundBrush if self._chart._interactive else self.BackgroundBrush,
)
l, b, w, h = self._chart._geometry
painter.DrawRect(l, b, w, h)
if vtk_version_info < (9, 2, 0): # pragma: no cover
# Following 'patch' is necessary for earlier VTK versions. Otherwise Pie plots will use the same opacity
# as the chart's background when their legend is hidden. As the default background is transparent,
# this will cause Pie charts to completely disappear.
painter.GetBrush().SetOpacity(255)
painter.GetBrush().SetTexture(None)
return True
class _Chart(DocSubs):
"""Common pythonic interface for vtkChart, vtkChartBox, vtkChartPie and ChartMPL instances."""
# Subclasses should specify following substitutions: 'chart_name', 'chart_args', 'chart_init' and 'chart_set_labels'.
_DOC_SUBS: dict[str, str] | None = None
def __init__(self, size=(1, 1), loc=(0, 0)):
super().__init__()
self._background = _ChartBackground(self)
self._x_axis = Axis()
self._y_axis = Axis()
if size is not None:
self.size = size
if loc is not None:
self.loc = loc
@property
def _scene(self):
"""Get a reference to the vtkScene in which this chart is drawn."""
return self.GetScene()
@property
def _renderer(self):
"""Get a reference to the vtkRenderer in which this chart is drawn."""
return self._scene.GetRenderer() if self._scene is not None else None
def _render_event(self, *args, plotter_render=False, **kwargs):
"""Update the chart right before it will be rendered."""
# Only resize on real VTK render events (plotter.render calls will afterwards invoke a proper render event)
if not plotter_render:
self._resize()
def _resize(self):
"""Resize this chart.
Resize this chart such that it always occupies the specified
geometry (matching the specified location and size).
Returns
-------
bool
``True`` if the chart was resized, ``False`` otherwise.
"""
# edge race case
if self._renderer is None: # pragma: no cover
return None
r_w, r_h = self._renderer.GetSize()
# Alternatively: self.scene.GetViewWidth(), self.scene.GetViewHeight()
_, _, c_w, c_h = (int(g) for g in self._geometry)
# Target size is calculated from specified normalized width and height and the renderer's current size
t_w = int(self._size[0] * r_w)
t_h = int(self._size[1] * r_h)
resize = c_w != t_w or c_h != t_h
if resize:
# Mismatch between current size and target size, so resize chart:
self._geometry = (int(self._loc[0] * r_w), int(self._loc[1] * r_h), t_w, t_h)
return resize
@property
def _geometry(self):
"""Chart geometry (x and y position of bottom left corner and width and height in pixels)."""
return tuple(self.GetSize())
@_geometry.setter
def _geometry(self, val):
"""Set the chart geometry."""
self.SetSize(_vtk.vtkRectf(*val))
@property
def _interactive(self):
"""Return or set the chart's interactivity.
Notes
-----
Users should not set this property directly, but use the
:func:`Renderer.set_chart_interaction` method instead.
"""
return self.GetInteractive()
@_interactive.setter
def _interactive(self, val):
self.SetInteractive(val)
def _is_within(self, pos):
"""Check whether the specified position (in pixels) lies within this chart's geometry."""
l, b, w, h = self._geometry
return l <= pos[0] <= l + w and b <= pos[1] <= b + h
@property
@doc_subs
def size(self): # numpydoc ignore=RT01
"""Return or set the chart size in normalized coordinates.
A size of ``(1, 1)`` occupies the whole renderer.
Examples
--------
Create a half-sized {chart_name} centered in the middle of the
renderer.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.size = (0.5, 0.5)
>>> chart.loc = (0.25, 0.25)
>>> chart.show()
"""
return self._size
@size.setter
def size(self, val): # numpydoc ignore=GL08
if not (len(val) == 2 and 0 <= val[0] <= 1 and 0 <= val[1] <= 1):
raise ValueError(f'Invalid size {val}.')
self._size = val
@property
@doc_subs
def loc(self): # numpydoc ignore=RT01
"""Return or set the chart position in normalized coordinates.
This denotes the location of the chart's bottom left corner.
Examples
--------
Create a half-sized {chart_name} centered in the middle of the
renderer.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.size = (0.5, 0.5)
>>> chart.loc = (0.25, 0.25)
>>> chart.show()
"""
return self._loc
@loc.setter
def loc(self, val): # numpydoc ignore=GL08
if not (len(val) == 2 and 0 <= val[0] <= 1 and 0 <= val[1] <= 1):
raise ValueError(f'Invalid loc {val}.')
self._loc = val
@property
@doc_subs
def border_color(self): # numpydoc ignore=RT01
"""Return or set the chart's border color.
Examples
--------
Create a {chart_name} with a thick, dashed red border.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.border_color = 'r'
>>> chart.border_width = 5
>>> chart.border_style = '--'
>>> chart.show(interactive=False)
"""
return self._background.BorderPen.color
@border_color.setter
def border_color(self, val): # numpydoc ignore=GL08
self._background.BorderPen.color = val
@property
@doc_subs
def border_width(self): # numpydoc ignore=RT01
"""Return or set the chart's border width.
Examples
--------
Create a {chart_name} with a thick, dashed red border.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.border_color = 'r'
>>> chart.border_width = 5
>>> chart.border_style = '--'
>>> chart.show(interactive=False)
"""
return self._background.BorderPen.width
@border_width.setter
def border_width(self, val): # numpydoc ignore=GL08
self._background.BorderPen.width = val
self._background.ActiveBorderPen.width = val
@property
@doc_subs
def border_style(self): # numpydoc ignore=RT01
"""Return or set the chart's border style.
Examples
--------
Create a {chart_name} with a thick, dashed red border.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.border_color = 'r'
>>> chart.border_width = 5
>>> chart.border_style = '--'
>>> chart.show(interactive=False)
"""
return self._background.BorderPen.style
@border_style.setter
def border_style(self, val): # numpydoc ignore=GL08
self._background.BorderPen.style = val
self._background.ActiveBorderPen.style = val
@property
@doc_subs
def active_border_color(self): # numpydoc ignore=RT01
"""Return or set the chart's border color in interactive mode.
Examples
--------
Create a {chart_name} with a thick, dashed red border.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.border_color = 'r'
>>> chart.border_width = 5
>>> chart.border_style = '--'
>>> chart.show(interactive=False)
Set the active border color to yellow and activate the chart.
>>> chart.active_border_color = 'y'
>>> chart.show(interactive=True)
"""
return self._background.ActiveBorderPen.color
@active_border_color.setter
def active_border_color(self, val): # numpydoc ignore=GL08
self._background.ActiveBorderPen.color = val
@property
@doc_subs
def background_color(self): # numpydoc ignore=RT01
"""Return or set the chart's background color.
Examples
--------
Create a {chart_name} with a green background.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.background_color = (0.5, 0.9, 0.5)
>>> chart.show(interactive=False)
"""
return self._background.BackgroundBrush.color
@background_color.setter
def background_color(self, val): # numpydoc ignore=GL08
self._background.BackgroundBrush.color = val
@property
@doc_subs
def background_texture(self): # numpydoc ignore=RT01
"""Return or set the chart's background texture.
Examples
--------
Create a {chart_name} with an emoji as its background.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> from pyvista import examples
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.background_texture = examples.download_emoji_texture()
>>> chart.show(interactive=False)
"""
return self._background.BackgroundBrush.texture
@background_texture.setter
def background_texture(self, val): # numpydoc ignore=GL08
self._background.BackgroundBrush.texture = val
self._background.ActiveBackgroundBrush.texture = val
@property
@doc_subs
def active_background_color(self): # numpydoc ignore=RT01
"""Return or set the chart's background color in interactive mode.
Examples
--------
Create a {chart_name} with a green background.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.background_color = (0.5, 0.9, 0.5)
>>> chart.show(interactive=False)
Set the active background color to blue and activate the chart.
>>> chart.active_background_color = 'b'
>>> chart.show(interactive=True)
"""
return self._background.ActiveBackgroundBrush.color
@active_background_color.setter
def active_background_color(self, val): # numpydoc ignore=GL08
self._background.ActiveBackgroundBrush.color = val
@property
@doc_subs
def visible(self): # numpydoc ignore=RT01
"""Return or set the chart's visibility.
Examples
--------
Create a {chart_name}.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.show()
Hide it.
>>> chart.visible = False
>>> chart.show()
"""
return self.GetVisible()
@visible.setter
def visible(self, val): # numpydoc ignore=GL08
self.SetVisible(val)
@doc_subs
def toggle(self):
"""Toggle the chart's visibility.
Examples
--------
Create a {chart_name}.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.show()
Hide it.
>>> chart.toggle()
>>> chart.show()
"""
self.visible = not self.visible
@property
@doc_subs
def title(self): # numpydoc ignore=RT01
"""Return or set the chart's title.
Examples
--------
Create a {chart_name} with title 'My Chart'.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.title = 'My Chart'
>>> chart.show()
"""
return self.GetTitle()
@title.setter
def title(self, val): # numpydoc ignore=GL08
self.SetTitle(val)
@property
@doc_subs
def legend_visible(self): # numpydoc ignore=RT01
"""Return or set the visibility of the chart's legend.
Examples
--------
Create a {chart_name} with custom labels.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> {chart_set_labels}
>>> chart.show()
Hide the legend.
>>> chart.legend_visible = False
>>> chart.show()
"""
return self.GetShowLegend()
@legend_visible.setter
def legend_visible(self, val): # numpydoc ignore=GL08
self.SetShowLegend(val)
@doc_subs
def show(
self,
interactive=True,
off_screen=None,
full_screen=None,
screenshot=None,
window_size=None,
notebook=None,
background='w',
dev_kwargs=None,
):
"""Show this chart in a self contained plotter.
Parameters
----------
interactive : bool, default: True
Enable interaction with the chart. Interaction is not enabled
when plotting off screen.
off_screen : bool, optional
Plots off screen when ``True``. Helpful for saving screenshots
without a window popping up. Defaults to active theme setting.
full_screen : bool, optional
Opens window in full screen. When enabled, ignores
``window_size``. Defaults to active theme setting.
screenshot : str | bool, default: False
Saves screenshot to file when enabled. See:
:func:`Plotter.screenshot() <pyvista.Plotter.screenshot>`.
When ``True``, takes screenshot and returns ``numpy`` array of
image.
window_size : list, optional
Window size in pixels. Defaults to active theme setting.
notebook : bool, optional
When ``True``, the resulting plot is placed inline a
jupyter notebook. Assumes a jupyter console is active.
background : ColorLike, default: "w"
Use to make the entire mesh have a single solid color.
Either a string, RGB list, or hex color string. For example:
``color='white'``, ``color='w'``, ``color=[1.0, 1.0, 1.0]``, or
``color='#FFFFFF'``.
dev_kwargs : dict, optional
Optional developer keyword arguments.
Returns
-------
np.ndarray
Numpy array of the last image when ``screenshot=True``
is set. Optionally contains alpha values. Sized:
* [Window height x Window width x 3] if the theme sets
``transparent_background=False``.
* [Window height x Window width x 4] if the theme sets
``transparent_background=True``.
Examples
--------
Create a simple {chart_name} and show it.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.{cls}({chart_args}){chart_init}
>>> chart.show()
"""
if dev_kwargs is None:
dev_kwargs = {}
if off_screen is None:
off_screen = pyvista.OFF_SCREEN
pl = pyvista.Plotter(window_size=window_size, notebook=notebook, off_screen=off_screen)
pl.background_color = background
pl.add_chart(self)
if interactive and (not off_screen or pyvista.BUILDING_GALLERY): # pragma: no cover
pl.set_chart_interaction(self)
return pl.show(
screenshot=screenshot,
full_screen=full_screen,
**dev_kwargs,
)
class _Plot(DocSubs):
"""Common pythonic interface for vtkPlot and vtkPlot3D instances."""
# Subclasses should specify following substitutions: 'plot_name', 'chart_init' and 'plot_init'.
_DOC_SUBS: dict[str, str] | None = None
def __init__(self, chart):
super().__init__()
self._chart = weakref.proxy(chart)
self._pen = Pen()
self._brush = Brush()
self._label = ""
if hasattr(self, "SetPen"):
self.SetPen(self._pen)
if hasattr(self, "SetBrush"):
self.SetBrush(self._brush)
@property
@doc_subs
def color(self): # numpydoc ignore=RT01
"""Return or set the plot's color.
This is the color used by the plot's pen and brush to draw lines and shapes.
Examples
--------
Set the {plot_name}'s color to red.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {chart_init}
>>> plot = {plot_init}
>>> plot.color = 'r'
>>> chart.show()
"""
return self.pen.color
@color.setter
def color(self, val): # numpydoc ignore=GL08
self.pen.color = val
self.brush.color = val
@property
@doc_subs
def pen(self): # numpydoc ignore=RT01
"""Pen object controlling how lines in this plot are drawn.
Returns
-------
Pen
Pen object controlling how lines in this plot are drawn.
Examples
--------
Increase the line width of the {plot_name}'s pen object.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {chart_init}
>>> plot = {plot_init}
>>> plot.line_style = '-' # Make sure all lines are visible
>>> plot.pen.width = 10
>>> chart.show()
"""
return self._pen
@property
@doc_subs
def brush(self): # numpydoc ignore=RT01
"""Brush object controlling how shapes in this plot are filled.
Returns
-------
Brush
Brush object controlling how shapes in this plot are filled.
Examples
--------
Use a custom texture for the {plot_name}'s brush object.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> from pyvista import examples
>>> chart = {chart_init}
>>> plot = {plot_init}
>>> plot.brush.texture = examples.download_puppy_texture()
>>> chart.show()
"""
return self._brush
@property
@doc_subs
def line_width(self): # numpydoc ignore=RT01
"""Return or set the line width of all lines drawn in this plot.
This is equivalent to accessing/modifying the width of this plot's pen.
Examples
--------
Set the line width to 10
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {chart_init}
>>> plot = {plot_init}
>>> plot.line_style = '-' # Make sure all lines are visible
>>> plot.line_width = 10
>>> chart.show()
"""
return self.pen.width
@line_width.setter
def line_width(self, val): # numpydoc ignore=GL08
self.pen.width = val
@property
@doc_subs
def line_style(self): # numpydoc ignore=RT01
"""Return or set the line style of all lines drawn in this plot.
This is equivalent to accessing/modifying the style of this plot's pen.
Examples
--------
Set a custom line style.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {chart_init}
>>> plot = {plot_init}
>>> plot.line_style = '-.'
>>> chart.show()
"""
return self.pen.style
@line_style.setter
def line_style(self, val): # numpydoc ignore=GL08
self.pen.style = val
@property
@doc_subs
def label(self): # numpydoc ignore=RT01
"""Return or set the this plot's label, as shown in the chart's legend.
Examples
--------
Create a {plot_name} with custom label.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {chart_init}
>>> plot = {plot_init}
>>> plot.label = "My awesome plot"
>>> chart.show()
"""
return self._label
@label.setter
def label(self, val): # numpydoc ignore=GL08
self._label = "" if val is None else val
self.SetLabel(self._label)
@property
@doc_subs
def visible(self): # numpydoc ignore=RT01
"""Return or set the this plot's visibility.
Examples
--------
Create a {plot_name}.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {chart_init}
>>> plot = {plot_init}
>>> chart.show()
Hide it.
>>> plot.visible = False
>>> chart.show()
"""
return self.GetVisible()
@visible.setter
def visible(self, val): # numpydoc ignore=GL08
self.SetVisible(val)
@doc_subs
def toggle(self):
"""Toggle the plot's visibility.
Examples
--------
Create a {plot_name}.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {chart_init}
>>> plot = {plot_init}
>>> chart.show()
Hide it.
>>> plot.toggle()
>>> chart.show()
"""
self.visible = not self.visible
class _MultiCompPlot(_Plot):
"""Common pythonic interface for vtkPlot instances with multiple components.
Example subclasses are BoxPlot, PiePlot, BarPlot and StackPlot.
"""
DEFAULT_COLOR_SCHEME = "qual_accent"
# Subclasses should specify following substitutions: 'plot_name', 'chart_init', 'plot_init', 'multichart_init' and 'multiplot_init'.
_DOC_SUBS: dict[str, str] | None = None
def __init__(self, chart):
super().__init__(chart)
self._color_series = _vtk.vtkColorSeries()
self._lookup_table = self._color_series.CreateLookupTable(_vtk.vtkColorSeries.CATEGORICAL)
self._labels = _vtk.vtkStringArray()
self.SetLabels(self._labels)
self.color_scheme = self.DEFAULT_COLOR_SCHEME
@property
@doc_subs
def color_scheme(self): # numpydoc ignore=RT01
"""Return or set the plot's color scheme.
This scheme defines the colors of the different
components drawn by this plot.
See the table below for the available color
schemes.
Notes
-----
.. _plot_color_schemes:
Overview of all available color schemes.
.. include:: ../plot_color_schemes.rst
Examples
--------
Set the {plot_name}'s color scheme to warm.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {multichart_init}
>>> plot = {multiplot_init}
>>> plot.color_scheme = "warm"
>>> chart.show()
"""
return SCHEME_NAMES.get(self._color_series.GetColorScheme(), "custom")
@color_scheme.setter
def color_scheme(self, val): # numpydoc ignore=GL08
self._color_series.SetColorScheme(COLOR_SCHEMES.get(val, COLOR_SCHEMES["custom"])["id"])
self._color_series.BuildLookupTable(self._lookup_table, _vtk.vtkColorSeries.CATEGORICAL)
self.brush.color = self.colors[0]
@property
@doc_subs
def colors(self): # numpydoc ignore=RT01
"""Return or set the plot's colors.
These are the colors used for the different
components drawn by this plot.
Examples
--------
Set the {plot_name}'s colors manually.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {multichart_init}
>>> plot = {multiplot_init}
>>> plot.colors = ["b", "g", "r", "c"]
>>> chart.show()
"""
return [
Color(self._color_series.GetColor(i))
for i in range(self._color_series.GetNumberOfColors())
]
@colors.setter
def colors(self, val): # numpydoc ignore=GL08
if val is None:
self.color_scheme = self.DEFAULT_COLOR_SCHEME
# Setting color_scheme already sets brush.color
elif isinstance(val, str):
self.color_scheme = val
# Setting color_scheme already sets brush.color
else:
try:
self._color_series.SetNumberOfColors(len(val))
for i, color in enumerate(val):
self._color_series.SetColor(i, Color(color).vtk_c3ub)
self._color_series.BuildLookupTable(
self._lookup_table,
_vtk.vtkColorSeries.CATEGORICAL,
)
self.brush.color = self.colors[0] # Synchronize "color" and "colors" properties
except ValueError as e:
self.color_scheme = self.DEFAULT_COLOR_SCHEME
raise ValueError(
"Invalid colors specified, falling back to default color scheme.",
) from e
@property
@doc_subs
def color(self): # numpydoc ignore=RT01
"""Return or set the plot's color.
This is the color used by the plot's brush
to draw the different components.
Examples
--------
Set the {plot_name}'s color to red.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {chart_init}
>>> plot = {plot_init}
>>> plot.color = 'r'
>>> chart.show()
"""
return self.brush.color
@color.setter
def color(self, val): # numpydoc ignore=GL08
# Override default _Plot behaviour. This makes sure the plot's "color_scheme", "colors" and "color" properties
# (and their internal representations through color series, lookup tables and brushes) stay synchronized.
self.colors = [val]
@property
@doc_subs
def labels(self): # numpydoc ignore=RT01
"""Return or set the this plot's labels, as shown in the chart's legend.
Examples
--------
Create a {plot_name}.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = {multichart_init}
>>> plot = {multiplot_init}
>>> chart.show()
Modify the labels.
>>> plot.labels = ["A", "B", "C", "D"]
>>> chart.show()
"""
return [self._labels.GetValue(i) for i in range(self._labels.GetNumberOfValues())]
@labels.setter
def labels(self, val): # numpydoc ignore=GL08
self._labels.Reset()
if isinstance(val, str):
val = [val]
try:
if val is not None:
for label in val:
self._labels.InsertNextValue(label)
except TypeError:
raise ValueError("Invalid labels specified.")
@property
@doc_subs
def label(self): # numpydoc ignore=RT01
"""Return or set the this plot's label, as shown in the chart's legend.
Examples
--------
Create a {plot_name} with custom label.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> chart = {chart_init}
>>> plot = {plot_init}
>>> chart.show()
Modify the label.
>>> plot.label = "My awesome plot"
>>> chart.show()
"""
return self.labels[0] if self._labels.GetNumberOfValues() > 0 else ""
@label.setter
def label(self, val): # numpydoc ignore=GL08
# Override default _Plot behaviour. This makes sure the plot's "labels" and "label" properties (and their
# internal representations) stay synchronized.
self.labels = None if val is None else [val]
class LinePlot2D(_Plot, _vtk.vtkPlotLine):
"""Class representing a 2D line plot.
Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.
Parameters
----------
chart : Chart2D
The chart containing this plot.
x : array_like
X coordinates of the points through which a line should be drawn.
y : array_like
Y coordinates of the points through which a line should be drawn.
color : ColorLike, default: "b"
Color of the line drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed.
width : float, default: 1
Width of the line drawn in this plot.
style : str, default: "-"
Style of the line drawn in this plot. See :ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of allowed line
styles.
label : str, default: ""
Label of this plot, as shown in the chart's legend.
Examples
--------
Create a 2D chart plotting an approximate satellite
trajectory.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> from pyvista import examples
>>> import numpy as np
>>> chart = pv.Chart2D()
>>> x = np.linspace(0, 1, 100)
>>> y = np.sin(6.5*x-1)
>>> _ = chart.line(x, y, "y", 4)
>>> chart.background_texture = examples.load_globe_texture()
>>> chart.hide_axes()
>>> chart.show()
"""
_DOC_SUBS = { # noqa: RUF012
"plot_name": "2D line plot",
"chart_init": "pv.Chart2D()",
"plot_init": "chart.line([0, 1, 2], [2, 1, 3])",
}
def __init__(
self,
chart,
x,
y,
color="b",
width=1.0,
style="-",
label="",
): # numpydoc ignore=PR01,RT01
"""Initialize a new 2D line plot instance."""
super().__init__(chart)
self._table = pyvista.Table({"x": np.empty(0, np.float32), "y": np.empty(0, np.float32)})
self.SetInputData(self._table, "x", "y")
self.update(x, y)
self.color = color
self.line_width = width
self.line_style = style
self.label = label
@property
def x(self): # numpydoc ignore=RT01
"""Retrieve the X coordinates of the points through which a line is drawn.
Examples
--------
Create a line plot and display the x coordinates.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.line([0, 1, 2], [2, 1, 3])
>>> plot.x
pyvista_ndarray([0, 1, 2])
>>> chart.show()
"""
return self._table["x"]
@property
def y(self): # numpydoc ignore=RT01
"""Retrieve the Y coordinates of the points through which a line is drawn.
Examples
--------
Create a line plot and display the y coordinates.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.line([0, 1, 2], [2, 1, 3])
>>> plot.y
pyvista_ndarray([2, 1, 3])
>>> chart.show()
"""
return self._table["y"]
def update(self, x, y):
"""Update this plot's points, through which a line is drawn.
Parameters
----------
x : array_like
The new x coordinates of the points through which a line should be drawn.
y : array_like
The new y coordinates of the points through which a line should be drawn.
Examples
--------
Create a line plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.show()
Update the line's y coordinates.
>>> plot.update([0, 1, 2], [3, 1, 2])
>>> chart.show()
"""
if len(x) > 1:
self._table.update({"x": np.asarray(x), "y": np.asarray(y)})
self.visible = True
else:
# Turn off visibility for fewer than 2 points as otherwise an error message is shown
self.visible = False
class ScatterPlot2D(_Plot, _vtk.vtkPlotPoints):
"""Class representing a 2D scatter plot.
Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.
Parameters
----------
chart : Chart2D
The chart containing this plot.
x : array_like
X coordinates of the points to draw.
y : array_like
Y coordinates of the points to draw.
color : ColorLike, default: "b"
Color of the points drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed.
size : float, default: 10
Size of the point markers drawn in this plot.
style : str, default: "o"
Style of the point markers drawn in this plot. See :ref:`ScatterPlot2D.MARKER_STYLES <scatter_marker_styles>`
for a list of allowed marker styles.
label : str, default: ""
Label of this plot, as shown in the chart's legend.
Notes
-----
.. _scatter_marker_styles:
MARKER_STYLES : dict
Dictionary containing all allowed marker styles as its keys.
.. include:: ../scatter_marker_styles.rst
Examples
--------
Plot a simple sine wave as a scatter plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> x = np.linspace(0, 2*np.pi, 20)
>>> y = np.sin(x)
>>> chart = pv.Chart2D()
>>> _ = chart.scatter(x, y)
>>> chart.show()
"""
MARKER_STYLES: ClassVar[
dict[str, dict[str, int | str]]
] = { # descr is used in the documentation, set to None to hide it from the docs.
"": {"id": _vtk.vtkPlotPoints.NONE, "descr": "Hidden"},
"x": {"id": _vtk.vtkPlotPoints.CROSS, "descr": "Cross"},
"+": {"id": _vtk.vtkPlotPoints.PLUS, "descr": "Plus"},
"s": {"id": _vtk.vtkPlotPoints.SQUARE, "descr": "Square"},
"o": {"id": _vtk.vtkPlotPoints.CIRCLE, "descr": "Circle"},
"d": {"id": _vtk.vtkPlotPoints.DIAMOND, "descr": "Diamond"},
}
_DOC_SUBS = { # noqa: RUF012
"plot_name": "2D scatter plot",
"chart_init": "pv.Chart2D()",
"plot_init": "chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])",
}
def __init__(
self,
chart,
x,
y,
color="b",
size=10,
style="o",
label="",
): # numpydoc ignore=PR01,RT01
"""Initialize a new 2D scatter plot instance."""
super().__init__(chart)
self._table = pyvista.Table({"x": np.empty(0, np.float32), "y": np.empty(0, np.float32)})
self.SetInputData(self._table, "x", "y")
self.update(x, y)
self.color = color
self.marker_size = size
self.marker_style = style
self.label = label
@property
def x(self): # numpydoc ignore=RT01
"""Retrieve the X coordinates of this plot's points.
Examples
--------
Create a scatter plot and display the x coordinates.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
>>> plot.x
pyvista_ndarray([0, 1, 2, 3, 4])
>>> chart.show()
"""
return self._table["x"]
@property
def y(self): # numpydoc ignore=RT01
"""Retrieve the Y coordinates of this plot's points.
Examples
--------
Create a scatter plot and display the y coordinates.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
>>> plot.y
pyvista_ndarray([2, 1, 3, 4, 2])
>>> chart.show()
"""
return self._table["y"]
def update(self, x, y):
"""Update this plot's points.
Parameters
----------
x : array_like
The new x coordinates of the points to draw.
y : array_like
The new y coordinates of the points to draw.
Examples
--------
Create a scatter plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
>>> chart.show()
Update the marker locations.
>>> plot.update([0, 1, 2, 3, 4], [3, 2, 4, 2, 1])
>>> chart.show()
"""
if len(x) > 0:
self._table.update({"x": np.asarray(x), "y": np.asarray(y)})
self.visible = True
else:
self.visible = False
@property
def marker_size(self): # numpydoc ignore=RT01
"""Return or set the plot's marker size.
Examples
--------
Create a 2D scatter plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
>>> chart.show()
Increase the marker size.
>>> plot.marker_size = 30
>>> chart.show()
"""
return self.GetMarkerSize()
@marker_size.setter
def marker_size(self, val): # numpydoc ignore=GL08
self.SetMarkerSize(val)
@property
def marker_style(self): # numpydoc ignore=RT01
"""Return or set the plot's marker style.
Examples
--------
Create a 2D scatter plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.scatter([0, 1, 2, 3, 4], [2, 1, 3, 4, 2])
>>> chart.show()
Change the marker style.
>>> plot.marker_style = "d"
>>> chart.show()
"""
return self._marker_style
@marker_style.setter
def marker_style(self, val): # numpydoc ignore=GL08
if val is None:
val = ""
try:
self.SetMarkerStyle(self.MARKER_STYLES[val]["id"])
self._marker_style = val
except KeyError:
formatted_styles = "\", \"".join(self.MARKER_STYLES.keys())
raise ValueError(f"Invalid marker style. Allowed marker styles: \"{formatted_styles}\"")
class AreaPlot(_Plot, _vtk.vtkPlotArea):
"""Class representing a 2D area plot.
Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.
Parameters
----------
chart : Chart2D
The chart containing this plot.
x : array_like
X coordinates of the points outlining the area to draw.
y1 : array_like
Y coordinates of the points on the first outline of the area to draw.
y2 : array_like, optional
Y coordinates of the points on the second outline of the area to
draw. Defaults to ``numpy.zeros_like(x)``.
color : ColorLike, default: "b"
Color of the area drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed.
label : str, default: ""
Label of this plot, as shown in the chart's legend.
Examples
--------
Create an area plot showing the minimum and maximum precipitation observed in each month.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> x = np.arange(12)
>>> p_min = [11, 0, 16, 2, 23, 18, 25, 17, 9, 12, 14, 21]
>>> p_max = [87, 64, 92, 73, 91, 94, 107, 101, 84, 88, 95, 103]
>>> chart = pv.Chart2D()
>>> _ = chart.area(x, p_min, p_max)
>>> chart.x_axis.tick_locations = x
>>> chart.x_axis.tick_labels = ["Jan", "Feb", "Mar", "Apr", "May",
... "Jun", "Jul", "Aug", "Sep", "Oct",
... "Nov", "Dec"]
>>> chart.x_axis.label = "Month"
>>> chart.y_axis.label = "Precipitation [mm]"
>>> chart.show()
"""
_DOC_SUBS = { # noqa: RUF012
"plot_name": "area plot",
"chart_init": "pv.Chart2D()",
"plot_init": "chart.area([0, 1, 2], [0, 0, 1], [1, 3, 2])",
}
def __init__(self, chart, x, y1, y2=None, color="b", label=""):
"""Initialize a new 2D area plot instance."""
super().__init__(chart)
self._table = pyvista.Table(
{
"x": np.empty(0, np.float32),
"y1": np.empty(0, np.float32),
"y2": np.empty(0, np.float32),
},
)
self.SetInputData(self._table)
self.SetInputArray(0, "x")
self.SetInputArray(1, "y1")
self.SetInputArray(2, "y2")
self.update(x, y1, y2)
self.color = color
self.label = label
@property
def x(self): # numpydoc ignore=RT01
"""Retrieve the X coordinates of the points outlining the drawn area.
Examples
--------
Create an area plot and display the x coordinates.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
>>> plot.x
pyvista_ndarray([0, 1, 2])
>>> chart.show()
"""
return self._table["x"]
@property
def y1(self): # numpydoc ignore=RT01
"""Retrieve the Y coordinates of the points on the first outline of the drawn area.
Examples
--------
Create an area plot and display the y1 coordinates.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
>>> plot.y1
pyvista_ndarray([2, 1, 3])
>>> chart.show()
"""
return self._table["y1"]
@property
def y2(self): # numpydoc ignore=RT01
"""Retrieve the Y coordinates of the points on the second outline of the drawn area.
Examples
--------
Create an area plot and display the y2 coordinates.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.area([0, 1, 2], [2, 1, 3], [1, 0, 1])
>>> plot.y2
pyvista_ndarray([1, 0, 1])
>>> chart.show()
"""
return self._table["y2"]
def update(self, x, y1, y2=None):
"""Update this plot's points, outlining the area to draw.
Parameters
----------
x : array_like
The new x coordinates of the points outlining the area.
y1 : array_like
The new y coordinates of the points on the first outline of the area.
y2 : array_like, optional
The new y coordinates of the points on the second outline of the
area. Default ``numpy.zeros_like(x)``.
Examples
--------
Create an area plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.area([0, 1, 2], [2, 1, 3])
>>> chart.show()
Update the points on the second outline of the area.
>>> plot.update([0, 1, 2], [2, 1, 3], [1, 0, 1])
>>> chart.show()
"""
if len(x) > 0:
if y2 is None:
y2 = np.zeros_like(x)
self._table.update(
{
"x": np.asarray(x),
"y1": np.asarray(y1),
"y2": np.asarray(y2),
},
)
self.visible = True
else:
self.visible = False
class BarPlot(_MultiCompPlot, _vtk.vtkPlotBar):
"""Class representing a 2D bar plot.
Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.
Parameters
----------
chart : Chart2D
The chart containing this plot.
x : array_like
Positions (along the x-axis for a vertical orientation, along the y-axis for
a horizontal orientation) of the bars to draw.
y : array_like
Size of the bars to draw. Multiple bars can be stacked by passing a sequence of sequences.
color : ColorLike, default: "b"
Color of the bars drawn in this plot. Any color parsable by :class:`pyvista.Color` is allowed.
orientation : str, default: "V"
Orientation of the bars drawn in this plot. Either ``"H"`` for an horizontal orientation or ``"V"`` for a
vertical orientation.
label : str, default: ""
Label of this plot, as shown in the chart's legend.
Examples
--------
Create a stacked bar chart showing the average time spent on activities
throughout the week.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> x = np.arange(1, 8)
>>> y_s = [7, 8, 7.5, 8, 7.5, 9, 10]
>>> y_h = [2, 3, 2, 2.5, 1.5, 4, 6.5]
>>> y_w = [8, 8, 7, 8, 7, 0, 0]
>>> y_r = [5, 2.5, 4.5, 3.5, 6, 9, 6.5]
>>> y_t = [2, 2.5, 3, 2, 2, 2, 1]
>>> labels = ["Sleep", "Household", "Work", "Relax", "Transport"]
>>> chart = pv.Chart2D()
>>> _ = chart.bar(x, [y_s, y_h, y_w, y_r, y_t], label=labels)
>>> chart.x_axis.tick_locations = x
>>> chart.x_axis.tick_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
>>> chart.x_label = "Day of week"
>>> chart.y_label = "Average time spent"
>>> chart.grid = False # Disable the grid lines
>>> chart.show()
"""
ORIENTATIONS: ClassVar[dict[str, int]] = {
"H": _vtk.vtkPlotBar.HORIZONTAL,
"V": _vtk.vtkPlotBar.VERTICAL,
}
_DOC_SUBS = { # noqa: RUF012
"plot_name": "bar plot",
"chart_init": "pv.Chart2D()",
"plot_init": "chart.bar([1, 2, 3], [2, 1, 3])",
"multichart_init": "pv.Chart2D()",
"multiplot_init": "chart.bar([1, 2, 3], [[2, 1, 3], [1, 0, 2], [0, 3, 1], [3, 2, 0]])",
}
def __init__(
self,
chart,
x,
y,
color=None,
orientation="V",
label=None,
): # numpydoc ignore=PR01,RT01
"""Initialize a new 2D bar plot instance."""
super().__init__(chart)
if not isinstance(y[0], (Sequence, np.ndarray)):
y = (y,)
y_data = {f"y{i}": np.empty(0, np.float32) for i in range(len(y))}
self._table = pyvista.Table({"x": np.empty(0, np.float32), **y_data})
self.SetInputData(self._table, "x", "y0")
for i in range(1, len(y)):
self.SetInputArray(i + 1, f"y{i}")
self.update(x, y)
if len(y) > 1:
self.SetColorSeries(self._color_series)
self.colors = color # None will use default scheme
self.labels = label
else:
# Use blue bars by default in single component mode
self.color = "b" if color is None else color
self.label = label
self.orientation = orientation
@property
def x(self): # numpydoc ignore=RT01
"""Retrieve the positions of the drawn bars.
Examples
--------
Create a bar plot and display the positions.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 2, 0]])
>>> plot.x
pyvista_ndarray([1, 2, 3])
>>> chart.show()
"""
return self._table["x"]
@property
def y(self): # numpydoc ignore=RT01
"""Retrieve the sizes of the drawn bars.
Examples
--------
Create a bar plot and display the sizes.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 2, 0]])
>>> plot.y
(pyvista_ndarray([2, 1, 3]), pyvista_ndarray([1, 2, 0]))
>>> chart.show()
"""
return tuple(self._table[f"y{i}"] for i in range(self._table.n_arrays - 1))
def update(self, x, y):
"""Update the positions and/or size of the bars in this plot.
Parameters
----------
x : array_like
The new positions of the bars to draw.
y : array_like
The new sizes of the bars to draw.
Examples
--------
Create a bar plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.bar([1, 2, 3], [2, 1, 3])
>>> chart.show()
Update the bar sizes.
>>> plot.update([1, 2, 3], [3, 1, 2])
>>> chart.show()
"""
if len(x) > 0:
if not isinstance(y[0], (Sequence, np.ndarray)):
y = (y,)
y_data = {f"y{i}": np.asarray(y[i]) for i in range(len(y))}
self._table.update({"x": np.asarray(x), **y_data})
self.visible = True
else:
self.visible = False
@property
def orientation(self): # numpydoc ignore=RT01
"""Return or set the orientation of the bars in this plot.
Examples
--------
Create a bar plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.bar([1, 2, 3], [[2, 1, 3], [1, 3, 2]])
>>> chart.show()
Change the orientation to horizontal.
>>> plot.orientation = "H"
>>> chart.show()
"""
return self._orientation
@orientation.setter
def orientation(self, val): # numpydoc ignore=GL08
try:
self.SetOrientation(self.ORIENTATIONS[val])
self._orientation = val
except KeyError:
formatted_orientations = "\", \"".join(self.ORIENTATIONS.keys())
raise ValueError(
f"Invalid orientation. Allowed orientations: \"{formatted_orientations}\"",
)
class StackPlot(_MultiCompPlot, _vtk.vtkPlotStacked):
"""Class representing a 2D stack plot.
Users should typically not directly create new plot instances, but use the dedicated 2D chart's plotting methods.
Parameters
----------
chart : Chart2D
The chart containing this plot.
x : array_like
X coordinates of the points outlining the stacks (areas) to draw.
ys : sequence[array_like]
Size of the stacks (areas) to draw at the corresponding X
coordinates. Each sequence defines the sizes of one stack
(area), which are stacked on top of each other.
colors : sequence[ColorLike], optional
Color of the stacks (areas) drawn in this plot. Any color
parsable by :class:`pyvista.Color` is allowed.
labels : sequence[str], default: []
Label for each stack (area) drawn in this plot, as shown in
the chart's legend.
Examples
--------
Create a stack plot showing the amount of vehicles sold per type.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> year = [f"{y}" for y in np.arange(2011, 2021)]
>>> x = np.arange(len(year))
>>> n_e = [1739, 4925, 9515, 21727, 31452, 29926, 40648,
... 57761, 76370, 93702]
>>> n_h = [5563, 7642, 11937, 13905, 22807, 46700, 60875,
... 53689, 46650, 50321]
>>> n_f = [166556, 157249, 151552, 138183, 129669,
... 113985, 92965, 73683, 57097, 29499]
>>> chart = pv.Chart2D()
>>> plot = chart.stack(x, [n_e, n_h, n_f])
>>> plot.labels = ["Electric", "Hybrid", "Fossil"]
>>> chart.x_axis.label = "Year"
>>> chart.x_axis.tick_locations = x
>>> chart.x_axis.tick_labels = year
>>> chart.y_axis.label = "New car sales"
>>> chart.show()
"""
_DOC_SUBS = { # noqa: RUF012
"plot_name": "stack plot",
"chart_init": "pv.Chart2D()",
"plot_init": "chart.stack([0, 1, 2], [2, 1, 3])",
"multichart_init": "pv.Chart2D()",
"multiplot_init": "chart.stack([0, 1, 2], [[2, 1, 3], [1, 0, 2], [0, 3, 1], [3, 2, 0]])",
}
def __init__(self, chart, x, ys, colors=None, labels=None):
"""Initialize a new 2D stack plot instance."""
super().__init__(chart)
if not isinstance(ys[0], (Sequence, np.ndarray)):
ys = (ys,)
y_data = {f"y{i}": np.empty(0, np.float32) for i in range(len(ys))}
self._table = pyvista.Table({"x": np.empty(0, np.float32), **y_data})
self.SetInputData(self._table, "x", "y0")
for i in range(1, len(ys)):
self.SetInputArray(i + 1, f"y{i}")
self.update(x, ys)
if len(ys) > 1:
self.SetColorSeries(self._color_series)
self.colors = colors # None will use default scheme
self.labels = labels
else:
self.color = "b" if colors is None else colors
self.label = labels
self.pen.style = None # Hide lines by default
@property
def x(self): # numpydoc ignore=RT01
"""Retrieve the X coordinates of the drawn stacks.
Examples
--------
Create a stack plot and display the x coordinates.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.stack([0, 1, 2], [[2, 1, 3], [1, 2, 0]])
>>> plot.x
pyvista_ndarray([0, 1, 2])
>>> chart.show()
"""
return self._table["x"]
@property
def ys(self): # numpydoc ignore=RT01
"""Retrieve the sizes of the drawn stacks.
Examples
--------
Create a stack plot and display the sizes.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.stack([0, 1, 2], [[2, 1, 3], [1, 2, 0]])
>>> plot.ys
(pyvista_ndarray([2, 1, 3]), pyvista_ndarray([1, 2, 0]))
>>> chart.show()
"""
return tuple(self._table[f"y{i}"] for i in range(self._table.n_arrays - 1))
def update(self, x, ys):
"""Update the locations and/or size of the stacks (areas) in this plot.
Parameters
----------
x : array_like
The new x coordinates of the stacks (areas) to draw.
ys : sequence[array_like]
The new sizes of the stacks (areas) to draw.
Examples
--------
Create a stack plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.stack([0, 1, 2], [[2, 1, 3],[1, 2, 1]])
>>> chart.show()
Update the stack sizes.
>>> plot.update([0, 1, 2], [[3, 1, 2], [0, 3, 1]])
>>> chart.show()
"""
if len(x) > 0:
if not isinstance(ys[0], (Sequence, np.ndarray)):
ys = (ys,)
y_data = {f"y{i}": np.asarray(ys[i]) for i in range(len(ys))}
self._table.update({"x": np.asarray(x), **y_data})
self.visible = True
else:
self.visible = False
class Chart2D(_Chart, _vtk.vtkChartXY):
"""2D chart class similar to a ``matplotlib`` figure.
Parameters
----------
size : sequence[float], default: (1, 1)
Size of the chart in normalized coordinates. A size of ``(0,
0)`` is invisible, a size of ``(1, 1)`` occupies the whole
renderer's width and height.
loc : sequence[float], default: (0, 0)
Location of the chart (its bottom left corner) in normalized
coordinates. A location of ``(0, 0)`` corresponds to the
renderer's bottom left corner, a location of ``(1, 1)``
corresponds to the renderer's top right corner.
x_label : str, default: "x"
Label along the x-axis.
y_label : str, default: "y"
Label along the y-axis.
grid : bool, default: True
Show the background grid in the plot.
Examples
--------
Plot a simple sine wave as a scatter and line plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> x = np.linspace(0, 2*np.pi, 20)
>>> y = np.sin(x)
>>> chart = pv.Chart2D()
>>> _ = chart.scatter(x, y)
>>> _ = chart.line(x, y, 'r')
>>> chart.show()
Combine multiple types of plots in the same chart.
>>> rng = np.random.default_rng(1)
>>> x = np.arange(1, 8)
>>> y = rng.integers(5, 15, 7)
>>> e = np.abs(rng.normal(scale=2, size=7))
>>> z = rng.integers(0, 5, 7)
>>> chart = pv.Chart2D()
>>> _ = chart.area(x, y-e, y+e, color=(0.12, 0.46, 0.71, 0.2))
>>> _ = chart.line(x, y, color="tab:blue", style="--", label="Scores")
>>> _ = chart.scatter(x, y, color="tab:blue", style="d")
>>> _ = chart.bar(x, z, color="tab:orange", label="Violations")
>>> chart.x_axis.tick_locations = x
>>> chart.x_axis.tick_labels = ["Mon", "Tue", "Wed", "Thu", "Fri",
... "Sat", "Sun"]
>>> chart.x_label = "Day of week"
>>> chart.show()
"""
PLOT_TYPES: ClassVar[
dict[
str,
(type[ScatterPlot2D | LinePlot2D | AreaPlot | BarPlot | StackPlot]),
]
] = {
"scatter": ScatterPlot2D,
"line": LinePlot2D,
"area": AreaPlot,
"bar": BarPlot,
"stack": StackPlot,
}
_PLOT_CLASSES: ClassVar[
dict[
(type[ScatterPlot2D | LinePlot2D | AreaPlot | BarPlot | StackPlot]),
str,
]
] = {plot_class: plot_type for (plot_type, plot_class) in PLOT_TYPES.items()}
_DOC_SUBS = { # noqa: RUF012
"chart_name": "2D chart",
"chart_args": "",
"chart_init": """
>>> plot = chart.line([0, 1, 2], [2, 1, 3])""",
"chart_set_labels": 'plot.label = "My awesome plot"',
}
def __init__(
self,
size=(1, 1),
loc=(0, 0),
x_label="x",
y_label="y",
grid=True,
): # numpydoc ignore=PR01,RT01
"""Initialize the chart."""
super().__init__(size, loc)
self._plots = {plot_type: [] for plot_type in self.PLOT_TYPES.keys()}
self.SetAutoSize(False) # We manually set the appropriate size
# Overwrite custom x-axis and y-axis using a wrapper object, as using the
# SetAxis method causes a crash at the end of the script's execution (nonzero exit code).
self._x_axis = Axis(_wrap=self.GetAxis(_vtk.vtkAxis.BOTTOM))
self._y_axis = Axis(_wrap=self.GetAxis(_vtk.vtkAxis.LEFT))
# Note: registering the axis prevents the nonzero exit code at the end, however
# this results in memory leaks in the plotting tests.
# self.SetAxis(_vtk.vtkAxis.BOTTOM, self._x_axis)
# self.SetAxis(_vtk.vtkAxis.LEFT, self._y_axis)
# self.Register(self._x_axis)
# self.Register(self._y_axis)
self.x_label = x_label
self.y_label = y_label
self.grid = grid
self.legend_visible = True
def _render_event(self, *args, plotter_render=False, **kwargs):
if plotter_render:
# TODO: should probably be called internally by VTK when plot data or axis behavior/logscale is changed?
self.RecalculateBounds()
super()._render_event(*args, plotter_render=plotter_render, **kwargs)
def _add_plot(self, plot_type, *args, **kwargs):
"""Add a plot of the given type to this chart."""
plot = self.PLOT_TYPES[plot_type](self, *args, **kwargs)
self.AddPlot(plot)
self._plots[plot_type].append(plot)
return plot
@classmethod
def _parse_format(cls, fmt):
"""Parse a format string and separate it into a marker style, line style and color.
Parameters
----------
fmt : str
Format string to parse. A format string consists of any
combination of a valid marker style, a valid line style
and parsable color. The specific order does not
matter. See :attr:`pyvista.ScatterPlot2D.MARKER_STYLES`
for a list of valid marker styles,
:attr:`pyvista.Pen.LINE_STYLES` for a list of valid line
styles and :class:`pyvista.Color` for an overview of
parsable colors.
Returns
-------
marker_style : str
Extracted marker style (empty string if no marker style
was present in the format string).
line_style : str
Extracted line style (empty string if no line style was
present in the format string).
color : str
Extracted color string (defaults to ``"b"`` if no color
was present in the format string).
Examples
--------
>>> import pyvista as pv
>>> m, l, c = pv.Chart2D._parse_format("x--b")
"""
marker_style = ""
line_style = ""
color = None
# Note: All colors, marker styles and line styles are sorted in decreasing order of length to be able to find
# the largest match first (e.g. find 'darkred' and '--' first instead of 'red' and '-')
colors = sorted(
itertools.chain(hexcolors.keys(), color_synonyms.keys()),
key=len,
reverse=True,
)
marker_styles = sorted(ScatterPlot2D.MARKER_STYLES.keys(), key=len, reverse=True)
line_styles = sorted(Pen.LINE_STYLES.keys(), key=len, reverse=True)
hex_pattern = "(#|0x)[A-Fa-f0-9]{6}([A-Fa-f0-9]{2})?" # Match RGB(A) hex string
# Extract color from format string
match = re.search(hex_pattern, fmt) # Start with matching hex strings
if match is not None:
color = match.group()
else: # Proceed with matching color strings
for c in colors:
if c in fmt:
color = c
break
if color is not None:
fmt = fmt.replace(color, "", 1) # Remove found color from format string
else:
color = "b"
# Extract marker style from format string
for style in marker_styles[:-1]: # Last style is empty string
if style in fmt:
marker_style = style
fmt = fmt.replace(
marker_style,
"",
1,
) # Remove found marker_style from format string
break
# Extract line style from format string
for style in line_styles[:-1]: # Last style is empty string
if style in fmt:
line_style = style
fmt = fmt.replace(line_style, "", 1) # Remove found line_style from format string
break
return marker_style, line_style, color
def plot(self, x, y=None, fmt='-'):
"""Matplotlib like plot method.
Parameters
----------
x : array_like
Values to plot on the X-axis. In case ``y`` is ``None``,
these are the values to plot on the Y-axis instead.
y : array_like, optional
Values to plot on the Y-axis.
fmt : str, default: "-"
A format string, e.g. ``'ro'`` for red circles. See the Notes
section for a full description of the format strings.
Returns
-------
scatter_plot : plotting.charts.ScatterPlot2D, optional
The created scatter plot when a valid marker style
was present in the format string, ``None`` otherwise.
line_plot : plotting.charts.LinePlot2D, optional
The created line plot when a valid line style was
present in the format string, ``None`` otherwise.
Notes
-----
This plot method shares many of the same plotting features as
the `matplotlib.pyplot.plot
<https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html>`_.
Please reference the documentation there for a full
description of the allowable format strings.
Examples
--------
Generate a line plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _, line_plot = chart.plot(range(10), range(10))
>>> chart.show()
Generate a line and scatter plot.
>>> chart = pv.Chart2D()
>>> scatter_plot, line_plot = chart.plot(range(10), fmt='o-')
>>> chart.show()
"""
if y is None:
y = x
x = np.arange(len(y))
elif isinstance(y, str):
fmt = y
y = x
x = np.arange(len(y))
marker_style, line_style, color = self._parse_format(fmt)
scatter_plot, line_plot = None, None
if marker_style != "":
scatter_plot = self.scatter(x, y, color, style=marker_style)
if line_style != "":
line_plot = self.line(x, y, color, style=line_style)
return scatter_plot, line_plot
def scatter(self, x, y, color="b", size=10, style="o", label=""):
"""Add a scatter plot to this chart.
Parameters
----------
x : array_like
X coordinates of the points to draw.
y : array_like
Y coordinates of the points to draw.
color : ColorLike, default: "b"
Color of the points drawn in this plot. Any color parsable
by :class:`pyvista.Color` is allowed.
size : float, default: 10
Size of the point markers drawn in this plot.
style : str, default: "o"
Style of the point markers drawn in this plot. See
:ref:`ScatterPlot2D.MARKER_STYLES <scatter_marker_styles>`
for a list of allowed marker styles.
label : str, default: ""
Label of this plot, as shown in the chart's legend.
Returns
-------
plotting.charts.ScatterPlot2D
The created scatter plot.
Examples
--------
Generate a scatter plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.scatter([0, 1, 2], [2, 1, 3])
>>> chart.show()
"""
return self._add_plot("scatter", x, y, color=color, size=size, style=style, label=label)
def line(self, x, y, color="b", width=1.0, style="-", label=""):
"""Add a line plot to this chart.
Parameters
----------
x : array_like
X coordinates of the points through which a line should be drawn.
y : array_like
Y coordinates of the points through which a line should be drawn.
color : ColorLike, default: "b"
Color of the line drawn in this plot. Any color parsable
by :class:`pyvista.Color` is allowed.
width : float, default: 1
Width of the line drawn in this plot.
style : str, default: "-"
Style of the line drawn in this plot. See
:ref:`Pen.LINE_STYLES <pen_line_styles>` for a list of
allowed line styles.
label : str, default: ""
Label of this plot, as shown in the chart's legend.
Returns
-------
plotting.charts.LinePlot2D
The created line plot.
Examples
--------
Generate a line plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.show()
"""
return self._add_plot("line", x, y, color=color, width=width, style=style, label=label)
def area(self, x, y1, y2=None, color="b", label=""):
"""Add an area plot to this chart.
Parameters
----------
x : array_like
X coordinates of the points outlining the area to draw.
y1 : array_like
Y coordinates of the points on the first outline of the area to draw.
y2 : array_like, optional
Y coordinates of the points on the second outline of the
area to draw. Defaults to ``np.zeros_like(x)``.
color : ColorLike, default: "b"
Color of the area drawn in this plot. Any color parsable
by :class:`pyvista.Color` is allowed.
label : str, default: ""
Label of this plot, as shown in the chart's legend.
Returns
-------
plotting.charts.AreaPlot
The created area plot.
Examples
--------
Generate an area plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.area([0, 1, 2], [2, 1, 3])
>>> chart.show()
"""
return self._add_plot("area", x, y1, y2, color=color, label=label)
def bar(self, x, y, color=None, orientation="V", label=None):
"""Add a bar plot to this chart.
Parameters
----------
x : array_like
Positions (along the x-axis for a vertical orientation,
along the y-axis for a horizontal orientation) of the bars
to draw.
y : array_like
Size of the bars to draw. Multiple bars can be stacked by
passing a sequence of sequences.
color : ColorLike, default: "b"
Color of the bars drawn in this plot. Any color parsable
by :class:`pyvista.Color` is allowed.
orientation : str, default: "V"
Orientation of the bars drawn in this plot. Either ``"H"``
for an horizontal orientation or ``"V"`` for a vertical
orientation.
label : str, default: ""
Label of this plot, as shown in the chart's legend.
Returns
-------
plotting.charts.BarPlot
The created bar plot.
Examples
--------
Generate a bar plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.bar([0, 1, 2], [2, 1, 3])
>>> chart.show()
"""
return self._add_plot("bar", x, y, color=color, orientation=orientation, label=label)
def stack(self, x, ys, colors=None, labels=None):
"""Add a stack plot to this chart.
Parameters
----------
x : array_like
X coordinates of the points outlining the stacks (areas) to draw.
ys : sequence[array_like]
Size of the stacks (areas) to draw at the corresponding X
coordinates. Each sequence defines the sizes of one stack
(area), which are stacked on top of each other.
colors : sequence[ColorLike], optional
Color of the stacks (areas) drawn in this plot. Any color
parsable by :class:`pyvista.Color` is allowed.
labels : sequence[str], default: []
Label for each stack (area) drawn in this plot, as shown
in the chart's legend.
Returns
-------
plotting.charts.StackPlot
The created stack plot.
Examples
--------
Generate a stack plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> plot = chart.stack([0, 1, 2], [[2, 1, 3],[1, 2, 1]])
>>> chart.show()
"""
return self._add_plot("stack", x, ys, colors=colors, labels=labels)
def plots(self, plot_type=None):
"""Return all plots of the specified type in this chart.
Parameters
----------
plot_type : str, optional
The type of plots to return. Allowed types are
``"scatter"``, ``"line"``, ``"area"``, ``"bar"``
and ``"stack"``.
If no type is provided (``None``), all plots are returned,
regardless of their type.
Yields
------
plot : plotting.charts.ScatterPlot2D | plotting.charts.LinePlot2D | plotting.charts.AreaPlot | plotting.charts.BarPlot | plotting.charts.StackPlot
One of the plots (of the specified type) in this chart.
Examples
--------
Create a 2D chart with a line and scatter plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> scatter_plot, line_plot = chart.plot([0, 1, 2], [2, 1, 3], "o-")
>>> chart.show()
Retrieve all plots in the chart.
>>> plots = [*chart.plots()]
>>> scatter_plot in plots and line_plot in plots
True
Retrieve all line plots in the chart.
>>> line_plots = [*chart.plots("line")]
>>> line_plot == line_plots[0]
True
"""
plot_types = self.PLOT_TYPES.keys() if plot_type is None else [plot_type]
for plot_type in plot_types:
yield from self._plots[plot_type]
def remove_plot(self, plot):
"""Remove the given plot from this chart.
Parameters
----------
plot : plotting.charts.ScatterPlot2D | plotting.charts.LinePlot2D | plotting.charts.AreaPlot | plotting.charts.BarPlot | plotting.charts.StackPlot
The plot to remove.
Examples
--------
Create a 2D chart with a line and scatter plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> scatter_plot, line_plot = chart.plot([0, 1, 2], [2, 1, 3], "o-")
>>> chart.show()
Remove the scatter plot from the chart.
>>> chart.remove_plot(scatter_plot)
>>> chart.show()
"""
try:
plot_type = self._PLOT_CLASSES[type(plot)]
self._plots[plot_type].remove(plot)
self.RemovePlotInstance(plot)
except (KeyError, ValueError):
raise ValueError("The given plot is not part of this chart.")
def clear(self, plot_type=None):
"""Remove all plots of the specified type from this chart.
Parameters
----------
plot_type : str, optional
The type of the plots to remove. Allowed types are
``"scatter"``, ``"line"``, ``"area"``, ``"bar"``
and ``"stack"``.
If no type is provided (``None``), all plots are removed,
regardless of their type.
Examples
--------
Create a 2D chart with multiple line and scatter plot.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.plot([0, 1, 2], [2, 1, 3], "o-b")
>>> _ = chart.plot([-2, -1, 0], [3, 1, 2], "d-r")
>>> chart.show()
Remove all scatter plots from the chart.
>>> chart.clear("scatter")
>>> chart.show()
"""
plot_types = self.PLOT_TYPES.keys() if plot_type is None else [plot_type]
for plot_type in plot_types:
# Make a copy, as this list will be modified by remove_plot
plots = [*self._plots[plot_type]]
for plot in plots:
self.remove_plot(plot)
@property
def x_axis(self): # numpydoc ignore=RT01
"""Return this chart's horizontal (x) :class:`Axis <plotting.charts.Axis>`.
Examples
--------
Create a 2D plot and hide the x-axis.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_axis.toggle()
>>> chart.show()
"""
return self._x_axis
@property
def y_axis(self): # numpydoc ignore=RT01
"""Return this chart's vertical (y) :class:`Axis <plotting.charts.Axis>`.
Examples
--------
Create a 2D plot and hide the y-axis.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.y_axis.toggle()
>>> chart.show()
"""
return self._y_axis
@property
def x_label(self): # numpydoc ignore=RT01
"""Return or set the label of this chart's x-axis.
Examples
--------
Create a 2D plot and set custom axis labels.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_label = "Horizontal axis"
>>> chart.y_label = "Vertical axis"
>>> chart.show()
"""
return self.x_axis.label
@x_label.setter
def x_label(self, val): # numpydoc ignore=GL08
self.x_axis.label = val
@property
def y_label(self): # numpydoc ignore=RT01
"""Return or set the label of this chart's y-axis.
Examples
--------
Create a 2D plot and set custom axis labels.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_label = "Horizontal axis"
>>> chart.y_label = "Vertical axis"
>>> chart.show()
"""
return self.y_axis.label
@y_label.setter
def y_label(self, val): # numpydoc ignore=GL08
self.y_axis.label = val
@property
def x_range(self): # numpydoc ignore=RT01
"""Return or set the range of this chart's x-axis.
Examples
--------
Create a 2D plot and set custom axis ranges.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_range = [-2, 2]
>>> chart.y_range = [0, 5]
>>> chart.show()
"""
return self.x_axis.range
@x_range.setter
def x_range(self, val): # numpydoc ignore=GL08
self.x_axis.range = val
@property
def y_range(self): # numpydoc ignore=RT01
"""Return or set the range of this chart's y-axis.
Examples
--------
Create a 2D plot and set custom axis ranges.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.x_range = [-2, 2]
>>> chart.y_range = [0, 5]
>>> chart.show()
"""
return self.y_axis.range
@y_range.setter
def y_range(self, val): # numpydoc ignore=GL08
self.y_axis.range = val
@property
def grid(self): # numpydoc ignore=RT01
"""Enable or disable the chart grid.
Examples
--------
Create a 2D chart with the grid disabled.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> x = np.linspace(0, 2*np.pi, 20)
>>> y = np.sin(x)
>>> chart = pv.Chart2D()
>>> _ = chart.line(x, y, 'r')
>>> chart.grid = False
>>> chart.show()
Enable the grid
>>> chart.grid = True
>>> chart.show()
"""
return self.x_axis.grid and self.y_axis.grid
@grid.setter
def grid(self, val): # numpydoc ignore=GL08
self.x_axis.grid = val
self.y_axis.grid = val
def hide_axes(self):
"""Hide the x- and y-axis of this chart.
This includes all labels, ticks and the grid.
Examples
--------
Create a 2D plot and hide the axes.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([0, 1, 2], [2, 1, 3])
>>> chart.hide_axes()
>>> chart.show()
"""
for axis in (self.x_axis, self.y_axis):
axis.visible = False
axis.label_visible = False
axis.ticks_visible = False
axis.tick_labels_visible = False
axis.grid = False
class BoxPlot(_MultiCompPlot, _vtk.vtkPlotBox):
"""Class representing a box plot.
Users should typically not directly create new plot instances, but
use the dedicated ``ChartBox`` class.
Parameters
----------
chart : ChartBox
The chart containing this plot.
data : sequence[array_like]
Dataset(s) from which the relevant statistics will be
calculated used to draw the box plot.
colors : sequence[ColorLike], optional
Color of the boxes drawn in this plot. Any color parsable by
:class:`pyvista.Color` is allowed. If omitted (``None``), the
default color scheme is used.
labels : sequence[str], default: []
Label for each box drawn in this plot, as shown in the chart's
legend.
Examples
--------
Create boxplots for datasets sampled from shifted normal distributions.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> rng = np.random.default_rng(1) # Seeded random number generator used for data generation
>>> normal_data = [rng.normal(i, size=50) for i in range(5)]
>>> chart = pv.ChartBox(normal_data, labels=[f"x ~ N({i},1)" for i in range(5)])
>>> chart.show()
"""
_DOC_SUBS = { # noqa: RUF012
"plot_name": "box plot",
"chart_init": "pv.ChartBox([[0, 1, 1, 2, 3, 3, 4]])",
"plot_init": "chart.plot",
"multichart_init": "pv.ChartBox([[0, 1, 1, 2, 3, 4, 5], [0, 1, 2, 2, 3, 4, 5], [0, 1, 2, 3, 3, 4, 5], [0, 1, 2, 3, 4, 4, 5]])",
"multiplot_init": "chart.plot",
}
def __init__(self, chart, data, colors=None, labels=None):
"""Initialize a new box plot instance."""
super().__init__(chart)
self._table = pyvista.Table(
{f"data_{i}": np.asarray(d) for i, d in enumerate(data)},
)
self._quartiles = _vtk.vtkComputeQuartiles()
self._quartiles.SetInputData(self._table)
self.SetInputData(self._quartiles.GetOutput())
self.update(data)
self.SetLookupTable(self._lookup_table)
self.colors = colors
self.labels = labels
@property
def data(self): # numpydoc ignore=RT01
"""Retrieve the datasets of which the boxplots are drawn.
Examples
--------
Create a box plot and display the datasets.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
>>> chart.plot.data
(pyvista_ndarray([0, 1, 1, 2, 3, 3, 4]),)
>>> chart.show()
"""
return tuple(self._table[f"data_{i}"] for i in range(self._table.n_arrays))
@property
def stats(self): # numpydoc ignore=RT01
"""Retrieve the statistics (quartiles and extremum values) of the datasets of which the boxplots are drawn.
Examples
--------
Create a box plot and display the statistics.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
>>> chart.plot.stats
(pyvista_ndarray([0., 1., 2., 3., 4.]),)
>>> chart.show()
"""
stats_table = pyvista.Table(self._quartiles.GetOutput())
return tuple(stats_table[f"data_{i}"] for i in range(stats_table.n_arrays))
def update(self, data):
"""Update the plot's underlying dataset(s).
Parameters
----------
data : sequence[array_like]
The new dataset(s) used in this box plot.
Examples
--------
Create a box plot from a standard Gaussian dataset.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> rng = np.random.default_rng(1) # Seeded random number generator for data generation
>>> chart = pv.ChartBox([rng.normal(size=100)])
>>> chart.show()
Update the box plot (shift the standard Gaussian distribution).
>>> chart.plot.update([rng.normal(loc=2, size=100)])
>>> chart.show()
"""
self._table.update({f"data_{i}": np.asarray(d) for i, d in enumerate(data)})
self._quartiles.Update()
class ChartBox(_Chart, _vtk.vtkChartBox):
"""Dedicated chart for drawing box plots.
Parameters
----------
data : sequence[array_like]
Dataset(s) from which the relevant statistics will be
calculated used to draw the box plot.
colors : sequence[ColorLike], optional
Color used for each drawn boxplot. If omitted (``None``), the
default color scheme is used.
labels : sequence[str], default: []
Label for each drawn boxplot, as shown in the chart's
legend.
size : sequence[float], optional
Size of the chart in normalized coordinates. A size of ``(0,
0)`` is invisible, a size of ``(1, 1)`` occupies the whole
renderer's width and height.
loc : sequence[float], optional
Location of the chart (its bottom left corner) in normalized
coordinates. A location of ``(0, 0)`` corresponds to the
renderer's bottom left corner, a location of ``(1, 1)``
corresponds to the renderer's top right corner.
Examples
--------
Create boxplots for datasets sampled from shifted normal distributions.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> rng = np.random.default_rng(1) # Seeded random number generator used for data generation
>>> normal_data = [rng.normal(i, size=50) for i in range(5)]
>>> chart = pv.ChartBox(normal_data, labels=[f"x ~ N({i},1)" for i in range(5)])
>>> chart.show()
"""
_DOC_SUBS = { # noqa: RUF012
"chart_name": "boxplot chart",
"chart_args": "[[0, 1, 1, 2, 3, 3, 4]]",
"chart_init": "",
"chart_set_labels": 'chart.plot.label = "Data label"',
}
def __init__(
self,
data,
colors=None,
labels=None,
size=None,
loc=None,
): # numpydoc ignore=PR01,RT01
"""Initialize a new chart containing box plots."""
if vtk_version_info >= (9, 2, 0):
self.SetAutoSize(False) # We manually set the appropriate size
if size is None:
size = (1, 1)
if loc is None:
loc = (0, 0)
super().__init__(size, loc)
self._plot = BoxPlot(self, data, colors, labels)
self.SetPlot(self._plot)
self.SetColumnVisibilityAll(True)
self.legend_visible = True
def _render_event(self, *args, **kwargs):
if vtk_version_info < (9, 2, 0): # pragma: no cover
# In older VTK versions, ChartBox fills the entire scene, so
# no resizing is needed (nor possible).
pass
else:
super()._render_event(*args, **kwargs)
@property
def _geometry(self):
if vtk_version_info < (9, 2, 0): # pragma: no cover
return (0, 0, *self._renderer.GetSize())
else:
return _Chart._geometry.fget(self)
@_geometry.setter
def _geometry(self, value):
if vtk_version_info < (9, 2, 0): # pragma: no cover
raise AttributeError(f'Cannot set the geometry of {type(self).__class__}')
else:
_Chart._geometry.fset(self, value)
@property
def plot(self): # numpydoc ignore=RT01
"""Return the :class:`BoxPlot <plotting.charts.BoxPlot>` instance associated with this chart.
Examples
--------
Create a box plot from a standard Gaussian dataset.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> rng = np.random.default_rng(1) # Seeded random number generator for data generation
>>> chart = pv.ChartBox([rng.normal(size=100)])
>>> chart.show()
Update the box plot (shift the standard Gaussian distribution).
>>> chart.plot.update([rng.normal(loc=2, size=100)])
>>> chart.show()
"""
return self._plot
@property
def size(self): # numpydoc ignore=RT01
"""Return or set the chart size in normalized coordinates.
A size of ``(1, 1)`` occupies the whole renderer.
Notes
-----
Customisable ChartBox geometry is only supported in VTK v9.2
or newer. For older VTK versions, the size cannot be modified,
filling up the entire viewport by default.
Examples
--------
Create a half-sized boxplot chart centered in the middle of the
renderer.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
>>> chart.size = (0.5, 0.5)
>>> chart.loc = (0.25, 0.25)
>>> chart.show()
"""
if vtk_version_info < (9, 2, 0): # pragma: no cover
return (1, 1)
else:
return _Chart.size.fget(self)
@size.setter
def size(self, val): # numpydoc ignore=GL08
if vtk_version_info < (9, 2, 0): # pragma: no cover
raise ValueError(
"Cannot set ChartBox geometry, it fills up the entire viewport by default. "
"Upgrade to VTK v9.2 or newer.",
)
else:
_Chart.size.fset(self, val)
@property
def loc(self): # numpydoc ignore=RT01
"""Return or set the chart position in normalized coordinates.
This denotes the location of the chart's bottom left corner.
Notes
-----
Customisable ChartBox geometry is only supported in VTK v9.2
or newer. For older VTK versions, the location cannot be modified,
filling up the entire viewport by default.
Examples
--------
Create a half-sized boxplot chart centered in the middle of the
renderer.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.ChartBox([[0, 1, 1, 2, 3, 3, 4]])
>>> chart.size = (0.5, 0.5)
>>> chart.loc = (0.25, 0.25)
>>> chart.show()
"""
if vtk_version_info < (9, 2, 0): # pragma: no cover
return (0, 0)
else:
return _Chart.loc.fget(self)
@loc.setter
def loc(self, val): # numpydoc ignore=GL08
if vtk_version_info < (9, 2, 0): # pragma: no cover
raise ValueError(
"Cannot set ChartBox geometry, it fills up the entire viewport by default. "
"Upgrade to VTK v9.2 or newer.",
)
else:
_Chart.loc.fset(self, val)
class PiePlot(_MultiCompPlot, _vtkWrapper, _vtk.vtkPlotPie):
"""Class representing a pie plot.
Users should typically not directly create new plot instances, but
use the dedicated :class:`ChartPie` class.
Parameters
----------
chart : ChartPie
The chart containing this plot.
data : array_like
Relative size of each pie segment.
colors : sequence[ColorLike], optional
Color of the segments drawn in this plot. Any color parsable
by :class:`pyvista.Color` is allowed. If omitted (``None``),
the default color scheme is used.
labels : sequence[str], default: []
Label for each pie segment drawn in this plot, as shown in the
chart's legend.
Examples
--------
Create a pie plot showing the usage of tax money.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> x = [128.3, 32.9, 31.8, 29.3, 21.2]
>>> l = ["Social benefits", "Governance", "Economic policy", "Education", "Other"]
>>> chart = pv.ChartPie(x, labels=l)
>>> chart.show()
"""
_DOC_SUBS = { # noqa: RUF012
"plot_name": "pie plot",
"chart_init": "pv.ChartPie([4, 3, 2, 1])",
"plot_init": "chart.plot",
"multichart_init": "pv.ChartPie([4, 3, 2, 1])",
"multiplot_init": "chart.plot",
}
def __init__(self, chart, data, colors=None, labels=None):
"""Initialize a new pie plot instance."""
super().__init__(chart)
self._table = pyvista.Table(data)
self.SetInputData(self._table)
self.SetInputArray(0, self._table.keys()[0])
self.update(data)
self.labels = labels
self.SetColorSeries(self._color_series)
self.colors = colors
@property
def data(self): # numpydoc ignore=RT01
"""Retrieve the sizes of the drawn segments.
Examples
--------
Create a pie plot and display the sizes.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.ChartPie([1, 2, 3])
>>> chart.plot.data
pyvista_ndarray([1, 2, 3])
>>> chart.show()
"""
return self._table[0]
def update(self, data):
"""Update the size of the pie segments.
Parameters
----------
data : array_like
The new relative size of each pie segment.
Examples
--------
Create a pie plot with segments of increasing size.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.ChartPie([1, 2, 3, 4, 5])
>>> chart.show()
Update the pie plot (segments of equal size).
>>> chart.plot.update([1, 1, 1, 1, 1])
>>> chart.show()
"""
self._table.update(data)
class ChartPie(_Chart, _vtk.vtkChartPie):
"""Dedicated chart for drawing pie plots.
Parameters
----------
data : array_like
Relative size of each pie segment.
colors : sequence[ColorLike], optional
Color used for each pie segment drawn in this plot. If
omitted (``None``), the default color scheme is used.
labels : sequence[str], default: []
Label for each pie segment drawn in this plot, as shown in the
chart's legend.
size : sequence[float], optional
Size of the chart in normalized coordinates. A size of ``(0,
0)`` is invisible, a size of ``(1, 1)`` occupies the whole
renderer's width and height.
loc : sequence[float], optional
Location of the chart (its bottom left corner) in normalized
coordinates. A location of ``(0, 0)`` corresponds to the
renderer's bottom left corner, a location of ``(1, 1)``
corresponds to the renderer's top right corner.
Examples
--------
Create a pie plot showing the usage of tax money.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> x = [128.3, 32.9, 31.8, 29.3, 21.2]
>>> l = ["Social benefits", "Governance", "Economic policy", "Education", "Other"]
>>> chart = pv.ChartPie(x, labels=l)
>>> chart.show()
"""
_DOC_SUBS = { # noqa: RUF012
"chart_name": "pie chart",
"chart_args": "[5, 4, 3, 2, 1]",
"chart_init": "",
"chart_set_labels": 'chart.plot.labels = ["A", "B", "C", "D", "E"]',
}
def __init__(
self,
data,
colors=None,
labels=None,
size=None,
loc=None,
): # numpydoc ignore=PR01,RT01
"""Initialize a new chart containing a pie plot."""
if vtk_version_info >= (9, 2, 0):
self.SetAutoSize(False) # We manually set the appropriate size
if size is None:
size = (1, 1)
if loc is None:
loc = (0, 0)
super().__init__(size, loc)
if vtk_version_info < (9, 2, 0): # pragma: no cover
# SetPlot method is not available for older VTK versions,
# so fallback to using a wrapper object.
self.AddPlot(0)
self._plot = PiePlot(self, data, colors, labels, _wrap=self.GetPlot(0))
else:
self._plot = PiePlot(self, data, colors, labels)
self.SetPlot(self._plot)
self.legend_visible = True
def _render_event(self, *args, **kwargs):
if vtk_version_info < (9, 2, 0): # pragma: no cover
# In older VTK versions, ChartPie fills the entire scene, so
# no resizing is needed (nor possible).
pass
else:
super()._render_event(*args, **kwargs)
@property
def _geometry(self):
if vtk_version_info < (9, 2, 0): # pragma: no cover
return (0, 0, *self._renderer.GetSize())
else:
return _Chart._geometry.fget(self)
@_geometry.setter
def _geometry(self, value):
if vtk_version_info < (9, 2, 0): # pragma: no cover
raise AttributeError(f'Cannot set the geometry of {type(self).__class__}')
else:
_Chart._geometry.fset(self, value)
@property
def plot(self): # numpydoc ignore=RT01
"""Return the :class:`PiePlot <plotting.charts.PiePlot>` instance associated with this chart.
Examples
--------
Create a pie plot with segments of increasing size.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.ChartPie([1, 2, 3, 4, 5])
>>> chart.show()
Update the pie plot (segments of equal size).
>>> chart.plot.update([1, 1, 1, 1, 1])
>>> chart.show()
"""
return self._plot
@property
def size(self): # numpydoc ignore=RT01
"""Return or set the chart size in normalized coordinates.
A size of ``(1, 1)`` occupies the whole renderer.
Notes
-----
Customisable ChartPie geometry is only supported in VTK v9.2
or newer. For older VTK versions, the size cannot be modified,
filling up the entire viewport by default.
Examples
--------
Create a half-sized pie chart centered in the middle of the
renderer.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.ChartPie([5, 4, 3, 2, 1])
>>> chart.size = (0.5, 0.5)
>>> chart.loc = (0.25, 0.25)
>>> chart.show()
"""
if vtk_version_info < (9, 2, 0): # pragma: no cover
return (1, 1)
else:
return _Chart.size.fget(self)
@size.setter
def size(self, val): # numpydoc ignore=GL08
if vtk_version_info < (9, 2, 0): # pragma: no cover
raise ValueError(
"Cannot set ChartPie geometry, it fills up the entire viewport by default. "
"Upgrade to VTK v9.2 or newer.",
)
else:
_Chart.size.fset(self, val)
@property
def loc(self): # numpydoc ignore=RT01
"""Return or set the chart position in normalized coordinates.
This denotes the location of the chart's bottom left corner.
Notes
-----
Customisable ChartPie geometry is only supported in VTK v9.2
or newer. For older VTK versions, the location cannot be modified,
filling up the entire viewport by default.
Examples
--------
Create a half-sized pie chart centered in the middle of the
renderer.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.ChartPie([5, 4, 3, 2, 1])
>>> chart.size = (0.5, 0.5)
>>> chart.loc = (0.25, 0.25)
>>> chart.show()
"""
if vtk_version_info < (9, 2, 0): # pragma: no cover
return (0, 0)
else:
return _Chart.loc.fget(self)
@loc.setter
def loc(self, val): # numpydoc ignore=GL08
if vtk_version_info < (9, 2, 0): # pragma: no cover
raise ValueError(
"Cannot set ChartPie geometry, it fills up the entire viewport by default. "
"Upgrade to VTK v9.2 or newer.",
)
else:
_Chart.loc.fset(self, val)
# region 3D charts
# A basic implementation of 3D line, scatter and volume plots, to be used in a 3D chart was provided in this section
# but removed in commit 8ef8daea5d105e85f256d4e9af584aeea3c85040 of PR #1432. Unfortunately, these charts are much less
# customisable than their 2D counterparts and they do not respect the enforced size/geometry constraints once you start
# interacting with them.
# endregion
class ChartMPL(_Chart, _vtk.vtkImageItem):
"""Create new chart from an existing matplotlib figure.
Parameters
----------
figure : matplotlib.figure.Figure, optional
The matplotlib figure to draw. If no figure is
provided ( ``None`` ), a new figure is created.
size : sequence[float], default: (1, 1)
Size of the chart in normalized coordinates. A size of ``(0,
0)`` is invisible, a size of ``(1, 1)`` occupies the whole
renderer's width and height.
loc : sequence[float], default: (0, 0)
Location of the chart (its bottom left corner) in normalized
coordinates. A location of ``(0, 0)`` corresponds to the
renderer's bottom left corner, a location of ``(1, 1)``
corresponds to the renderer's top right corner.
redraw_on_render : bool, default: True
Flag indicating whether the chart should be redrawn when
the plotter is rendered. For static charts, setting this
to ``False`` can improve performance.
Examples
--------
Plot streamlines of a vector field with varying colors (based on `this example <https://matplotlib.org/stable/gallery/images_contours_and_fields/plot_streamplot.html>`_).
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> w = 3
>>> Y, X = np.mgrid[-w:w:100j, -w:w:100j]
>>> U = -1 - X**2 + Y
>>> V = 1 + X - Y**2
>>> speed = np.sqrt(U**2 + V**2)
>>> f, ax = plt.subplots()
>>> strm = ax.streamplot(X, Y, U, V, color=U, linewidth=2, cmap='autumn')
>>> _ = f.colorbar(strm.lines)
>>> _ = ax.set_title('Streamplot with varying Color')
>>> plt.tight_layout()
>>> chart = pv.ChartMPL(f)
>>> chart.show()
"""
_DOC_SUBS = { # noqa: RUF012
"chart_name": "matplotlib chart",
"chart_args": "",
"chart_init": """
>>> plots = chart.figure.axes[0].plot([0, 1, 2], [2, 1, 3])""",
"chart_set_labels": 'plots[0].label = "My awesome plot"',
}
def __init__(
self,
figure=None,
size=(1, 1),
loc=(0, 0),
redraw_on_render=True,
): # numpydoc ignore=PR01,RT01
"""Initialize chart."""
super().__init__(size, loc)
if figure is None:
figure, _ = plt.subplots()
self._fig = figure
self._canvas = FigureCanvasAgg(
self._fig,
) # Switch backends and store reference to figure's canvas
# Make figure and axes fully transparent, as the background is already dealt with by self._background.
self._fig.patch.set_alpha(0)
for ax in self._fig.axes:
ax.patch.set_alpha(0)
self._canvas.mpl_connect('draw_event', self._redraw) # Attach 'draw_event' callback
self._redraw_on_render = redraw_on_render
self._redraw()
# Close the underlying matplotlib figure when creating the sphinx gallery.
# This prevents the charts from being drawn twice in example scripts:
# once as a pyvista plot (fetched by the 'pyvista' scraper) and once as a
# matplotlib figure (fetched by the 'matplotlib' scraper).
# See #1999 and #2031.
if pyvista.BUILDING_GALLERY: # pragma: no cover
plt.close(self._fig)
@property
def figure(self): # numpydoc ignore=RT01
"""Retrieve the matplotlib figure associated with this chart.
Examples
--------
Create a matplotlib chart from an existing figure.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import matplotlib.pyplot as plt
>>> f, ax = plt.subplots()
>>> _ = ax.plot([0, 1, 2], [2, 1, 3])
>>> chart = pv.ChartMPL(f)
>>> chart.figure is f
True
>>> chart.show()
"""
return self._fig
@property
def redraw_on_render(self): # numpydoc ignore=RT01
"""Return or set the chart's redraw-on-render behavior.
Notes
-----
When disabled, the chart will only be redrawn when the
Plotter window is resized or the matplotlib figure is
manually redrawn using ``fig.canvas.draw()``.
When enabled, the chart will also be automatically
redrawn whenever the Plotter is rendered using
``plotter.render()``.
"""
return self._redraw_on_render
@redraw_on_render.setter
def redraw_on_render(self, val): # numpydoc ignore=GL08
self._redraw_on_render = bool(val)
def _resize(self):
r_w, r_h = self._renderer.GetSize()
c_w, c_h = (int(s) for s in self._canvas.get_width_height())
# Calculate target size from specified normalized width and height and the renderer's current size
t_w = int(self._size[0] * r_w)
t_h = int(self._size[1] * r_h)
resize = c_w != t_w or c_h != t_h
if resize:
# Mismatch between canvas size and target size, so resize figure:
f_w = t_w / self._fig.dpi
f_h = t_h / self._fig.dpi
self._fig.set_size_inches(f_w, f_h)
self.position = (int(self._loc[0] * r_w), int(self._loc[1] * r_h))
return resize
def _redraw(self, event=None):
"""Redraw the chart."""
if event is None:
# Manual call, so make sure canvas is redrawn first (which will callback to _redraw with a proper event defined)
self._canvas.draw()
else:
# Called from draw_event callback
img = np.frombuffer(
self._canvas.buffer_rgba(),
dtype=np.uint8,
) # Store figure data in numpy array
w, h = self._canvas.get_width_height()
img_arr = img.reshape([h, w, 4])
img_data = pyvista.Texture(img_arr).to_image() # Convert to vtkImageData
self.SetImage(img_data)
def _render_event(self, *args, plotter_render=False, **kwargs):
# Redraw figure when geometry has changed (self._resize call
# already updated figure dimensions in that case) OR the
# plotter's render method was called and redraw_on_render is
# enabled.
if (plotter_render and self.redraw_on_render) or (not plotter_render and self._resize()):
self._redraw()
@property
def _geometry(self):
r_w, r_h = self._renderer.GetSize()
t_w = self._size[0] * r_w
t_h = self._size[1] * r_h
return (*self.position, t_w, t_h)
@_geometry.setter
def _geometry(self, _):
raise AttributeError(f'Cannot set the geometry of {type(self).__class__}')
# Below code can be used to customize the chart's background without a _ChartBackground instance
# @property
# def background_color(self): # numpydoc ignore=RT01
# return self._bg_color
#
# @background_color.setter
# def background_color(self, val): # numpydoc ignore=GL08
# color = Color(val).int_rgba if val is not None else [1.0, 1.0, 1.0, 1.0]
# opacity = color[3]
# self._bg_color = color
# self._fig.patch.set_color(color[:3])
# self._fig.patch.set_alpha(opacity)
# for ax in self._fig.axes:
# ax.patch.set_alpha(0 if opacity < 1 else 1) # Make axes fully transparent if opacity is lower than 1
@property
def position(self): # numpydoc ignore=RT01
"""Chart position w.r.t the bottom left corner (in pixels)."""
return self.GetPosition()
@position.setter
def position(self, val): # numpydoc ignore=GL08
if len(val) != 2:
raise ValueError(f'Invalid position {val}, must be length 2.')
self.SetPosition(*val)
@property
def title(self): # numpydoc ignore=RT01
"""Return or set the chart's title.
Examples
--------
Create a matplotlib chart with title 'My Chart'.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import matplotlib.pyplot as plt
>>> f, ax = plt.subplots()
>>> _ = ax.plot([0, 1, 2], [2, 1, 3])
>>> chart = pv.ChartMPL(f)
>>> chart.title = 'My Chart'
>>> chart.show()
"""
return self._fig._suptitle.get_text()
@title.setter
def title(self, val): # numpydoc ignore=GL08
self._fig.suptitle(val)
@property
def legend_visible(self): # numpydoc ignore=RT01
"""Return or set the visibility of the chart's legend.
Examples
--------
Create a matplotlib chart with custom labels and show the legend.
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> import matplotlib.pyplot as plt
>>> f, ax = plt.subplots()
>>> _ = ax.plot([0, 1, 2], [2, 1, 3], label="Line")
>>> _ = ax.scatter([0, 1, 2], [3, 2, 1], label="Points")
>>> chart = pv.ChartMPL(f)
>>> chart.legend_visible = True
>>> chart.show()
Hide the legend.
>>> chart.legend_visible = False
>>> chart.show()
"""
legend = self._fig.axes[0].get_legend()
return False if legend is None else legend.get_visible()
@legend_visible.setter
def legend_visible(self, val): # numpydoc ignore=GL08
legend = self._fig.axes[0].get_legend()
if legend is None:
legend = self._fig.axes[0].legend()
legend.set_visible(val)
class Charts:
"""Collection of charts for a renderer.
Users should typically not directly create new instances of this
class, but use the dedicated ``Plotter.add_chart`` method.
Parameters
----------
renderer : pyvista.Renderer
The renderer to which the charts should be added.
"""
def __init__(self, renderer):
"""Create a new collection of charts for the given renderer."""
self._charts = []
# Postpone creation of scene and actor objects until they are
# needed.
self._scene = None
self._actor = None
# a weakref.proxy would be nice here, but that doesn't play
# nicely with SetRenderer, so instead we'll use a weak reference
# plus a property to call it
self.__renderer = weakref.ref(renderer)
@property
def _renderer(self):
"""Return the weakly dereferenced renderer, maybe None."""
return self.__renderer()
def _setup_scene(self):
"""Set up a new context scene and actor for these charts."""
self._scene = _vtk.vtkContextScene()
self._actor = _vtk.vtkContextActor()
self._actor.SetScene(self._scene)
self._renderer.AddActor(self._actor)
self._scene.SetRenderer(self._renderer)
def deep_clean(self):
"""Remove all references to the chart objects and internal objects."""
if self._scene is not None:
charts = [*self._charts] # Make a copy, as this list will be modified by remove_chart
for chart in charts:
self.remove_chart(chart)
if self._renderer is not None:
self._renderer.RemoveActor(self._actor)
self._scene = None
self._actor = None
def add_chart(self, *charts):
"""Add charts to the collection.
Parameters
----------
*charts : Chart2D | Chart3D
One or more chart objects to be added to the collection.
"""
if self._scene is None:
self._setup_scene()
for chart in charts:
self._charts.append(chart)
if chart._background is not None:
self._scene.AddItem(chart._background)
self._scene.AddItem(chart)
chart._interactive = False # Charts are not interactive by default
def set_interaction(self, interactive, toggle=False):
"""Set or toggle interaction with charts for this renderer.
Interaction with other charts in this renderer is disabled when ``toggle``
is ``False``.
Parameters
----------
interactive : bool | Chart | int | list[Chart] | list[int]
Following parameter values are accepted:
* A boolean to enable (``True``) or disable (``False``) interaction
with all charts.
* The chart or its index to enable interaction with. Interaction
with multiple charts can be enabled by passing a list of charts
or indices.
toggle : bool, default: False
Instead of enabling interaction with the provided chart(s), interaction
with the provided chart(s) is toggled. Only applicable when ``interactive``
is not a boolean.
Returns
-------
list of Chart
The list of all interactive charts for this renderer.
"""
if isinstance(interactive, bool):
# Disable toggle and convert to list of charts
toggle = False
interactive = self._charts if interactive else []
if not isinstance(interactive, list):
# Convert single chart parameter to list
interactive = [interactive]
# Convert to list of Charts
charts = [
self._charts[coi] if isinstance(coi, int) and 0 <= coi < len(self) else coi
for coi in interactive
]
interactive_charts = []
for chart in self._charts:
# Determine whether to enable interaction with the current chart.
if toggle:
enable = not chart._interactive if chart in charts else chart._interactive
else:
enable = chart in charts
chart._interactive = enable
if enable:
interactive_charts.append(chart)
return interactive_charts
def remove_chart(self, chart_or_index):
"""Remove a chart from the collection.
Parameters
----------
chart_or_index : int or Chart
The index or the chart object to be removed from the collection.
Raises
------
ValueError
If the specified chart index is not present in the charts collection.
"""
chart = self._charts[chart_or_index] if isinstance(chart_or_index, int) else chart_or_index
if chart not in self._charts: # pragma: no cover
raise ValueError('chart_index not present in charts collection.')
self._charts.remove(chart)
self._scene.RemoveItem(chart)
if chart._background is not None:
self._scene.RemoveItem(chart._background)
def get_charts_by_pos(self, pos):
"""Retrieve visible charts indicated by the given mouse position.
Parameters
----------
pos : sequence[float]
Tuple containing the mouse position.
Returns
-------
list of Chart
Visible charts indicated by the given mouse position.
"""
return [chart for chart in self._charts if chart.visible and chart._is_within(pos)]
def __getitem__(self, index) -> Chart:
"""Return a chart based on an index."""
return self._charts[index]
def __len__(self):
"""Return number of charts."""
return len(self._charts)
def __iter__(self):
"""Return an iterable of charts."""
yield from self._charts
def __del__(self):
"""Clean up before being destroyed."""
self.deep_clean()
|