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
|
"""Module containing pyvista implementation of vtkRenderer."""
from __future__ import annotations
from collections.abc import Iterable
import contextlib
from functools import partial
from functools import wraps
from typing import ClassVar
from typing import Sequence
from typing import cast
import warnings
import numpy as np
import pyvista
from pyvista import MAX_N_COLOR_BARS
from pyvista import vtk_version_info
from pyvista.core._typing_core import BoundsLike
from pyvista.core.errors import PyVistaDeprecationWarning
from pyvista.core.utilities.helpers import wrap
from pyvista.core.utilities.misc import assert_empty_kwargs
from pyvista.core.utilities.misc import try_callback
from . import _vtk
from .actor import Actor
from .camera import Camera
from .charts import Charts
from .colors import Color
from .colors import get_cycler
from .errors import InvalidCameraError
from .helpers import view_vectors
from .mapper import DataSetMapper
from .render_passes import RenderPasses
from .tools import create_axes_marker
from .tools import create_axes_orientation_box
from .tools import create_north_arrow
from .tools import parse_font_family
from .utilities.gl_checks import check_depth_peeling
from .utilities.gl_checks import uses_egl
ACTOR_LOC_MAP = [
'upper right',
'upper left',
'lower left',
'lower right',
'center left',
'center right',
'lower center',
'upper center',
'center',
]
def map_loc_to_pos(loc, size, border=0.05):
"""Map location and size to a VTK position and position2.
Parameters
----------
loc : str
Location of the actor. Can be a string with values such as 'right',
'left', 'upper', or 'lower'.
size : Sequence of length 2
Size of the actor. It must be a list of length 2.
border : float, default: 0.05
Size of the border around the actor.
Returns
-------
tuple
The VTK position and position2 coordinates. Tuple of the form (x, y, size).
Raises
------
ValueError
If the ``size`` parameter is not a list of length 2.
"""
if not isinstance(size, Sequence) or len(size) != 2:
raise ValueError(f'`size` must be a list of length 2. Passed value is {size}')
if 'right' in loc:
x = 1 - size[1] - border
elif 'left' in loc:
x = border
else:
x = 0.5 - size[1] / 2
if 'upper' in loc:
y = 1 - size[1] - border
elif 'lower' in loc:
y = border
else:
y = 0.5 - size[1] / 2
return x, y, size
def make_legend_face(face):
"""
Create the legend face based on the given face.
Parameters
----------
face : str | pyvista.PolyData | NoneType
The shape of the legend face. Valid strings are:
'-', 'line', '^', 'triangle', 'o', 'circle', 'r', 'rectangle', 'none'.
Also accepts ``None`` or instances of ``pyvista.PolyData``.
Returns
-------
pyvista.PolyData
The legend face as a PolyData object.
Raises
------
ValueError
If the provided face value is invalid.
"""
if face is None or face == "none":
legendface = pyvista.PolyData([0.0, 0.0, 0.0], faces=np.empty(0, dtype=int))
elif face in ["-", "line"]:
legendface = _line_for_legend()
elif face in ["^", "triangle"]:
legendface = pyvista.Triangle()
elif face in ["o", "circle"]:
legendface = pyvista.Circle()
elif face in ["r", "rectangle"]:
legendface = pyvista.Rectangle()
elif isinstance(face, pyvista.PolyData):
legendface = face
else:
raise ValueError(
f'Invalid face "{face}". Must be one of the following:\n'
'\t"triangle"\n'
'\t"circle"\n'
'\t"rectangle"\n'
'\t"none"\n'
'\tpyvista.PolyData',
)
return legendface
def scale_point(camera, point, invert=False):
"""Scale a point using the camera's transform matrix.
Parameters
----------
camera : Camera
The camera who's matrix to use.
point : sequence[float]
Scale point coordinates.
invert : bool, default: False
If ``True``, invert the matrix to transform the point out of
the camera's transformed space. Default is ``False`` to
transform a point from world coordinates to the camera's
transformed space.
Returns
-------
tuple
Scaling of the camera in ``(x, y, z)``.
"""
if invert:
mtx = _vtk.vtkMatrix4x4()
mtx.DeepCopy(camera.GetModelTransformMatrix())
mtx.Invert()
else:
mtx = camera.GetModelTransformMatrix()
scaled = mtx.MultiplyDoublePoint((point[0], point[1], point[2], 0.0))
return (scaled[0], scaled[1], scaled[2])
class CameraPosition:
"""Container to hold camera location attributes.
Parameters
----------
position : sequence[float]
Position of the camera.
focal_point : sequence[float]
The focal point of the camera.
viewup : sequence[float]
View up of the camera.
"""
def __init__(self, position, focal_point, viewup):
"""Initialize a new camera position descriptor."""
self._position = position
self._focal_point = focal_point
self._viewup = viewup
def to_list(self):
"""Convert to a list of the position, focal point, and viewup.
Returns
-------
list
List of the position, focal point, and view up of the camera.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.camera_position.to_list()
[(0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
"""
return [self._position, self._focal_point, self._viewup]
def __repr__(self):
"""List representation method."""
return "[{},\n {},\n {}]".format(*self.to_list())
def __getitem__(self, index):
"""Fetch a component by index location like a list."""
return self.to_list()[index]
def __eq__(self, other):
"""Comparison operator to act on list version of CameraPosition object."""
if isinstance(other, CameraPosition):
return self.to_list() == other.to_list()
return self.to_list() == other
@property
def position(self): # numpydoc ignore=RT01
"""Location of the camera in world coordinates."""
return self._position
@position.setter
def position(self, value): # numpydoc ignore=GL08
self._position = value
@property
def focal_point(self): # numpydoc ignore=RT01
"""Location of the camera's focus in world coordinates."""
return self._focal_point
@focal_point.setter
def focal_point(self, value): # numpydoc ignore=GL08
self._focal_point = value
@property
def viewup(self): # numpydoc ignore=RT01
"""Viewup vector of the camera."""
return self._viewup
@viewup.setter
def viewup(self, value): # numpydoc ignore=GL08
self._viewup = value
class Renderer(_vtk.vtkOpenGLRenderer):
"""Renderer class."""
# map camera_position string to an attribute
CAMERA_STR_ATTR_MAP: ClassVar[dict[str, str]] = {
'xy': 'view_xy',
'xz': 'view_xz',
'yz': 'view_yz',
'yx': 'view_yx',
'zx': 'view_zx',
'zy': 'view_zy',
'iso': 'view_isometric',
}
def __init__(
self,
parent,
border=True,
border_color='w',
border_width=2.0,
): # numpydoc ignore=PR01,RT01
"""Initialize the renderer."""
super().__init__()
self._actors = {}
self.parent = parent # weakref.proxy to the plotter from Renderers
self._theme = parent.theme
self.bounding_box_actor = None
self.scale = [1.0, 1.0, 1.0]
self.AutomaticLightCreationOff()
self._labels = {} # tracks labeled actors
self._legend = None
self._floor = None
self._floors = []
self._floor_kwargs = []
# this keeps track of lights added manually to prevent garbage collection
self._lights = []
self._camera = Camera(self)
self.SetActiveCamera(self._camera)
self._empty_str = None # used to track reference to a vtkStringArray
self._shadow_pass = None
self._render_passes = RenderPasses(self)
self.cube_axes_actor = None
# This is a private variable to keep track of how many colorbars exist
# This allows us to keep adding colorbars without overlapping
self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
self._scalar_bar_slot_lookup = {}
self._charts = None
self._border_actor = None
if border:
self.add_border(border_color, border_width)
self.set_color_cycler(self._theme.color_cycler)
@property
def camera_set(self) -> bool: # numpydoc ignore=RT01
"""Get or set whether this camera has been configured."""
if self.camera is None: # pragma: no cover
return False
return self.camera.is_set
@camera_set.setter
def camera_set(self, is_set: bool): # numpydoc ignore=GL08
self.camera.is_set = is_set
def set_color_cycler(self, color_cycler):
"""Set or reset this renderer's color cycler.
This color cycler is iterated over by each sequential :class:`add_mesh() <pyvista.Plotter.add_mesh>`
call to set the default color of the dataset being plotted.
When setting, the value must be either a list of color-like objects,
or a cycler of color-like objects. If the value passed is a single
string, it must be one of:
* ``'default'`` - Use the default color cycler (matches matplotlib's default)
* ``'matplotlib`` - Dynamically get matplotlib's current theme's color cycler.
* ``'all'`` - Cycle through all of the available colors in ``pyvista.plotting.colors.hexcolors``
Setting to ``None`` will disable the use of the color cycler on this
renderer.
Parameters
----------
color_cycler : str | cycler.Cycler | sequence[ColorLike]
The colors to cycle through.
Examples
--------
Set the default color cycler to iterate through red, green, and blue.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.renderer.set_color_cycler(['red', 'green', 'blue'])
>>> _ = pl.add_mesh(pv.Cone(center=(0, 0, 0))) # red
>>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0))) # green
>>> _ = pl.add_mesh(pv.Sphere(center=(1, 1, 0))) # blue
>>> _ = pl.add_mesh(pv.Cylinder(center=(0, 1, 0))) # red again
>>> pl.show()
"""
cycler = get_cycler(color_cycler)
if cycler is not None:
# Color cycler - call object to generate `cycle` instance
self._color_cycle = cycler()
else:
self._color_cycle = None
@property
def next_color(self): # numpydoc ignore=RT01
"""Return next color from this renderer's color cycler."""
if self._color_cycle is None:
return self._theme.color
return next(self._color_cycle)['color']
@property
def camera_position(self): # numpydoc ignore=RT01
"""Return or set the camera position of active render window.
Returns
-------
pyvista.CameraPosition
Camera position.
"""
return CameraPosition(
scale_point(self.camera, self.camera.position, invert=True),
scale_point(self.camera, self.camera.focal_point, invert=True),
self.camera.up,
)
@camera_position.setter
def camera_position(self, camera_location): # numpydoc ignore=GL08
if camera_location is None:
return
elif isinstance(camera_location, str):
camera_location = camera_location.lower()
if camera_location not in self.CAMERA_STR_ATTR_MAP:
raise InvalidCameraError(
'Invalid view direction. '
'Use one of the following:\n '
f'{", ".join(self.CAMERA_STR_ATTR_MAP)}',
)
getattr(self, self.CAMERA_STR_ATTR_MAP[camera_location])()
elif isinstance(camera_location[0], (int, float)):
if len(camera_location) != 3:
raise InvalidCameraError
self.view_vector(camera_location)
else:
# check if a valid camera position
if not isinstance(camera_location, CameraPosition):
if not len(camera_location) == 3 or any(len(item) != 3 for item in camera_location):
raise InvalidCameraError
# everything is set explicitly
self.camera.position = scale_point(self.camera, camera_location[0], invert=False)
self.camera.focal_point = scale_point(self.camera, camera_location[1], invert=False)
self.camera.up = camera_location[2]
# reset clipping range
self.reset_camera_clipping_range()
self.camera_set = True
self.Modified()
def reset_camera_clipping_range(self):
"""Reset the camera clipping range based on the bounds of the visible actors.
This ensures that no props are cut off
"""
self.ResetCameraClippingRange()
@property
def camera(self): # numpydoc ignore=RT01
"""Return the active camera for the rendering scene."""
return self._camera
@camera.setter
def camera(self, source): # numpydoc ignore=GL08
self._camera = source
self.SetActiveCamera(self._camera)
self.camera_position = CameraPosition(
scale_point(source, source.position, invert=True),
scale_point(source, source.focal_point, invert=True),
source.up,
)
self.Modified()
self.camera_set = True
@property
def bounds(self) -> BoundsLike: # numpydoc ignore=RT01
"""Return the bounds of all actors present in the rendering window."""
the_bounds = np.array([np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf])
def _update_bounds(bounds):
def update_axis(ax):
if bounds[ax * 2] < the_bounds[ax * 2]:
the_bounds[ax * 2] = bounds[ax * 2]
if bounds[ax * 2 + 1] > the_bounds[ax * 2 + 1]:
the_bounds[ax * 2 + 1] = bounds[ax * 2 + 1]
for ax in range(3):
update_axis(ax)
for actor in self._actors.values():
if isinstance(actor, (_vtk.vtkCubeAxesActor, _vtk.vtkLightActor)):
continue
if (
hasattr(actor, 'GetBounds')
and actor.GetBounds() is not None
and id(actor) != id(self.bounding_box_actor)
):
_update_bounds(actor.GetBounds())
if np.any(np.abs(the_bounds)):
the_bounds[the_bounds == np.inf] = -1.0
the_bounds[the_bounds == -np.inf] = 1.0
return cast(BoundsLike, tuple(the_bounds.tolist()))
@property
def length(self): # numpydoc ignore=RT01
"""Return the length of the diagonal of the bounding box of the scene.
Returns
-------
float
Length of the diagonal of the bounding box.
"""
return pyvista.Box(self.bounds).length
@property
def center(self) -> tuple[float, float, float]:
"""Return the center of the bounding box around all data present in the scene.
Returns
-------
tuple[float, float, float]
Cartesian coordinates of the center.
"""
bounds = self.bounds
x = (bounds[1] + bounds[0]) / 2
y = (bounds[3] + bounds[2]) / 2
z = (bounds[5] + bounds[4]) / 2
return x, y, z
@property
def background_color(self): # numpydoc ignore=RT01
"""Return the background color of this renderer."""
return Color(self.GetBackground())
@background_color.setter
def background_color(self, color): # numpydoc ignore=GL08
self.set_background(color)
self.Modified()
def _before_render_event(self, *args, **kwargs):
"""Notify all charts about render event."""
for chart in self._charts:
chart._render_event(*args, **kwargs)
def enable_depth_peeling(self, number_of_peels=None, occlusion_ratio=None):
"""Enable depth peeling to improve rendering of translucent geometry.
Parameters
----------
number_of_peels : int, optional
The maximum number of peeling layers. Initial value is 4
and is set in the ``pyvista.global_theme``. A special value of
0 means no maximum limit. It has to be a positive value.
occlusion_ratio : float, optional
The threshold under which the depth peeling algorithm
stops to iterate over peel layers. This is the ratio of
the number of pixels that have been touched by the last
layer over the total number of pixels of the viewport
area. Initial value is 0.0, meaning rendering has to be
exact. Greater values may speed up the rendering with
small impact on the quality.
Returns
-------
bool
If depth peeling is supported.
"""
if number_of_peels is None:
number_of_peels = self._theme.depth_peeling.number_of_peels
if occlusion_ratio is None:
occlusion_ratio = self._theme.depth_peeling.occlusion_ratio
depth_peeling_supported = check_depth_peeling(number_of_peels, occlusion_ratio)
if depth_peeling_supported:
self.SetUseDepthPeeling(True)
self.SetMaximumNumberOfPeels(number_of_peels)
self.SetOcclusionRatio(occlusion_ratio)
self.Modified()
return depth_peeling_supported
def disable_depth_peeling(self):
"""Disable depth peeling."""
self.SetUseDepthPeeling(False)
self.Modified()
def enable_anti_aliasing(self, aa_type='ssaa'):
"""Enable anti-aliasing.
Parameters
----------
aa_type : str, default: 'ssaa'
Anti-aliasing type. Either ``"fxaa"`` or ``"ssaa"``.
"""
if not isinstance(aa_type, str):
raise TypeError(f'`aa_type` must be a string, not {type(aa_type)}')
aa_type = aa_type.lower()
if aa_type == 'fxaa':
if uses_egl(): # pragma: no cover
# only display the warning when not building documentation
if not pyvista.BUILDING_GALLERY:
warnings.warn(
"VTK compiled with OSMesa/EGL does not properly support "
"FXAA anti-aliasing and SSAA will be used instead.",
)
self._render_passes.enable_ssaa_pass()
return
self._enable_fxaa()
elif aa_type == 'ssaa':
self._render_passes.enable_ssaa_pass()
else:
raise ValueError(f'Invalid `aa_type` "{aa_type}". Should be either "fxaa" or "ssaa"')
def disable_anti_aliasing(self):
"""Disable all anti-aliasing."""
self._render_passes.disable_ssaa_pass()
self.SetUseFXAA(False)
self.Modified()
def _enable_fxaa(self):
"""Enable FXAA anti-aliasing."""
self.SetUseFXAA(True)
self.Modified()
def _disable_fxaa(self):
"""Disable FXAA anti-aliasing."""
self.SetUseFXAA(False)
self.Modified()
def add_border(self, color='white', width=2.0):
"""Add borders around the frame.
Parameters
----------
color : ColorLike, default: "white"
Color of the border.
width : float, default: 2.0
Width of the border.
Returns
-------
vtk.vtkActor2D
Border actor.
"""
points = np.array([[1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
lines = np.array([[2, 0, 1], [2, 1, 2], [2, 2, 3], [2, 3, 0]]).ravel()
poly = pyvista.PolyData()
poly.points = points
poly.lines = lines
coordinate = _vtk.vtkCoordinate()
coordinate.SetCoordinateSystemToNormalizedViewport()
mapper = _vtk.vtkPolyDataMapper2D()
mapper.SetInputData(poly)
mapper.SetTransformCoordinate(coordinate)
actor = _vtk.vtkActor2D()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(Color(color).float_rgb)
actor.GetProperty().SetLineWidth(width)
self.AddViewProp(actor)
self.Modified()
self._border_actor = actor
return actor
@property
def has_border(self): # numpydoc ignore=RT01
"""Return if the renderer has a border."""
return self._border_actor is not None
@property
def border_width(self): # numpydoc ignore=RT01
"""Return the border width."""
if self.has_border:
return self._border_actor.GetProperty().GetLineWidth()
return 0
@property
def border_color(self): # numpydoc ignore=RT01
"""Return the border color."""
if self.has_border:
return Color(self._border_actor.GetProperty().GetColor())
return None
def add_chart(self, chart, *charts):
"""Add a chart to this renderer.
Parameters
----------
chart : Chart
Chart to add to renderer.
*charts : Chart
Charts to add to renderer.
Examples
--------
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.plot(range(10), range(10))
>>> pl = pv.Plotter()
>>> pl.add_chart(chart)
>>> pl.show()
"""
if _vtk.vtkRenderingContextOpenGL2 is None: # pragma: no cover
from pyvista.core.errors import VTKVersionError
raise VTKVersionError(
"VTK is missing vtkRenderingContextOpenGL2. Try installing VTK v9.1.0 or newer.",
)
# lazy instantiation here to avoid creating the charts object unless needed.
if self._charts is None:
self._charts = Charts(self)
self.AddObserver("StartEvent", partial(try_callback, self._before_render_event))
self._charts.add_chart(chart, *charts)
@property
def has_charts(self): # numpydoc ignore=RT01
"""Return whether this renderer has charts."""
return self._charts is not None and len(self._charts) > 0
def get_charts(self): # numpydoc ignore=RT01
"""Return a list of all charts in this renderer.
Examples
--------
.. pyvista-plot::
:force_static:
>>> import pyvista as pv
>>> chart = pv.Chart2D()
>>> _ = chart.line([1, 2, 3], [0, 1, 0])
>>> pl = pv.Plotter()
>>> pl.add_chart(chart)
>>> chart is pl.renderer.get_charts()[0]
True
"""
return [*self._charts] if self.has_charts else []
@wraps(Charts.set_interaction)
def set_chart_interaction(self, interactive, toggle=False): # numpydoc ignore=PR01,RT01
"""Wrap ``Charts.set_interaction``."""
return self._charts.set_interaction(interactive, toggle) if self.has_charts else []
@wraps(Charts.get_charts_by_pos)
def _get_charts_by_pos(self, pos):
"""Wrap ``Charts.get_charts_by_pos``."""
return self._charts.get_charts_by_pos(pos) if self.has_charts else []
def remove_chart(self, chart_or_index):
"""Remove a chart from this renderer.
Parameters
----------
chart_or_index : Chart or int
Either the chart to remove from this renderer or its index in the collection of charts.
Examples
--------
First define a function to add two charts to a renderer.
>>> import pyvista as pv
>>> def plotter_with_charts():
... pl = pv.Plotter()
... pl.background_color = 'w'
... chart_left = pv.Chart2D(size=(0.5, 1))
... _ = chart_left.line([0, 1, 2], [2, 1, 3])
... pl.add_chart(chart_left)
... chart_right = pv.Chart2D(size=(0.5, 1), loc=(0.5, 0))
... _ = chart_right.line([0, 1, 2], [3, 1, 2])
... pl.add_chart(chart_right)
... return pl, chart_left, chart_right
...
>>> pl, *_ = plotter_with_charts()
>>> pl.show()
Now reconstruct the same plotter but remove the right chart by index.
>>> pl, *_ = plotter_with_charts()
>>> pl.remove_chart(1)
>>> pl.show()
Finally, remove the left chart by reference.
>>> pl, chart_left, chart_right = plotter_with_charts()
>>> pl.remove_chart(chart_left)
>>> pl.show()
"""
if self.has_charts:
self._charts.remove_chart(chart_or_index)
@property
def actors(self): # numpydoc ignore=RT01
"""Return a dictionary of actors assigned to this renderer."""
return self._actors
def add_actor(
self,
actor,
reset_camera=False,
name=None,
culling=False,
pickable=True,
render=True,
remove_existing_actor=True,
):
"""Add an actor to render window.
Creates an actor if input is a mapper.
Parameters
----------
actor : vtk.vtkActor | vtk.vtkMapper | pyvista.Actor
The actor to be added. Can be either ``vtkActor`` or ``vtkMapper``.
reset_camera : bool, default: False
Resets the camera when ``True``.
name : str, optional
Name to assign to the actor. Defaults to the memory address.
culling : str, default: False
Does not render faces that are culled. Options are
``'front'`` or ``'back'``. This can be helpful for dense
surface meshes, especially when edges are visible, but can
cause flat meshes to be partially displayed.
pickable : bool, default: True
Whether to allow this actor to be pickable within the
render window.
render : bool, default: True
If the render window is being shown, trigger a render
after adding the actor.
remove_existing_actor : bool, default: True
Removes any existing actor if the named actor ``name`` is already
present.
Returns
-------
actor : vtk.vtkActor or pyvista.Actor
The actor.
actor_properties : vtk.Properties
Actor properties.
"""
# Remove actor by that name if present
rv = None
if name and remove_existing_actor:
rv = self.remove_actor(name, reset_camera=False, render=False)
if isinstance(actor, _vtk.vtkMapper):
actor = Actor(mapper=actor, name=name)
if isinstance(actor, Actor) and name:
# WARNING: this will override the name if already set on Actor
actor.name = name
if name is None:
# Fallback for non-wrapped actors
# e.g., vtkScalarBarActor
name = actor.name if isinstance(actor, Actor) else actor.GetAddressAsString("")
actor.SetPickable(pickable)
# Apply this renderer's scale to the actor (which can be further scaled)
if hasattr(actor, 'SetScale'):
actor.SetScale(np.array(actor.GetScale()) * np.array(self.scale))
self.AddActor(actor) # must add actor before resetting camera
self._actors[name] = actor
if reset_camera or not self.camera_set and reset_camera is None and not rv:
self.reset_camera(render)
elif render:
self.parent.render()
self.update_bounds_axes()
if isinstance(culling, str):
culling = culling.lower()
if culling:
if culling in [True, 'back', 'backface', 'b']:
with contextlib.suppress(AttributeError):
actor.GetProperty().BackfaceCullingOn()
elif culling in ['front', 'frontface', 'f']:
with contextlib.suppress(AttributeError):
actor.GetProperty().FrontfaceCullingOn()
else:
raise ValueError(f'Culling option ({culling}) not understood.')
self.Modified()
prop = None
if hasattr(actor, 'GetProperty'):
prop = actor.GetProperty()
return actor, prop
def add_axes_at_origin(
self,
x_color=None,
y_color=None,
z_color=None,
xlabel='X',
ylabel='Y',
zlabel='Z',
line_width=2,
labels_off=False,
):
"""Add axes actor at origin.
Parameters
----------
x_color : ColorLike, optional
The color of the x axes arrow.
y_color : ColorLike, optional
The color of the y axes arrow.
z_color : ColorLike, optional
The color of the z axes arrow.
xlabel : str, default: "X"
The label of the x axes arrow.
ylabel : str, default: "Y"
The label of the y axes arrow.
zlabel : str, default: "Z"
The label of the z axes arrow.
line_width : int, default: 2
Width of the arrows.
labels_off : bool, default: False
Disables the label text when ``True``.
Returns
-------
vtk.vtkAxesActor
Actor of the axes.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere(center=(2, 0, 0)), color='r')
>>> _ = pl.add_mesh(pv.Sphere(center=(0, 2, 0)), color='g')
>>> _ = pl.add_mesh(pv.Sphere(center=(0, 0, 2)), color='b')
>>> _ = pl.add_axes_at_origin()
>>> pl.show()
"""
self._marker_actor = create_axes_marker(
line_width=line_width,
x_color=x_color,
y_color=y_color,
z_color=z_color,
xlabel=xlabel,
ylabel=ylabel,
zlabel=zlabel,
labels_off=labels_off,
)
self.AddActor(self._marker_actor)
memory_address = self._marker_actor.GetAddressAsString("")
self._actors[memory_address] = self._marker_actor
self.Modified()
return self._marker_actor
def add_orientation_widget(
self,
actor,
interactive=None,
color=None,
opacity=1.0,
viewport=None,
):
"""Use the given actor in an orientation marker widget.
Color and opacity are only valid arguments if a mesh is passed.
Parameters
----------
actor : vtk.vtkActor | pyvista.DataSet
The mesh or actor to use as the marker.
interactive : bool, optional
Control if the orientation widget is interactive. By
default uses the value from
:attr:`pyvista.global_theme.interactive
<pyvista.plotting.themes.Theme.interactive>`.
color : ColorLike, optional
The color of the actor. This only applies if ``actor`` is
a :class:`pyvista.DataSet`.
opacity : int | float, default: 1.0
Opacity of the marker.
viewport : sequence[float], optional
Viewport ``(xstart, ystart, xend, yend)`` of the widget.
Returns
-------
vtk.vtkOrientationMarkerWidget
Orientation marker widget.
See Also
--------
add_axes
Add an axes orientation widget.
Examples
--------
Use an Arrow as the orientation widget.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Cube(), show_edges=True)
>>> widget = pl.add_orientation_widget(pv.Arrow(), color='r')
>>> pl.show()
"""
if isinstance(actor, pyvista.DataSet):
mapper = _vtk.vtkDataSetMapper()
mesh = actor.copy()
mesh.clear_data()
mapper.SetInputData(mesh)
actor = pyvista.Actor(mapper=mapper)
if color is not None:
actor.prop.color = color
actor.prop.opacity = opacity
if hasattr(self, 'axes_widget'):
# Delete the old one
self.axes_widget.EnabledOff()
self.Modified()
del self.axes_widget
if interactive is None:
interactive = self._theme.interactive
self.axes_widget = _vtk.vtkOrientationMarkerWidget()
self.axes_widget.SetOrientationMarker(actor)
if hasattr(self.parent, 'iren'):
self.axes_widget.SetInteractor(self.parent.iren.interactor)
self.axes_widget.SetEnabled(1)
self.axes_widget.SetInteractive(interactive)
self.axes_widget.SetCurrentRenderer(self)
if viewport is not None:
self.axes_widget.SetViewport(viewport)
self.Modified()
return self.axes_widget
def add_axes(
self,
interactive=None,
line_width=2,
color=None,
x_color=None,
y_color=None,
z_color=None,
xlabel='X',
ylabel='Y',
zlabel='Z',
labels_off=False,
box=None,
box_args=None,
viewport=(0, 0, 0.2, 0.2),
**kwargs,
):
"""Add an interactive axes widget in the bottom left corner.
Parameters
----------
interactive : bool, optional
Enable this orientation widget to be moved by the user.
line_width : int, default: 2
The width of the marker lines.
color : ColorLike, optional
Color of the labels.
x_color : ColorLike, optional
Color used for the x-axis arrow. Defaults to theme axes parameters.
y_color : ColorLike, optional
Color used for the y-axis arrow. Defaults to theme axes parameters.
z_color : ColorLike, optional
Color used for the z-axis arrow. Defaults to theme axes parameters.
xlabel : str, default: "X"
Text used for the x-axis.
ylabel : str, default: "Y"
Text used for the y-axis.
zlabel : str, default: "Z"
Text used for the z-axis.
labels_off : bool, default: false
Enable or disable the text labels for the axes.
box : bool, optional
Show a box orientation marker. Use ``box_args`` to adjust.
See :func:`pyvista.create_axes_orientation_box` for details.
.. deprecated:: 0.43.0
The is deprecated. Use `add_box_axes` method instead.
box_args : dict, optional
Parameters for the orientation box widget when
``box=True``. See the parameters of
:func:`pyvista.create_axes_orientation_box`.
viewport : sequence[float], default: (0, 0, 0.2, 0.2)
Viewport ``(xstart, ystart, xend, yend)`` of the widget.
**kwargs : dict, optional
Used for passing parameters for the orientation marker
widget. See the parameters of :func:`pyvista.create_axes_marker`.
Returns
-------
AxesActor
Axes actor of the added widget.
See Also
--------
show_axes
Similar method which calls :func:`add_axes` without any parameters.
add_axes_at_origin
Add an :class:`pyvista.AxesActor` to the origin of a scene.
Examples
--------
Show axes without labels and with thick lines.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Box(), show_edges=True)
>>> _ = pl.add_axes(line_width=5, labels_off=True)
>>> pl.show()
Specify more parameters for the axes marker.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Box(), show_edges=True)
>>> _ = pl.add_axes(
... line_width=5,
... cone_radius=0.6,
... shaft_length=0.7,
... tip_length=0.3,
... ambient=0.5,
... label_size=(0.4, 0.16),
... )
>>> pl.show()
"""
if interactive is None:
interactive = self._theme.interactive
if hasattr(self, 'axes_widget'):
self.axes_widget.EnabledOff()
self.Modified()
del self.axes_widget
if box is None:
box = self._theme.axes.box
if box:
warnings.warn(
"`box` is deprecated. Use `add_box_axes` or `add_color_box_axes` method instead.",
PyVistaDeprecationWarning,
)
if box_args is None:
box_args = {}
self.axes_actor = create_axes_orientation_box(
label_color=color,
line_width=line_width,
x_color=x_color,
y_color=y_color,
z_color=z_color,
xlabel=xlabel,
ylabel=ylabel,
zlabel=zlabel,
labels_off=labels_off,
**box_args,
)
else:
self.axes_actor = create_axes_marker(
label_color=color,
line_width=line_width,
x_color=x_color,
y_color=y_color,
z_color=z_color,
xlabel=xlabel,
ylabel=ylabel,
zlabel=zlabel,
labels_off=labels_off,
**kwargs,
)
axes_widget = self.add_orientation_widget(
self.axes_actor,
interactive=interactive,
color=None,
)
axes_widget.SetViewport(viewport)
return self.axes_actor
def add_north_arrow_widget(
self,
interactive=None,
color="#4169E1",
opacity=1.0,
line_width=2,
edge_color=None,
lighting=False,
viewport=(0, 0, 0.1, 0.1),
):
"""Add a geographic north arrow to the scene.
.. versionadded:: 0.44.0
Parameters
----------
interactive : bool, optional
Control if the orientation widget is interactive. By
default uses the value from
:attr:`pyvista.global_theme.interactive
<pyvista.plotting.themes.Theme.interactive>`.
color : ColorLike, optional
Color of the north arrow.
opacity : float, optional
Opacity of the north arrow.
line_width : float, optional
Width of the north edge arrow lines.
edge_color : ColorLike, optional
Color of the edges.
lighting : bool, optional
Enable or disable lighting on north arrow.
viewport : sequence[float], default: (0, 0, 0.1, 0.1)
Viewport ``(xstart, ystart, xend, yend)`` of the widget.
Returns
-------
vtk.vtkOrientationMarkerWidget
Orientation marker widget.
Examples
--------
Use an north arrow as the orientation widget.
>>> import pyvista as pv
>>> from pyvista import examples
>>> terrain = examples.download_st_helens().warp_by_scalar()
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(terrain)
>>> widget = pl.add_north_arrow_widget()
>>> pl.enable_terrain_style(True)
>>> pl.show()
"""
marker = create_north_arrow()
mapper = pyvista.DataSetMapper(marker)
actor = pyvista.Actor(mapper)
actor.prop.show_edges = True
if edge_color is not None:
actor.prop.edge_color = edge_color
actor.prop.line_width = line_width
actor.prop.color = color
actor.prop.opacity = opacity
actor.prop.lighting = lighting
return self.add_orientation_widget(
actor,
interactive=interactive,
viewport=viewport,
)
def add_box_axes(
self,
*,
interactive=None,
line_width=2,
text_scale=0.366667,
edge_color='black',
x_color=None,
y_color=None,
z_color=None,
xlabel='X',
ylabel='Y',
zlabel='Z',
x_face_color='white',
y_face_color='white',
z_face_color='white',
label_color=None,
labels_off=False,
opacity=0.5,
show_text_edges=False,
viewport=(0, 0, 0.2, 0.2),
):
"""Add an interactive color box axes widget in the bottom left corner.
Parameters
----------
interactive : bool, optional
Enable this orientation widget to be moved by the user.
line_width : float, optional
The width of the marker lines.
text_scale : float, optional
Size of the text relative to the faces.
edge_color : ColorLike, optional
Color of the edges.
x_color : ColorLike, optional
Color of the x-axis text.
y_color : ColorLike, optional
Color of the y-axis text.
z_color : ColorLike, optional
Color of the z-axis text.
xlabel : str, optional
Text used for the x-axis.
ylabel : str, optional
Text used for the y-axis.
zlabel : str, optional
Text used for the z-axis.
x_face_color : ColorLike, optional
Color used for the x-axis arrow. Defaults to theme axes
parameters.
y_face_color : ColorLike, optional
Color used for the y-axis arrow. Defaults to theme axes
parameters.
z_face_color : ColorLike, optional
Color used for the z-axis arrow. Defaults to theme axes
parameters.
label_color : ColorLike, optional
Color of the labels.
labels_off : bool, optional
Enable or disable the text labels for the axes.
opacity : float, optional
Opacity in the range of ``[0, 1]`` of the orientation box.
show_text_edges : bool, optional
Enable or disable drawing the vector text edges.
viewport : sequence[float], default: (0, 0, 0.2, 0.2)
Viewport ``(xstart, ystart, xend, yend)`` of the widget.
Returns
-------
vtk.vtkAxesActor
Axes actor.
Examples
--------
Use the axes orientation widget instead of the default arrows.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> _ = pl.add_box_axes()
>>> pl.show()
"""
if interactive is None:
interactive = self._theme.interactive
if hasattr(self, 'axes_widget'):
self.axes_widget.EnabledOff()
self.Modified()
del self.axes_widget
self.axes_actor = create_axes_orientation_box(
line_width=line_width,
text_scale=text_scale,
edge_color=edge_color,
x_color=x_color,
y_color=y_color,
z_color=z_color,
xlabel=xlabel,
ylabel=ylabel,
zlabel=zlabel,
x_face_color=x_face_color,
y_face_color=y_face_color,
z_face_color=z_face_color,
color_box=True,
label_color=label_color,
labels_off=labels_off,
opacity=opacity,
show_text_edges=show_text_edges,
)
axes_widget = self.add_orientation_widget(
self.axes_actor,
interactive=interactive,
color=None,
)
axes_widget.SetViewport(viewport)
return self.axes_actor
def hide_axes(self):
"""Hide the axes orientation widget.
See Also
--------
show_axes
Show the axes orientation widget.
axes_enabled
Check if the axes orientation widget is enabled.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.hide_axes()
"""
if hasattr(self, 'axes_widget') and self.axes_widget.GetEnabled():
self.axes_widget.EnabledOff()
self.Modified()
def show_axes(self):
"""Show the axes orientation widget.
See Also
--------
add_axes
Similar method with additional options.
hide_axes
Hide the axes orientation widget.
axes_enabled
Check if the axes orientation widget is enabled.
add_axes_at_origin
Add a :class:`pyvista.AxesActor` to the origin of a scene.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.show_axes()
"""
if hasattr(self, 'axes_widget'):
self.axes_widget.EnabledOn()
self.axes_widget.SetCurrentRenderer(self)
else:
self.add_axes()
self.Modified()
@property
def axes_enabled(self):
"""Return ``True`` when the axes widget is enabled.
See Also
--------
show_axes
Show the axes orientation widget.
hide_axes
Hide the axes orientation widget.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.hide_axes()
>>> pl.renderer.axes_enabled
False
Returns
-------
bool
Return ``True`` when the axes widget is enabled.
"""
if hasattr(self, 'axes_widget'):
return bool(self.axes_widget.GetEnabled())
return False
def show_bounds(
self,
mesh=None,
bounds=None,
axes_ranges=None,
show_xaxis=True,
show_yaxis=True,
show_zaxis=True,
show_xlabels=True,
show_ylabels=True,
show_zlabels=True,
bold=True,
font_size=None,
font_family=None,
color=None,
xtitle='X Axis',
ytitle='Y Axis',
ztitle='Z Axis',
n_xlabels=5,
n_ylabels=5,
n_zlabels=5,
use_2d=False,
grid=None,
location='closest',
ticks=None,
all_edges=False,
corner_factor=0.5,
fmt=None,
minor_ticks=False,
padding=0.0,
use_3d_text=True,
render=None,
**kwargs,
):
"""Add bounds axes.
Shows the bounds of the most recent input mesh unless mesh is
specified.
Parameters
----------
mesh : pyvista.DataSet | pyvista.MultiBlock, optional
Input mesh to draw bounds axes around.
bounds : sequence[float], optional
Bounds to override mesh bounds in the form ``[xmin, xmax,
ymin, ymax, zmin, zmax]``.
axes_ranges : sequence[float], optional
When set, these values override the values that are shown on the
axes. This can be useful when plotting scaled datasets or if you wish
to manually display different values. These values must be in the
form:
``[xmin, xmax, ymin, ymax, zmin, zmax]``.
show_xaxis : bool, default: True
Makes x-axis visible.
show_yaxis : bool, default: True
Makes y-axis visible.
show_zaxis : bool, default: True
Makes z-axis visible.
show_xlabels : bool, default: True
Shows X labels.
show_ylabels : bool, default: True
Shows Y labels.
show_zlabels : bool, default: True
Shows Z labels.
bold : bool, default: True
Bolds axis labels and numbers.
font_size : float, optional
Sets the size of the label font. Defaults to
:attr:`pyvista.global_theme.font.size
<pyvista.plotting.themes._Font.size>`.
font_family : str, optional
Font family. Must be either ``'courier'``, ``'times'``,
or ``'arial'``. Defaults to :attr:`pyvista.global_theme.font.family
<pyvista.plotting.themes._Font.family>`.
color : ColorLike, optional
Color of all labels and axis titles. Defaults to
:attr:`pyvista.global_theme.font.color
<pyvista.plotting.themes._Font.color>`.
Either a string, RGB list, or hex color string. For
example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
xtitle : str, default: "X Axis"
Title of the x-axis. Default ``"X Axis"``.
ytitle : str, default: "Y Axis"
Title of the y-axis. Default ``"Y Axis"``.
ztitle : str, default: "Z Axis"
Title of the z-axis. Default ``"Z Axis"``.
n_xlabels : int, default: 5
Number of labels for the x-axis.
n_ylabels : int, default: 5
Number of labels for the y-axis.
n_zlabels : int, default: 5
Number of labels for the z-axis.
use_2d : bool, default: False
This can be enabled for smoother plotting.
grid : bool or str, optional
Add grid lines to the backface (``True``, ``'back'``, or
``'backface'``) or to the frontface (``'front'``,
``'frontface'``) of the axes actor.
location : str, default: "closest"
Set how the axes are drawn: either static (``'all'``), closest
triad (``'front'``, ``'closest'``, ``'default'``), furthest triad
(``'back'``, ``'furthest'``), static closest to the origin
(``'origin'``), or outer edges (``'outer'``) in relation to the
camera position.
ticks : str, optional
Set how the ticks are drawn on the axes grid. Options include:
``'inside', 'outside', 'both'``.
all_edges : bool, default: False
Adds an unlabeled and unticked box at the boundaries of
plot. Useful for when wanting to plot outer grids while
still retaining all edges of the boundary.
corner_factor : float, default: 0.5
If ``all_edges``, this is the factor along each axis to
draw the default box. Default shows the full box.
fmt : str, optional
A format string defining how tick labels are generated from
tick positions. A default is looked up on the active theme.
minor_ticks : bool, default: False
If ``True``, also plot minor ticks on all axes.
padding : float, default: 0.0
An optional percent padding along each axial direction to
cushion the datasets in the scene from the axes
annotations. Defaults no padding.
use_3d_text : bool, default: True
Use ``vtkTextActor3D`` for titles and labels.
render : bool, optional
If the render window is being shown, trigger a render
after showing bounds.
**kwargs : dict, optional
Deprecated keyword arguments.
Returns
-------
vtk.vtkCubeAxesActor
Bounds actor.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = pv.Sphere()
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(mesh)
>>> actor = plotter.show_bounds(
... grid='front',
... location='outer',
... all_edges=True,
... )
>>> plotter.show()
Control how many labels are displayed.
>>> mesh = examples.load_random_hills()
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(
... mesh, cmap='terrain', show_scalar_bar=False
... )
>>> actor = plotter.show_bounds(
... grid='back',
... location='outer',
... ticks='both',
... n_xlabels=2,
... n_ylabels=2,
... n_zlabels=2,
... xtitle='Easting',
... ytitle='Northing',
... ztitle='Elevation',
... )
>>> plotter.show()
Hide labels, but still show axis titles.
>>> plotter = pv.Plotter()
>>> actor = plotter.add_mesh(
... mesh, cmap='terrain', show_scalar_bar=False
... )
>>> actor = plotter.show_bounds(
... grid='back',
... location='outer',
... ticks='both',
... show_xlabels=False,
... show_ylabels=False,
... show_zlabels=False,
... xtitle='Easting',
... ytitle='Northing',
... ztitle='Elevation',
... )
>>> plotter.show()
"""
self.remove_bounds_axes()
if font_family is None:
font_family = self._theme.font.family
if font_size is None:
font_size = self._theme.font.size
if fmt is None:
fmt = self._theme.font.fmt
if fmt is None:
fmt = '%.1f' # fallback
if 'xlabel' in kwargs: # pragma: no cover
xtitle = kwargs.pop('xlabel')
warnings.warn(
"`xlabel` is deprecated. Use `xtitle` instead.",
PyVistaDeprecationWarning,
)
if 'ylabel' in kwargs: # pragma: no cover
ytitle = kwargs.pop('ylabel')
warnings.warn(
"`ylabel` is deprecated. Use `ytitle` instead.",
PyVistaDeprecationWarning,
)
if 'zlabel' in kwargs: # pragma: no cover
ztitle = kwargs.pop('zlabel')
warnings.warn(
"`zlabel` is deprecated. Use `ztitle` instead.",
PyVistaDeprecationWarning,
)
assert_empty_kwargs(**kwargs)
color = Color(color, default_color=self._theme.font.color)
if mesh is None and bounds is None:
# Use the bounds of all data in the rendering window
bounds = np.array(self.bounds)
elif bounds is None:
# otherwise, use the bounds of the mesh (if available)
bounds = np.array(mesh.bounds)
else:
bounds = np.asanyarray(bounds, dtype=float)
# create actor
cube_axes_actor = pyvista.CubeAxesActor(
self.camera,
minor_ticks=minor_ticks,
tick_location=ticks,
x_title=xtitle,
y_title=ytitle,
z_title=ztitle,
x_axis_visibility=show_xaxis,
y_axis_visibility=show_yaxis,
z_axis_visibility=show_zaxis,
x_label_format=fmt,
y_label_format=fmt,
z_label_format=fmt,
x_label_visibility=show_xlabels,
y_label_visibility=show_ylabels,
z_label_visibility=show_zlabels,
n_xlabels=n_xlabels,
n_ylabels=n_ylabels,
n_zlabels=n_zlabels,
)
cube_axes_actor.use_2d_mode = use_2d or not np.allclose(self.scale, [1.0, 1.0, 1.0])
if grid:
grid = 'back' if grid is True else grid
if not isinstance(grid, str):
raise TypeError(f'`grid` must be a str, not {type(grid)}')
grid = grid.lower()
if grid in ('front', 'frontface'):
cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_CLOSEST)
elif grid in ('both', 'all'):
cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_ALL)
elif grid in ('back', True):
cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_FURTHEST)
else:
raise ValueError(f'`grid` must be either "front", "back, or, "all", not {grid}')
# Only show user desired grid lines
cube_axes_actor.SetDrawXGridlines(show_xaxis)
cube_axes_actor.SetDrawYGridlines(show_yaxis)
cube_axes_actor.SetDrawZGridlines(show_zaxis)
# Set the colors
cube_axes_actor.GetXAxesGridlinesProperty().SetColor(color.float_rgb)
cube_axes_actor.GetYAxesGridlinesProperty().SetColor(color.float_rgb)
cube_axes_actor.GetZAxesGridlinesProperty().SetColor(color.float_rgb)
if isinstance(location, str):
location = location.lower()
if location in ('all'):
cube_axes_actor.SetFlyModeToStaticEdges()
elif location in ('origin'):
cube_axes_actor.SetFlyModeToStaticTriad()
elif location in ('outer'):
cube_axes_actor.SetFlyModeToOuterEdges()
elif location in ('default', 'closest', 'front'):
cube_axes_actor.SetFlyModeToClosestTriad()
elif location in ('furthest', 'back'):
cube_axes_actor.SetFlyModeToFurthestTriad()
else:
raise ValueError(
f'Value of location ("{location}") should be either "all", "origin",'
' "outer", "default", "closest", "front", "furthest", or "back".',
)
elif location is not None:
raise TypeError('location must be a string')
if isinstance(padding, (int, float)) and 0.0 <= padding < 1.0:
if not np.any(np.abs(bounds) == np.inf):
cushion = (
np.array(
[
np.abs(bounds[1] - bounds[0]),
np.abs(bounds[3] - bounds[2]),
np.abs(bounds[5] - bounds[4]),
],
)
* padding
)
bounds[::2] -= cushion
bounds[1::2] += cushion
else:
raise ValueError(f'padding ({padding}) not understood. Must be float between 0 and 1')
cube_axes_actor.bounds = bounds
# set axes ranges if input
if axes_ranges is not None:
if isinstance(axes_ranges, (Sequence, np.ndarray)):
axes_ranges = np.asanyarray(axes_ranges)
else:
raise TypeError('Input axes_ranges must be a numeric sequence.')
if not np.issubdtype(axes_ranges.dtype, np.number):
raise TypeError('All of the elements of axes_ranges must be numbers.')
# set the axes ranges
if axes_ranges.shape != (6,):
raise ValueError(
'`axes_ranges` must be passed as a [xmin, xmax, ymin, ymax, zmin, zmax] sequence.',
)
cube_axes_actor.x_axis_range = axes_ranges[0], axes_ranges[1]
cube_axes_actor.y_axis_range = axes_ranges[2], axes_ranges[3]
cube_axes_actor.z_axis_range = axes_ranges[4], axes_ranges[5]
# set color
cube_axes_actor.GetXAxesLinesProperty().SetColor(color.float_rgb)
cube_axes_actor.GetYAxesLinesProperty().SetColor(color.float_rgb)
cube_axes_actor.GetZAxesLinesProperty().SetColor(color.float_rgb)
# set font
font_family = parse_font_family(font_family)
if not use_3d_text or not np.allclose(self.scale, [1.0, 1.0, 1.0]):
use_3d_text = False
cube_axes_actor.SetUseTextActor3D(False)
else:
cube_axes_actor.SetUseTextActor3D(True)
props = [
cube_axes_actor.GetTitleTextProperty(0),
cube_axes_actor.GetTitleTextProperty(1),
cube_axes_actor.GetTitleTextProperty(2),
cube_axes_actor.GetLabelTextProperty(0),
cube_axes_actor.GetLabelTextProperty(1),
cube_axes_actor.GetLabelTextProperty(2),
]
for prop in props:
prop.SetColor(color.float_rgb)
prop.SetFontFamily(font_family)
prop.SetBold(bold)
# this merely makes the font sharper
if use_3d_text:
prop.SetFontSize(50)
# Note: font_size does nothing as a property, use SetScreenSize instead
# Here, we normalize relative to 12 to give the user an illusion of
# just changing the font size relative to a font size of 12. 10 is used
# here since it's the default "screen size".
cube_axes_actor.SetScreenSize(font_size / 12 * 10.0)
if all_edges:
self.add_bounding_box(color=color, corner_factor=corner_factor)
self.add_actor(cube_axes_actor, reset_camera=False, pickable=False, render=render)
self.cube_axes_actor = cube_axes_actor
self.Modified()
return cube_axes_actor
def show_grid(self, **kwargs):
"""Show grid lines and bounds axes labels.
A wrapped implementation of :func:`show_bounds()
<pyvista.Renderer.show_bounds>` to change default behavior to use
grid lines and showing the axes labels on the outer edges.
This is intended to be similar to :func:`matplotlib.pyplot.grid`.
Parameters
----------
**kwargs : dict, optional
See :func:`Renderer.show_bounds` for additional keyword
arguments.
Returns
-------
vtk.vtkAxesActor
Bounds actor.
Examples
--------
>>> import pyvista as pv
>>> mesh = pv.Cone()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh)
>>> _ = pl.show_grid()
>>> pl.show()
"""
kwargs.setdefault('grid', 'back')
kwargs.setdefault('location', 'outer')
kwargs.setdefault('ticks', 'both')
return self.show_bounds(**kwargs)
def remove_bounding_box(self, render=True):
"""Remove bounding box.
Parameters
----------
render : bool, default: True
Trigger a render once the bounding box is removed.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_bounding_box()
>>> pl.remove_bounding_box()
"""
if hasattr(self, '_box_object'):
actor = self.bounding_box_actor
self.bounding_box_actor = None
del self._box_object
self.remove_actor(actor, reset_camera=False, render=render)
self.Modified()
def add_bounding_box(
self,
color="grey",
corner_factor=0.5,
line_width=None,
opacity=1.0,
render_lines_as_tubes=False,
lighting=None,
reset_camera=None,
outline=True,
culling='front',
):
"""Add an unlabeled and unticked box at the boundaries of plot.
Useful for when wanting to plot outer grids while still
retaining all edges of the boundary.
Parameters
----------
color : ColorLike, default: "grey"
Color of all labels and axis titles. Default white.
Either a string, rgb sequence, or hex color string. For
example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
corner_factor : float, default: 0.5
This is the factor along each axis to draw the default
box. Default is 0.5 to show the full box.
line_width : float, optional
Thickness of lines.
opacity : float, default: 1.0
Opacity of mesh. Should be between 0 and 1.
render_lines_as_tubes : bool, default: False
Show lines as thick tubes rather than flat lines. Control
the width with ``line_width``.
lighting : bool, optional
Enable or disable directional lighting for this actor.
reset_camera : bool, optional
Reset camera position when ``True`` to include all actors.
outline : bool, default: True
Default is ``True``. when ``False``, a box with faces is
shown with the specified culling.
culling : str, default: "front"
Does not render faces on the bounding box that are culled. Options
are ``'front'`` or ``'back'``.
Returns
-------
vtk.vtkActor
VTK actor of the bounding box.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> _ = pl.add_bounding_box(line_width=5, color='black')
>>> pl.show()
"""
if lighting is None:
lighting = self._theme.lighting
self.remove_bounding_box()
if outline:
self._bounding_box = _vtk.vtkOutlineCornerSource()
self._bounding_box.SetCornerFactor(corner_factor)
else:
self._bounding_box = _vtk.vtkCubeSource()
self._bounding_box.SetBounds(self.bounds)
self._bounding_box.Update()
self._box_object = wrap(self._bounding_box.GetOutput())
name = f'BoundingBox({hex(id(self._box_object))})'
mapper = _vtk.vtkDataSetMapper()
mapper.SetInputData(self._box_object)
self.bounding_box_actor, prop = self.add_actor(
mapper,
reset_camera=reset_camera,
name=name,
culling=culling,
pickable=False,
)
prop.SetColor(Color(color, default_color=self._theme.outline_color).float_rgb)
prop.SetOpacity(opacity)
if render_lines_as_tubes:
prop.SetRenderLinesAsTubes(render_lines_as_tubes)
# lighting display style
if lighting is False:
prop.LightingOff()
# set line thickness
if line_width:
prop.SetLineWidth(line_width)
prop.SetRepresentationToSurface()
self.Modified()
return self.bounding_box_actor
def add_floor(
self,
face='-z',
i_resolution=10,
j_resolution=10,
color=None,
line_width=None,
opacity=1.0,
show_edges=False,
lighting=False,
edge_color=None,
reset_camera=None,
pad=0.0,
offset=0.0,
pickable=False,
store_floor_kwargs=True,
):
"""Show a floor mesh.
This generates planes at the boundaries of the scene to behave
like floors or walls.
Parameters
----------
face : str, default: "-z"
The face at which to place the plane. Options are
(``'-z'``, ``'-y'``, ``'-x'``, ``'+z'``, ``'+y'``, and
``'+z'``). Where the ``-/+`` sign indicates on which side of
the axis the plane will lie. For example, ``'-z'`` would
generate a floor on the XY-plane and the bottom of the
scene (minimum z).
i_resolution : int, default: 10
Number of points on the plane in the i direction.
j_resolution : int, default: 10
Number of points on the plane in the j direction.
color : ColorLike, optional
Color of all labels and axis titles. Default gray.
Either a string, rgb list, or hex color string.
line_width : int, optional
Thickness of the edges. Only if ``show_edges`` is
``True``.
opacity : float, default: 1.0
The opacity of the generated surface.
show_edges : bool, default: False
Flag on whether to show the mesh edges for tiling.
line_width : float, default: False
Thickness of lines. Only valid for wireframe and surface
representations.
lighting : bool, default: False
Enable or disable view direction lighting.
edge_color : ColorLike, optional
Color of the edges of the mesh.
reset_camera : bool, optional
Resets the camera when ``True`` after adding the floor.
pad : float, default: 0.0
Percentage padding between 0 and 1.
offset : float, default: 0.0
Percentage offset along plane normal.
pickable : bool, default: false
Make this floor actor pickable in the renderer.
store_floor_kwargs : bool, default: True
Stores the keyword arguments used when adding this floor.
Useful when updating the bounds and regenerating the
floor.
Returns
-------
vtk.vtkActor
VTK actor of the floor.
Examples
--------
Add a floor below a sphere and plot it.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Sphere())
>>> actor = pl.add_floor()
>>> pl.show()
"""
if store_floor_kwargs:
kwargs = locals()
kwargs.pop('self')
self._floor_kwargs.append(kwargs)
ranges = np.ptp(np.array(self.bounds).reshape(-1, 2), axis=1)
ranges += ranges * pad
center = np.array(self.center)
if face.lower() in '-z':
center[2] = self.bounds[4] - (ranges[2] * offset)
normal = (0, 0, 1)
i_size = ranges[0]
j_size = ranges[1]
elif face.lower() in '-y':
center[1] = self.bounds[2] - (ranges[1] * offset)
normal = (0, 1, 0)
i_size = ranges[2]
j_size = ranges[0]
elif face.lower() in '-x':
center[0] = self.bounds[0] - (ranges[0] * offset)
normal = (1, 0, 0)
i_size = ranges[2]
j_size = ranges[1]
elif face.lower() in '+z':
center[2] = self.bounds[5] + (ranges[2] * offset)
normal = (0, 0, -1)
i_size = ranges[0]
j_size = ranges[1]
elif face.lower() in '+y':
center[1] = self.bounds[3] + (ranges[1] * offset)
normal = (0, -1, 0)
i_size = ranges[2]
j_size = ranges[0]
elif face.lower() in '+x':
center[0] = self.bounds[1] + (ranges[0] * offset)
normal = (-1, 0, 0)
i_size = ranges[2]
j_size = ranges[1]
else:
raise NotImplementedError(f'Face ({face}) not implemented')
self._floor = pyvista.Plane(
center=center,
direction=normal,
i_size=i_size,
j_size=j_size,
i_resolution=i_resolution,
j_resolution=j_resolution,
)
self._floor.clear_data()
if lighting is None:
lighting = self._theme.lighting
self.remove_bounding_box()
mapper = DataSetMapper()
mapper.SetInputData(self._floor)
actor, prop = self.add_actor(
mapper,
reset_camera=reset_camera,
name=f'Floor({face})',
pickable=pickable,
)
prop.SetColor(Color(color, default_color=self._theme.floor_color).float_rgb)
prop.SetOpacity(opacity)
# edge display style
if show_edges:
prop.EdgeVisibilityOn()
prop.SetEdgeColor(Color(edge_color, default_color=self._theme.edge_color).float_rgb)
# lighting display style
if lighting is False:
prop.LightingOff()
# set line thickness
if line_width:
prop.SetLineWidth(line_width)
prop.SetRepresentationToSurface()
self._floors.append(actor)
return actor
def remove_floors(self, clear_kwargs=True, render=True):
"""Remove all floor actors.
Parameters
----------
clear_kwargs : bool, default: True
Clear default floor arguments.
render : bool, default: True
Render upon removing the floor.
Examples
--------
Add a floor below a sphere, remove it, and then plot it.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Sphere())
>>> actor = pl.add_floor()
>>> pl.remove_floors()
>>> pl.show()
"""
if getattr(self, '_floor', None) is not None:
self._floor.ReleaseData()
self._floor = None
for actor in self._floors:
self.remove_actor(actor, reset_camera=False, render=render)
self._floors.clear()
if clear_kwargs:
self._floor_kwargs.clear()
def remove_bounds_axes(self):
"""Remove bounds axes.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter(shape=(1, 2))
>>> pl.subplot(0, 0)
>>> actor = pl.add_mesh(pv.Sphere())
>>> actor = pl.show_bounds(grid='front', location='outer')
>>> pl.subplot(0, 1)
>>> actor = pl.add_mesh(pv.Sphere())
>>> actor = pl.show_bounds(grid='front', location='outer')
>>> actor = pl.remove_bounds_axes()
>>> pl.show()
"""
if self.cube_axes_actor is not None:
self.remove_actor(self.cube_axes_actor)
self.cube_axes_actor = None
self.Modified()
def add_light(self, light):
"""Add a light to the renderer.
Parameters
----------
light : vtk.vtkLight or pyvista.Light
Light to add.
"""
# convert from a vtk type if applicable
if isinstance(light, _vtk.vtkLight) and not isinstance(light, pyvista.Light):
light = pyvista.Light.from_vtk(light)
if not isinstance(light, pyvista.Light):
raise TypeError(f'Expected Light instance, got {type(light).__name__} instead.')
self._lights.append(light)
self.AddLight(light)
self.Modified()
# we add the renderer to add/remove the light actor if
# positional or cone angle is modified
light.add_renderer(self)
@property
def lights(self): # numpydoc ignore=RT01
"""Return a list of all lights in the renderer.
Returns
-------
list
Lights in the renderer.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.renderer.lights # doctest:+SKIP
[<Light (Headlight) at ...>,
<Light (Camera Light) at 0x7f1dd8155760>,
<Light (Camera Light) at 0x7f1dd8155340>,
<Light (Camera Light) at 0x7f1dd8155460>,
<Light (Camera Light) at 0x7f1dd8155f40>]
"""
return list(self.GetLights())
def remove_all_lights(self):
"""Remove all lights from the renderer."""
self.RemoveAllLights()
self._lights.clear()
def clear_actors(self):
"""Remove all actors (keep lights and properties)."""
if self._actors:
for actor in list(self._actors):
with contextlib.suppress(KeyError):
self.remove_actor(actor, reset_camera=False, render=False)
self.Modified()
def clear(self):
"""Remove all actors and properties."""
self.clear_actors()
if self._charts is not None:
self._charts.deep_clean()
self.remove_all_lights()
self.RemoveAllViewProps()
self.Modified()
self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
self._scalar_bar_slot_lookup = {}
def set_focus(self, point):
"""Set focus to a point.
Parameters
----------
point : sequence[float]
Cartesian point to focus on in the form of ``[x, y, z]``.
Examples
--------
>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, show_edges=True)
>>> _ = pl.add_point_labels([mesh.points[1]], ["Focus"])
>>> _ = pl.camera # this initializes the camera
>>> pl.set_focus(mesh.points[1])
>>> pl.show()
"""
if isinstance(point, np.ndarray):
if point.ndim != 1:
point = point.ravel()
self.camera.focal_point = scale_point(self.camera, point, invert=False)
self.camera_set = True
self.Modified()
def set_position(self, point, reset=False, render=True):
"""Set camera position to a point.
Parameters
----------
point : sequence
Cartesian point to focus on in the form of ``[x, y, z]``.
reset : bool, default: False
Whether to reset the camera after setting the camera
position.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the position.
Examples
--------
Move the camera far away to ``[7, 7, 7]``.
>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, show_edges=True)
>>> pl.set_position([7, 7, 7])
>>> pl.show()
"""
if isinstance(point, np.ndarray):
if point.ndim != 1:
point = point.ravel()
self.camera.position = scale_point(self.camera, point, invert=False)
if reset:
self.reset_camera(render=render)
self.camera_set = True
self.Modified()
def set_viewup(self, vector, reset=True, render=True):
"""Set camera viewup vector.
Parameters
----------
vector : sequence[float]
New camera viewup vector.
reset : bool, default: True
Whether to reset the camera after setting the camera
position.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the viewup.
Examples
--------
Look from the top down by setting view up to ``[0, 1, 0]``.
Notice how the y-axis appears vertical.
>>> from pyvista import demos
>>> pl = demos.orientation_plotter()
>>> pl.set_viewup([0, 1, 0])
>>> pl.show()
"""
if isinstance(vector, np.ndarray):
if vector.ndim != 1:
vector = vector.ravel()
self.camera.up = vector
if reset:
self.reset_camera(render=render)
self.camera_set = True
self.Modified()
def enable_parallel_projection(self):
"""Enable parallel projection.
The camera will have a parallel projection. Parallel projection is
often useful when viewing images or 2D datasets.
See Also
--------
pyvista.Plotter.enable_2d_style
Examples
--------
>>> import pyvista as pv
>>> from pyvista import demos
>>> pl = pv.demos.orientation_plotter()
>>> pl.enable_parallel_projection()
>>> pl.show()
"""
# Fix the 'reset camera' effect produced by the VTK when parallel
# projection is enabled.
angle = np.radians(self.camera.view_angle)
self.camera.parallel_scale = self.camera.distance * np.sin(0.5 * angle)
self.camera.enable_parallel_projection()
self.Modified()
def disable_parallel_projection(self):
"""Reset the camera to use perspective projection.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import demos
>>> pl = pv.demos.orientation_plotter()
>>> pl.disable_parallel_projection()
>>> pl.show()
"""
# Fix the 'reset camera' effect produced by the VTK when parallel
# projection is disabled.
focus = self.camera.focal_point
angle = np.radians(self.camera.view_angle)
distance = self.camera.parallel_scale / np.sin(0.5 * angle)
direction = self.camera.direction
x = focus[0] - distance * direction[0]
y = focus[1] - distance * direction[1]
z = focus[2] - distance * direction[2]
self.camera.position = (x, y, z)
self.ResetCameraClippingRange()
self.camera.disable_parallel_projection()
self.Modified()
@property
def parallel_projection(self): # numpydoc ignore=RT01
"""Return parallel projection state of active render window.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.parallel_projection = False
>>> pl.parallel_projection
False
"""
return self.camera.parallel_projection
@parallel_projection.setter
def parallel_projection(self, state): # numpydoc ignore=GL08
self.camera.parallel_projection = state
self.Modified()
@property
def parallel_scale(self): # numpydoc ignore=RT01
"""Return parallel scale of active render window.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.parallel_scale = 2
"""
return self.camera.parallel_scale
@parallel_scale.setter
def parallel_scale(self, value): # numpydoc ignore=GL08
self.camera.parallel_scale = value
self.Modified()
def remove_actor(self, actor, reset_camera=False, render=True):
"""Remove an actor from the Renderer.
Parameters
----------
actor : str, vtk.vtkActor, list or tuple
If the type is ``str``, removes the previously added actor
with the given name. If the type is ``vtk.vtkActor``,
removes the actor if it's previously added to the
Renderer. If ``list`` or ``tuple``, removes iteratively
each actor.
reset_camera : bool, optional
Resets camera so all actors can be seen.
render : bool, optional
Render upon actor removal. Set this to ``False`` to stop
the render window from rendering when an actor is removed.
Returns
-------
bool
``True`` when actor removed. ``False`` when actor has not
been removed.
Examples
--------
Add two meshes to a plotter and then remove the sphere actor.
>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> pl = pv.Plotter()
>>> cube_actor = pl.add_mesh(pv.Cube(), show_edges=True)
>>> sphere_actor = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> _ = pl.remove_actor(cube_actor)
>>> pl.show()
"""
name = None
if isinstance(actor, str):
name = actor
keys = list(self._actors.keys())
names = [k for k in keys if k.startswith(f'{name}-')]
if len(names) > 0:
self.remove_actor(names, reset_camera=reset_camera, render=render)
try:
actor = self._actors[name]
except KeyError:
# If actor of that name is not present then return success
return False
if isinstance(actor, Iterable):
success = False
for a in actor:
rv = self.remove_actor(a, reset_camera=reset_camera, render=render)
if rv or success:
success = True
return success
if actor is None:
return False
# remove any labels associated with the actor
self._labels.pop(actor.GetAddressAsString(""), None)
# ensure any scalar bars associated with this actor are removed
with contextlib.suppress(AttributeError, ReferenceError):
self.parent.scalar_bars._remove_mapper_from_plotter(actor)
self.RemoveActor(actor)
if name is None:
for k, v in self._actors.items():
if v == actor:
name = k
self._actors.pop(name, None)
self.update_bounds_axes()
if reset_camera or not self.camera_set and reset_camera is None:
self.reset_camera(render=render)
elif render:
self.parent.render()
self.Modified()
return True
def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True, render=True):
"""Scale all the actors in the scene.
Scaling in performed independently on the X, Y and z-axis.
A scale of zero is illegal and will be replaced with one.
.. warning::
Setting the scale on the renderer is a convenience method to
individually scale each of the actors in the scene. If a scale
was set on an actor previously, it will be reset to the scale
of this Renderer.
Parameters
----------
xscale : float, optional
Scaling in the x direction. Default is ``None``, which
does not change existing scaling.
yscale : float, optional
Scaling in the y direction. Default is ``None``, which
does not change existing scaling.
zscale : float, optional
Scaling in the z direction. Default is ``None``, which
does not change existing scaling.
reset_camera : bool, default: True
Resets camera so all actors can be seen.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the scale.
Examples
--------
Set the scale in the z direction to be 2 times that of
nominal. Leave the other axes unscaled.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.set_scale(zscale=2)
>>> _ = pl.add_mesh(pv.Sphere()) # perfect sphere
>>> pl.show()
"""
if xscale is None:
xscale = self.scale[0]
if yscale is None:
yscale = self.scale[1]
if zscale is None:
zscale = self.scale[2]
self.scale = [xscale, yscale, zscale]
# Reset all actors to match this scale
for actor in self.actors.values():
if hasattr(actor, 'SetScale'):
actor.SetScale(self.scale)
self.parent.render()
if reset_camera:
self.update_bounds_axes()
self.reset_camera(render=render)
self.Modified()
def get_default_cam_pos(self, negative=False):
"""Return the default focal points and viewup.
Uses ResetCamera to make a useful view.
Parameters
----------
negative : bool, default: False
View from the opposite direction.
Returns
-------
list
List of camera position:
* Position
* Focal point
* View up
"""
focal_pt = self.center
if any(np.isnan(focal_pt)):
focal_pt = (0.0, 0.0, 0.0)
position = np.array(self._theme.camera.position).astype(float)
if negative:
position *= -1
position = position / np.array(self.scale).astype(float)
return [position + np.array(focal_pt), focal_pt, self._theme.camera.viewup]
def update_bounds_axes(self):
"""Update the bounds axes of the render window."""
if (
hasattr(self, '_box_object')
and self._box_object is not None
and self.bounding_box_actor is not None
):
if not np.allclose(self._box_object.bounds, self.bounds):
color = self.bounding_box_actor.GetProperty().GetColor()
self.remove_bounding_box()
self.add_bounding_box(color=color)
self.remove_floors(clear_kwargs=False)
for floor_kwargs in self._floor_kwargs:
floor_kwargs['store_floor_kwargs'] = False
self.add_floor(**floor_kwargs)
if self.cube_axes_actor is not None:
self.cube_axes_actor.update_bounds(self.bounds)
if not np.allclose(self.scale, [1.0, 1.0, 1.0]):
self.cube_axes_actor.SetUse2DMode(True)
else:
self.cube_axes_actor.SetUse2DMode(False)
self.Modified()
def reset_camera(self, render=True, bounds=None):
"""Reset the camera of the active render window.
The camera slides along the vector defined from camera
position to focal point until all of the actors can be seen.
Parameters
----------
render : bool, default: True
Trigger a render after resetting the camera.
bounds : iterable(int), optional
Automatically set up the camera based on a specified bounding box
``(xmin, xmax, ymin, ymax, zmin, zmax)``.
Examples
--------
Add a mesh and place the camera position too close to the
mesh. Then reset the camera and show the mesh.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> pl.set_position((0, 0.1, 0.1))
>>> pl.reset_camera()
>>> pl.show()
"""
if bounds is not None:
self.ResetCamera(*bounds)
else:
self.ResetCamera()
self.reset_camera_clipping_range()
if render:
self.parent.render()
self.Modified()
def isometric_view(self):
"""Reset the camera to a default isometric view.
DEPRECATED: Please use ``view_isometric``.
"""
self.view_isometric()
def view_isometric(self, negative=False, render=True, bounds=None):
"""Reset the camera to a default isometric view.
The view will show all the actors in the scene.
Parameters
----------
negative : bool, default: False
View from the other isometric direction.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the camera position.
bounds : iterable(int), optional
Automatically set up the camera based on a specified bounding box
``(xmin, xmax, ymin, ymax, zmin, zmax)``.
Examples
--------
Isometric view.
>>> from pyvista import demos
>>> pl = demos.orientation_plotter()
>>> pl.view_isometric()
>>> pl.show()
Negative isometric view.
>>> from pyvista import demos
>>> pl = demos.orientation_plotter()
>>> pl.view_isometric(negative=True)
>>> pl.show()
"""
position = self.get_default_cam_pos(negative=negative)
self.camera_position = CameraPosition(*position)
self.camera_set = negative
self.reset_camera(render=render, bounds=bounds)
def view_vector(self, vector, viewup=None, render=True, bounds=None):
"""Point the camera in the direction of the given vector.
Parameters
----------
vector : sequence[float]
Direction to point the camera in.
viewup : sequence[float], optional
Sequence describing the view up of the camera.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the camera position.
bounds : iterable(int), optional
Automatically set up the camera based on a specified bounding box
``(xmin, xmax, ymin, ymax, zmin, zmax)``.
"""
focal_pt = self.center
if viewup is None:
viewup = self._theme.camera.viewup
cpos = CameraPosition(vector + np.array(focal_pt), focal_pt, viewup)
self.camera_position = cpos
self.reset_camera(render=render, bounds=bounds)
def view_xy(self, negative=False, render=True, bounds=None):
"""View the XY plane.
Parameters
----------
negative : bool, default: False
View from the opposite direction.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the camera position.
bounds : iterable(int), optional
Automatically set up the camera based on a specified bounding box
``(xmin, xmax, ymin, ymax, zmin, zmax)``.
Examples
--------
View the XY plane of a built-in mesh example.
>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_xy()
>>> pl.show()
"""
self.view_vector(*view_vectors('xy', negative=negative), render=render, bounds=bounds)
def view_yx(self, negative=False, render=True, bounds=None):
"""View the YX plane.
Parameters
----------
negative : bool, default: False
View from the opposite direction.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the camera position.
bounds : iterable(int), optional
Automatically set up the camera based on a specified bounding box
``(xmin, xmax, ymin, ymax, zmin, zmax)``.
Examples
--------
View the YX plane of a built-in mesh example.
>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_yx()
>>> pl.show()
"""
self.view_vector(*view_vectors('yx', negative=negative), render=render, bounds=bounds)
def view_xz(self, negative=False, render=True, bounds=None):
"""View the XZ plane.
Parameters
----------
negative : bool, default: False
View from the opposite direction.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the camera position.
bounds : iterable(int), optional
Automatically set up the camera based on a specified bounding box
``(xmin, xmax, ymin, ymax, zmin, zmax)``.
Examples
--------
View the XZ plane of a built-in mesh example.
>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_xz()
>>> pl.show()
"""
self.view_vector(*view_vectors('xz', negative=negative), render=render, bounds=bounds)
def view_zx(self, negative=False, render=True, bounds=None):
"""View the ZX plane.
Parameters
----------
negative : bool, default: False
View from the opposite direction.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the camera position.
bounds : iterable(int), optional
Automatically set up the camera based on a specified bounding box
``(xmin, xmax, ymin, ymax, zmin, zmax)``.
Examples
--------
View the ZX plane of a built-in mesh example.
>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_zx()
>>> pl.show()
"""
self.view_vector(*view_vectors('zx', negative=negative), render=render, bounds=bounds)
def view_yz(self, negative=False, render=True, bounds=None):
"""View the YZ plane.
Parameters
----------
negative : bool, default: False
View from the opposite direction.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the camera position.
bounds : iterable(int), optional
Automatically set up the camera based on a specified bounding box
``(xmin, xmax, ymin, ymax, zmin, zmax)``.
Examples
--------
View the YZ plane of a built-in mesh example.
>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_yz()
>>> pl.show()
"""
self.view_vector(*view_vectors('yz', negative=negative), render=render, bounds=bounds)
def view_zy(self, negative=False, render=True, bounds=None):
"""View the ZY plane.
Parameters
----------
negative : bool, default: False
View from the opposite direction.
render : bool, default: True
If the render window is being shown, trigger a render
after setting the camera position.
bounds : iterable(int), optional
Automatically set up the camera based on a specified bounding box
``(xmin, xmax, ymin, ymax, zmin, zmax)``.
Examples
--------
View the ZY plane of a built-in mesh example.
>>> from pyvista import examples
>>> import pyvista as pv
>>> airplane = examples.load_airplane()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(airplane)
>>> pl.view_zy()
>>> pl.show()
"""
self.view_vector(*view_vectors('zy', negative=negative), render=render, bounds=bounds)
def disable(self):
"""Disable this renderer's camera from being interactive."""
self.SetInteractive(0)
def enable(self):
"""Enable this renderer's camera to be interactive."""
self.SetInteractive(1)
def add_blurring(self):
"""Add blurring.
This can be added several times to increase the degree of blurring.
Examples
--------
Add two blurring passes to the plotter and show it.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere(), show_edges=True)
>>> pl.add_blurring()
>>> pl.add_blurring()
>>> pl.show()
See :ref:`blur_example` for a full example using this method.
"""
self._render_passes.add_blur_pass()
def remove_blurring(self):
"""Remove a single blurring pass.
You will need to run this multiple times to remove all blurring passes.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.add_blurring()
>>> pl.remove_blurring()
>>> pl.show()
"""
self._render_passes.remove_blur_pass()
def enable_depth_of_field(self, automatic_focal_distance=True):
"""Enable depth of field plotting.
Parameters
----------
automatic_focal_distance : bool, default: True
Use automatic focal distance calculation. When enabled, the center
of the viewport will always be in focus regardless of where the
focal point is.
Examples
--------
Create five spheres and demonstrate the effect of depth of field.
>>> import pyvista as pv
>>> from pyvista import examples
>>> pl = pv.Plotter(lighting="three lights")
>>> pl.background_color = "w"
>>> for i in range(5):
... mesh = pv.Sphere(center=(-i * 4, 0, 0))
... color = [0, 255 - i * 20, 30 + i * 50]
... _ = pl.add_mesh(
... mesh,
... show_edges=False,
... pbr=True,
... metallic=1.0,
... color=color,
... )
...
>>> pl.camera.zoom(1.8)
>>> pl.camera_position = [
... (4.74, 0.959, 0.525),
... (0.363, 0.3116, 0.132),
... (-0.088, -0.0075, 0.996),
... ]
>>> pl.enable_depth_of_field()
>>> pl.show()
See :ref:`depth_of_field_example` for a full example using this method.
"""
self._render_passes.enable_depth_of_field_pass(automatic_focal_distance)
def disable_depth_of_field(self):
"""Disable depth of field plotting.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter(lighting="three lights")
>>> pl.enable_depth_of_field()
>>> pl.disable_depth_of_field()
"""
self._render_passes.disable_depth_of_field_pass()
def enable_eye_dome_lighting(self):
"""Enable eye dome lighting (EDL).
Returns
-------
vtk.vtkOpenGLRenderer
VTK renderer with eye dome lighting pass.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> _ = pl.enable_eye_dome_lighting()
"""
self._render_passes.enable_edl_pass()
def disable_eye_dome_lighting(self):
"""Disable eye dome lighting (EDL).
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.disable_eye_dome_lighting()
"""
self._render_passes.disable_edl_pass()
def enable_shadows(self):
"""Enable shadows.
Examples
--------
First, plot without shadows enabled (default)
>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> pl = pv.Plotter(lighting='none', window_size=(1000, 1000))
>>> light = pv.Light()
>>> light.set_direction_angle(20, -20)
>>> pl.add_light(light)
>>> _ = pl.add_mesh(mesh, color='white', smooth_shading=True)
>>> _ = pl.add_mesh(pv.Box((-1.2, -1, -1, 1, -1, 1)))
>>> pl.show()
Now, enable shadows.
>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> pl = pv.Plotter(lighting='none', window_size=(1000, 1000))
>>> light = pv.Light()
>>> light.set_direction_angle(20, -20)
>>> pl.add_light(light)
>>> _ = pl.add_mesh(mesh, color='white', smooth_shading=True)
>>> _ = pl.add_mesh(pv.Box((-1.2, -1, -1, 1, -1, 1)))
>>> pl.enable_shadows()
>>> pl.show()
"""
self._render_passes.enable_shadow_pass()
def disable_shadows(self):
"""Disable shadows.
Examples
--------
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> pl.disable_shadows()
"""
self._render_passes.disable_shadow_pass()
def enable_ssao(self, radius=0.5, bias=0.005, kernel_size=256, blur=True):
"""Enable surface space ambient occlusion (SSAO).
SSAO can approximate shadows more efficiently than ray-tracing
and produce similar results. Use this when you wish to plot the
occlusion effect that nearby meshes have on each other by blocking
nearby light sources.
See `Kitware: Screen-Space Ambient Occlusion
<https://www.kitware.com/ssao/>`_ for more details
Parameters
----------
radius : float, default: 0.5
Neighbor pixels considered when computing the occlusion.
bias : float, default: 0.005
Tolerance factor used when comparing pixel depth.
kernel_size : int, default: 256
Number of samples used. This controls the quality where a higher
number increases the quality at the expense of computation time.
blur : bool, default: True
Controls if occlusion buffer should be blurred before combining it
with the color buffer.
Examples
--------
Generate a :class:`pyvista.UnstructuredGrid` with many tetrahedrons
nearby each other and plot it without SSAO.
>>> import pyvista as pv
>>> ugrid = pv.ImageData(dimensions=(3, 2, 2)).to_tetrahedra(12)
>>> exploded = ugrid.explode()
>>> exploded.plot()
Enable SSAO with the default parameters.
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(exploded)
>>> pl.enable_ssao()
>>> pl.show()
"""
self._render_passes.enable_ssao_pass(radius, bias, kernel_size, blur)
def disable_ssao(self):
"""Disable surface space ambient occlusion (SSAO)."""
self._render_passes.disable_ssao_pass()
def get_pick_position(self):
"""Get the pick position/area as ``x0, y0, x1, y1``.
Returns
-------
tuple
Pick position as ``x0, y0, x1, y1``.
"""
x0 = int(self.GetPickX1())
x1 = int(self.GetPickX2())
y0 = int(self.GetPickY1())
y1 = int(self.GetPickY2())
return x0, y0, x1, y1
def set_background(self, color, top=None, right=None, side=None, corner=None):
"""Set the background color of this renderer.
Parameters
----------
color : ColorLike, optional
Either a string, rgb list, or hex color string. Defaults
to theme default. For example:
* ``color='white'``
* ``color='w'``
* ``color=[1.0, 1.0, 1.0]``
* ``color='#FFFFFF'``
top : ColorLike, optional
If given, this will enable a gradient background where the
``color`` argument is at the bottom and the color given in
``top`` will be the color at the top of the renderer.
right : ColorLike, optional
If given, this will enable a gradient background where the
``color`` argument is at the left and the color given in
``right`` will be the color at the right of the renderer.
side : ColorLike, optional
If given, this will enable a gradient background where the
``color`` argument is at the center and the color given in
``side`` will be the color at the side of the renderer.
corner : ColorLike, optional
If given, this will enable a gradient background where the
``color`` argument is at the center and the color given in
``corner`` will be the color at the corner of the renderer.
Examples
--------
Set the background color to black with a gradient to white at
the top of the plot.
>>> import pyvista as pv
>>> pl = pv.Plotter()
>>> actor = pl.add_mesh(pv.Cone())
>>> pl.set_background('black', top='white')
>>> pl.show()
"""
self.SetBackground(Color(color, default_color=self._theme.background).float_rgb)
if not (right is side is corner is None) and vtk_version_info < (9, 3): # pragma: no cover
from pyvista.core.errors import VTKVersionError
raise VTKVersionError(
"`right` or `side` or `corner` cannot be used under VTK v9.3.0. Try installing VTK v9.3.0 or newer.",
)
if not (
(top is right is side is corner is None)
or (top is not None and right is side is corner is None)
or (right is not None and top is side is corner is None)
or (side is not None and top is right is corner is None)
or (corner is not None and top is right is side is None)
): # pragma: no cover
raise ValueError("You can only set one argument in top, right, side, corner.")
if top is not None:
self.SetGradientBackground(True)
self.SetBackground2(Color(top).float_rgb)
elif right is not None: # pragma: no cover
self.SetGradientBackground(True)
self.SetGradientMode(_vtk.vtkViewport.GradientModes.VTK_GRADIENT_HORIZONTAL)
self.SetBackground2(Color(right).float_rgb)
elif side is not None: # pragma: no cover
self.SetGradientBackground(True)
self.SetGradientMode(
_vtk.vtkViewport.GradientModes.VTK_GRADIENT_RADIAL_VIEWPORT_FARTHEST_SIDE,
)
self.SetBackground2(Color(side).float_rgb)
elif corner is not None: # pragma: no cover
self.SetGradientBackground(True)
self.SetGradientMode(
_vtk.vtkViewport.GradientModes.VTK_GRADIENT_RADIAL_VIEWPORT_FARTHEST_CORNER,
)
self.SetBackground2(Color(corner).float_rgb)
else:
self.SetGradientBackground(False)
self.Modified()
def set_environment_texture(self, texture, is_srgb=False):
"""Set the environment texture used for image based lighting.
This texture is supposed to represent the scene background. If
it is not a cubemap, the texture is supposed to represent an
equirectangular projection. If used with raytracing backends,
the texture must be an equirectangular projection and must be
constructed with a valid ``vtk.vtkImageData``.
Parameters
----------
texture : pyvista.Texture
Texture.
is_srgb : bool, default: False
If the texture is in sRGB color space, set the color flag on the
texture or set this parameter to ``True``. Textures are assumed
to be in linear color space by default.
Examples
--------
Add a skybox cubemap as an environment texture and show that the
lighting from the texture is mapped on to a sphere dataset. Note how
even when disabling the default lightkit, the scene lighting will still
be mapped onto the actor.
>>> from pyvista import examples
>>> import pyvista as pv
>>> pl = pv.Plotter(lighting=None)
>>> cubemap = examples.download_sky_box_cube_map()
>>> _ = pl.add_mesh(
... pv.Sphere(), pbr=True, metallic=0.9, roughness=0.4
... )
>>> pl.set_environment_texture(cubemap)
>>> pl.camera_position = 'xy'
>>> pl.show()
"""
# cube_map textures cannot use spherical harmonics
if texture.cube_map:
self.AutomaticLightCreationOff()
# disable spherical harmonics was added in 9.1.0
if hasattr(self, 'UseSphericalHarmonicsOff'):
self.UseSphericalHarmonicsOff()
self.UseImageBasedLightingOn()
self.SetEnvironmentTexture(texture, is_srgb)
self.Modified()
def remove_environment_texture(self):
"""Remove the environment texture.
Examples
--------
>>> from pyvista import examples
>>> import pyvista as pv
>>> pl = pv.Plotter(lighting=None)
>>> cubemap = examples.download_sky_box_cube_map()
>>> _ = pl.add_mesh(
... pv.Sphere(), pbr=True, metallic=0.9, roughness=0.4
... )
>>> pl.set_environment_texture(cubemap)
>>> pl.remove_environment_texture()
>>> pl.camera_position = 'xy'
>>> pl.show()
"""
self.UseImageBasedLightingOff()
self.SetEnvironmentTexture(None)
self.Modified()
def close(self):
"""Close out widgets and sensitive elements."""
self.RemoveAllObservers()
if hasattr(self, 'axes_widget'):
self.hide_axes() # Necessary to avoid segfault
self.axes_actor = None
del self.axes_widget
if self._empty_str is not None:
self._empty_str.SetReferenceCount(0)
self._empty_str = None
def on_plotter_render(self):
"""Notify renderer components of explicit plotter render call."""
if self._charts is not None:
for chart in self._charts:
# Notify Charts that plotter.render() is called
chart._render_event(plotter_render=True)
def deep_clean(self, render=False):
"""Clean the renderer of the memory.
Parameters
----------
render : bool, optional
Render the render window after removing the bounding box
(if applicable).
"""
if self.cube_axes_actor is not None:
self.cube_axes_actor = None
if hasattr(self, 'edl_pass'):
del self.edl_pass
if hasattr(self, '_box_object'):
self.remove_bounding_box(render=render)
if hasattr(self, '_shadow_pass') and self._shadow_pass is not None:
self.disable_shadows()
try:
if self._charts is not None:
self._charts.deep_clean()
self._charts = None
except AttributeError: # pragma: no cover
pass
self._render_passes.deep_clean()
self.remove_floors(render=render)
self.remove_legend(render=render)
self.RemoveAllViewProps()
self._actors = {}
self._camera = None
self._bounding_box = None
self._marker_actor = None
self._border_actor = None
# remove reference to parent last
self.parent = None
def __del__(self):
"""Delete the renderer."""
self.deep_clean()
def enable_hidden_line_removal(self):
"""Enable hidden line removal."""
self.UseHiddenLineRemovalOn()
def disable_hidden_line_removal(self):
"""Disable hidden line removal."""
self.UseHiddenLineRemovalOff()
@property
def layer(self): # numpydoc ignore=RT01
"""Return or set the current layer of this renderer."""
return self.GetLayer()
@layer.setter
def layer(self, layer): # numpydoc ignore=GL08
self.SetLayer(layer)
@property
def viewport(self): # numpydoc ignore=RT01
"""Viewport of the renderer.
Viewport describes the ``(xstart, ystart, xend, yend)`` square
of the renderer relative to the main renderer window.
For example, a renderer taking up the entire window will have
a viewport of ``(0.0, 0.0, 1.0, 1.0)``, while the viewport of
a renderer on the left-hand side of a horizontally split window
would be ``(0.0, 0.0, 0.5, 1.0)``.
Returns
-------
tuple
Viewport in the form ``(xstart, ystart, xend, yend)``.
Examples
--------
Show the viewport of a renderer taking up half the render
window.
>>> import pyvista as pv
>>> pl = pv.Plotter(shape=(1, 2))
>>> _ = pl.add_mesh(pv.Sphere())
>>> pl.renderers[0].viewport
(0.0, 0.0, 0.5, 1.0)
Change viewport to half size.
>>> pl.renderers[0].viewport = (0.125, 0.25, 0.375, 0.75)
>>> pl.show()
"""
return self.GetViewport()
@viewport.setter
def viewport(self, viewport): # numpydoc ignore=GL08
self.SetViewport(viewport)
@property
def width(self): # numpydoc ignore=RT01
"""Width of the renderer."""
xmin, _, xmax, _ = self.viewport
return self.parent.window_size[0] * (xmax - xmin)
@property
def height(self): # numpydoc ignore=RT01
"""Height of the renderer."""
_, ymin, _, ymax = self.viewport
return self.parent.window_size[1] * (ymax - ymin)
def add_legend(
self,
labels=None,
bcolor=None,
border=False,
size=(0.2, 0.2),
name=None,
loc='upper right',
face=None,
font_family=None,
background_opacity=1.0,
):
"""Add a legend to render window.
Entries must be a list containing one string and color entry for each
item.
Parameters
----------
labels : list, optional
When set to ``None``, uses existing labels as specified by
- :func:`add_mesh <Plotter.add_mesh>`
- :func:`add_lines <Plotter.add_lines>`
- :func:`add_points <Plotter.add_points>`
List containing one entry for each item to be added to the
legend. Each entry can contain one of the following:
* Two strings ([label, color]), where ``label`` is the name of the
item to add, and ``color`` is the color of the label to add.
* Three strings ([label, color, face]) where ``label`` is the name
of the item to add, ``color`` is the color of the label to add,
and ``face`` is a string which defines the face (i.e. ``circle``,
``triangle``, ``box``, etc.).
``face`` could be also ``"none"`` (no face shown for the entry),
or a :class:`pyvista.PolyData`.
* A dict with the key ``label``. Optionally you can add the
keys ``color`` and ``face``. The values of these keys can be
strings. For the ``face`` key, it can be also a
:class:`pyvista.PolyData`.
bcolor : ColorLike, default: (0.5, 0.5, 0.5)
Background color, either a three item 0 to 1 RGB color
list, or a matplotlib color string (e.g. ``'w'`` or ``'white'``
for a white color). If None, legend background is
disabled.
border : bool, default: False
Controls if there will be a border around the legend.
Default False.
size : sequence[float], default: (0.2, 0.2)
Two float sequence, each float between 0 and 1. For example
``(0.1, 0.1)`` would make the legend 10% the size of the
entire figure window.
name : str, optional
The name for the added actor so that it can be easily
updated. If an actor of this name already exists in the
rendering window, it will be replaced by the new actor.
loc : str, default: "upper right"
Location string. One of the following:
* ``'upper right'``
* ``'upper left'``
* ``'lower left'``
* ``'lower right'``
* ``'center left'``
* ``'center right'``
* ``'lower center'``
* ``'upper center'``
* ``'center'``
face : str | pyvista.PolyData, optional
Face shape of legend face. Defaults to a triangle for most meshes,
with the exception of glyphs where the glyph is shown
(e.g. arrows).
You may set it to one of the following:
* None: ``"none"``
* Line: ``"-"`` or ``"line"``
* Triangle: ``"^"`` or ``'triangle'``
* Circle: ``"o"`` or ``'circle'``
* Rectangle: ``"r"`` or ``'rectangle'``
* Custom: :class:`pyvista.PolyData`
Passing ``"none"`` removes the legend face. A custom face can be
created using :class:`pyvista.PolyData`. This will be rendered
from the XY plane.
font_family : str, optional
Font family. Must be either ``'courier'``, ``'times'``,
or ``'arial'``. Defaults to :attr:`pyvista.global_theme.font.family
<pyvista.plotting.themes._Font.family>`.
background_opacity : float, default: 1.0
Set background opacity.
Returns
-------
vtk.vtkLegendBoxActor
Actor for the legend.
Examples
--------
Create a legend by labeling the meshes when using ``add_mesh``
>>> import pyvista as pv
>>> from pyvista import examples
>>> sphere = pv.Sphere(center=(0, 0, 1))
>>> cube = pv.Cube()
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(
... sphere, 'grey', smooth_shading=True, label='Sphere'
... )
>>> _ = plotter.add_mesh(cube, 'r', label='Cube')
>>> _ = plotter.add_legend(bcolor='w', face=None)
>>> plotter.show()
Alternatively provide labels in the plotter.
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(sphere, 'grey', smooth_shading=True)
>>> _ = plotter.add_mesh(cube, 'r')
>>> legend_entries = []
>>> legend_entries.append(['My Mesh', 'w'])
>>> legend_entries.append(['My Other Mesh', 'k'])
>>> _ = plotter.add_legend(legend_entries)
>>> plotter.show()
"""
if self.legend is not None:
self.remove_legend()
self._legend = _vtk.vtkLegendBoxActor()
if labels is None:
# use existing labels
if not self._labels:
raise ValueError(
'No labels input.\n\n'
'Add labels to individual items when adding them to'
'the plotting object with the "label=" parameter. '
'or enter them as the "labels" parameter.',
)
self._legend.SetNumberOfEntries(len(self._labels))
for i, (vtk_object, text, color) in enumerate(self._labels.values()):
if face is not None:
vtk_object = make_legend_face(face)
self._legend.SetEntry(i, vtk_object, text, color.float_rgb)
else:
self._legend.SetNumberOfEntries(len(labels))
for i, args in enumerate(labels):
face_ = None
if isinstance(args, (list, tuple)):
if len(args) == 2:
# format labels = [[ text1, color1], [ text2, color2], etc]
text, color = args
else:
# format labels = [[ text1, color1, face1], [ text2, color2, face2], etc]
# Pikcing only the first 3 elements
text, color, face_ = args[:3]
elif isinstance(args, dict):
# it is using a dict
text = args.pop('label')
color = args.pop('color', None)
face_ = args.pop('face', None)
if args:
warnings.warn(
f"Some of the arguments given to legend are not used.\n{args}",
)
elif isinstance(args, str):
# Only passing label
text = args
# taking the currents (if any)
try:
face_, _, color = list(self._labels.values())[i]
except (AttributeError, IndexError):
# There are no values
face_ = None
color = None
else:
raise ValueError(
f"The object passed to the legend ({type(args)}) is not valid.",
)
legend_face = make_legend_face(face_ or face)
self._legend.SetEntry(i, legend_face, text, Color(color).float_rgb)
if loc is not None:
if loc not in ACTOR_LOC_MAP:
allowed = '\n'.join([f'\t * "{item}"' for item in ACTOR_LOC_MAP])
raise ValueError(f'Invalid loc "{loc}". Expected one of the following:\n{allowed}')
x, y, size = map_loc_to_pos(loc, size, border=0.05)
self._legend.SetPosition(x, y)
self._legend.SetPosition2(size[0], size[1])
if bcolor is None:
self._legend.SetUseBackground(False)
else:
self._legend.SetUseBackground(True)
self._legend.SetBackgroundColor(Color(bcolor).float_rgb)
self._legend.SetBorder(border)
if font_family is None:
font_family = self._theme.font.family
font_family = parse_font_family(font_family)
self._legend.GetEntryTextProperty().SetFontFamily(font_family)
self._legend.SetBackgroundOpacity(background_opacity)
self.add_actor(self._legend, reset_camera=False, name=name, pickable=False)
return self._legend
def remove_legend(self, render=True):
"""Remove the legend actor.
Parameters
----------
render : bool, default: True
Render upon actor removal. Set this to ``False`` to stop
the render window from rendering when a the legend is removed.
Examples
--------
>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(mesh, label='sphere')
>>> _ = pl.add_legend()
>>> pl.remove_legend()
"""
if self.legend is not None:
self.remove_actor(self.legend, reset_camera=False, render=render)
self._legend = None
@property
def legend(self): # numpydoc ignore=RT01
"""Legend actor."""
return self._legend
def add_ruler(
self,
pointa,
pointb,
flip_range=False,
number_labels=None,
show_labels=True,
font_size_factor=0.6,
label_size_factor=1.0,
label_format=None,
title="Distance",
number_minor_ticks=0,
tick_length=5,
minor_tick_length=3,
show_ticks=True,
tick_label_offset=2,
label_color=None,
tick_color=None,
scale=1.0,
):
"""Add ruler.
The ruler is a 2D object that is not occluded by 3D objects.
To avoid issues with perspective, it is recommended to use
parallel projection, i.e. :func:`Plotter.enable_parallel_projection`,
and place the ruler orthogonal to the viewing direction.
The title and labels are placed to the right of ruler moving from
``pointa`` to ``pointb``. Use ``flip_range`` to flip the ``0`` location,
if needed.
Since the ruler is placed in an overlay on the viewing scene, the camera
does not automatically reset to include the ruler in the view.
Parameters
----------
pointa : sequence[float]
Starting point for ruler.
pointb : sequence[float]
Ending point for ruler.
flip_range : bool, default: False
If ``True``, the distance range goes from ``pointb`` to ``pointa``.
number_labels : int, optional
Number of labels to place on ruler.
If not supplied, the number will be adjusted for "nice" values.
show_labels : bool, default: True
Whether to show labels.
font_size_factor : float, default: 0.6
Factor to scale font size overall.
label_size_factor : float, default: 1.0
Factor to scale label size relative to title size.
label_format : str, optional
A printf style format for labels, e.g. '%E'.
title : str, default: "Distance"
The title to display.
number_minor_ticks : int, default: 0
Number of minor ticks between major ticks.
tick_length : int, default: 5
Length of ticks in pixels.
minor_tick_length : int, default: 3
Length of minor ticks in pixels.
show_ticks : bool, default: True
Whether to show the ticks.
tick_label_offset : int, default: 2
Offset between tick and label in pixels.
label_color : ColorLike, optional
Either a string, rgb list, or hex color string for
label and title colors.
.. warning::
This is either white or black.
tick_color : ColorLike, optional
Either a string, rgb list, or hex color string for
tick line colors.
scale : float, default: 1.0
Scale factor for the ruler.
.. versionadded:: 0.44.0
Returns
-------
vtk.vtkActor
VTK actor of the ruler.
Examples
--------
>>> import pyvista as pv
>>> cone = pv.Cone(height=2.0, radius=0.5)
>>> plotter = pv.Plotter()
>>> _ = plotter.add_mesh(cone)
Measure x direction of cone and place ruler slightly below.
>>> _ = plotter.add_ruler(
... pointa=[cone.bounds[0], cone.bounds[2] - 0.1, 0.0],
... pointb=[cone.bounds[1], cone.bounds[2] - 0.1, 0.0],
... title="X Distance",
... )
Measure y direction of cone and place ruler slightly to left.
The title and labels are placed to the right of the ruler when
traveling from ``pointa`` to ``pointb``.
>>> _ = plotter.add_ruler(
... pointa=[cone.bounds[0] - 0.1, cone.bounds[3], 0.0],
... pointb=[cone.bounds[0] - 0.1, cone.bounds[2], 0.0],
... flip_range=True,
... title="Y Distance",
... )
>>> plotter.enable_parallel_projection()
>>> plotter.view_xy()
>>> plotter.show()
"""
label_color = Color(label_color, default_color=self._theme.font.color)
tick_color = Color(tick_color, default_color=self._theme.font.color)
ruler = _vtk.vtkAxisActor2D()
ruler.GetPositionCoordinate().SetCoordinateSystemToWorld()
ruler.GetPosition2Coordinate().SetCoordinateSystemToWorld()
ruler.GetPositionCoordinate().SetReferenceCoordinate(None)
ruler.GetPositionCoordinate().SetValue(pointa[0], pointa[1], pointa[2])
ruler.GetPosition2Coordinate().SetValue(pointb[0], pointb[1], pointb[2])
distance = np.linalg.norm(np.asarray(pointa) - np.asarray(pointb))
if flip_range:
ruler.SetRange(distance * scale, 0)
else:
ruler.SetRange(0, distance * scale)
ruler.SetTitle(title)
ruler.SetFontFactor(font_size_factor)
ruler.SetLabelFactor(label_size_factor)
if number_labels is not None:
ruler.AdjustLabelsOff()
ruler.SetNumberOfLabels(number_labels)
ruler.SetLabelVisibility(show_labels)
if label_format:
ruler.SetLabelFormat(label_format)
ruler.GetProperty().SetColor(*tick_color.int_rgb)
if label_color != Color('white'):
# This property turns black if set
ruler.GetLabelTextProperty().SetColor(*label_color.int_rgb)
ruler.GetTitleTextProperty().SetColor(*label_color.int_rgb)
ruler.SetNumberOfMinorTicks(number_minor_ticks)
ruler.SetTickVisibility(show_ticks)
ruler.SetTickLength(tick_length)
ruler.SetMinorTickLength(minor_tick_length)
ruler.SetTickOffset(tick_label_offset)
self.add_actor(ruler, reset_camera=True, pickable=False)
return ruler
def add_legend_scale(
self,
corner_offset_factor=2.0,
bottom_border_offset=30,
top_border_offset=30,
left_border_offset=30,
right_border_offset=30,
bottom_axis_visibility=True,
top_axis_visibility=True,
left_axis_visibility=True,
right_axis_visibility=True,
legend_visibility=True,
xy_label_mode=False,
render=True,
color=None,
font_size_factor=0.6,
label_size_factor=1.0,
label_format=None,
number_minor_ticks=0,
tick_length=5,
minor_tick_length=3,
show_ticks=True,
tick_label_offset=2,
):
"""Annotate the render window with scale and distance information.
Its basic goal is to provide an indication of the scale of the scene.
Four axes surrounding the render window indicate (in a variety of ways)
the scale of what the camera is viewing. An option also exists for
displaying a scale legend.
Parameters
----------
corner_offset_factor : float, default: 2.0
The corner offset value.
bottom_border_offset : int, default: 30
Bottom border offset. Recommended value ``50``.
top_border_offset : int, default: 30
Top border offset. Recommended value ``50``.
left_border_offset : int, default: 30
Left border offset. Recommended value ``100``.
right_border_offset : int, default: 30
Right border offset. Recommended value ``100``.
bottom_axis_visibility : bool, default: True
Whether the bottom axis is visible.
top_axis_visibility : bool, default: True
Whether the top axis is visible.
left_axis_visibility : bool, default: True
Whether the left axis is visible.
right_axis_visibility : bool, default: True
Whether the right axis is visible.
legend_visibility : bool, default: True
Whether the legend scale is visible.
xy_label_mode : bool, default: False
The axes can be programmed either to display distance scales
or x-y coordinate values. By default,
the scales display a distance. However, if you know that the
view is down the z-axis, the scales can be programmed to display
x-y coordinate values.
render : bool, default: True
Whether to render when the actor is added.
color : ColorLike, optional
Either a string, rgb list, or hex color string for tick text
and tick line colors.
.. warning::
The axis labels tend to be either white or black.
font_size_factor : float, default: 0.6
Factor to scale font size overall.
label_size_factor : float, default: 1.0
Factor to scale label size relative to title size.
label_format : str, optional
A printf style format for labels, e.g. ``'%E'``.
See :ref:`old-string-formatting`.
number_minor_ticks : int, default: 0
Number of minor ticks between major ticks.
tick_length : int, default: 5
Length of ticks in pixels.
minor_tick_length : int, default: 3
Length of minor ticks in pixels.
show_ticks : bool, default: True
Whether to show the ticks.
tick_label_offset : int, default: 2
Offset between tick and label in pixels.
Returns
-------
vtk.vtkActor
The actor for the added ``vtkLegendScaleActor``.
Warnings
--------
Please be aware that the axes and scale values are subject to perspective
effects. The distances are computed in the focal plane of the camera. When
there are large view angles (i.e., perspective projection), the computed
distances may provide users the wrong sense of scale. These effects are not
present when parallel projection is enabled.
Examples
--------
>>> import pyvista as pv
>>> cone = pv.Cone(height=2.0, radius=0.5)
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(cone)
>>> _ = pl.add_legend_scale()
>>> pl.show()
"""
color = Color(color, default_color=self._theme.font.color)
legend_scale = _vtk.vtkLegendScaleActor()
legend_scale.SetCornerOffsetFactor(corner_offset_factor)
legend_scale.SetLegendVisibility(legend_visibility)
if xy_label_mode:
legend_scale.SetLabelModeToXYCoordinates()
else:
legend_scale.SetLabelModeToDistance()
legend_scale.SetBottomAxisVisibility(bottom_axis_visibility)
legend_scale.SetBottomBorderOffset(bottom_border_offset)
legend_scale.SetLeftAxisVisibility(left_axis_visibility)
legend_scale.SetLeftBorderOffset(left_border_offset)
legend_scale.SetRightAxisVisibility(right_axis_visibility)
legend_scale.SetRightBorderOffset(right_border_offset)
legend_scale.SetTopAxisVisibility(top_axis_visibility)
legend_scale.SetTopBorderOffset(top_border_offset)
for text in ['Label', 'Title']:
prop = getattr(legend_scale, f'GetLegend{text}Property')()
if color != Color('white'):
# This property turns black if set
prop.SetColor(*color.int_rgb)
prop.SetFontSize(
int(font_size_factor * 20),
) # hack to avoid multiple font size arguments
for ax in ['Bottom', 'Left', 'Right', 'Top']:
axis = getattr(legend_scale, f'Get{ax}Axis')()
axis.GetProperty().SetColor(*color.int_rgb)
if color != Color('white'):
# This label property turns black if set
axis.GetLabelTextProperty().SetColor(*color.int_rgb)
axis.SetFontFactor(font_size_factor)
axis.SetLabelFactor(label_size_factor)
if label_format:
axis.SetLabelFormat(label_format)
axis.SetNumberOfMinorTicks(number_minor_ticks)
axis.SetTickLength(tick_length)
axis.SetMinorTickLength(minor_tick_length)
axis.SetTickVisibility(show_ticks)
axis.SetTickOffset(tick_label_offset)
return self.add_actor(
legend_scale,
reset_camera=False,
name='_vtkLegendScaleActor',
culling=False,
pickable=False,
render=render,
)
def _line_for_legend():
"""Create a simple line-like rectangle for the legend."""
points = [
[0, 0, 0],
[0.4, 0, 0],
[0.4, 0.07, 0],
[0, 0.07, 0],
[
0.5,
0,
0,
], # last point needed to expand the bounds of the PolyData to be rendered smaller
]
legendface = pyvista.PolyData()
legendface.points = np.array(points)
legendface.faces = [4, 0, 1, 2, 3]
return legendface
|