# PaCkAgE DaTaStReAm
LNFmatplotlib-docs-27 1 3945
# end of header
0707010001f954000081a400001782000005de00000001570a54fc00000329000002600000050a00000000000000000000001e00000000LNFmatplotlib-docs-27/pkginfo CLASSES=none
PSTAMP=q20160410152828
LICFILE=python.txt
LICURL=http://www.python.org/2.4/license.html
LICINFO=Python Software Foundation License 2.4 (GPL compatible)
DESC=This package contains additional documentation for the matplotlib. Matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. matplotlib can be used in python scripts, the python and ipython shell (ala matlab or mathematica), web application servers, and various graphical user interface toolkits.
BASEDIR=/usr/share/doc
VENDOR=LINOFEE, http://www.linofee.org
EMAIL=developers@linofee.org
CATEGORY=graphics,application
NAME=Python 2.7 plotting library - documentation
SERIALNUM=001
VERSION=1.5.1
ARCH=i386
PKG=LNFmatplotlib-docs-27
0707010001f953000081a400001782000005de00000001570a54fd0000b93d000002600000050a00000000000000000000001d00000000LNFmatplotlib-docs-27/pkgmap : 1 3945
1 d none matplotlib 0755 bin bin
1 f none matplotlib/CHANGELOG 0644 bin bin 219811 14292 1452481568
1 f none matplotlib/CONTRIBUTING.md 0644 bin bin 88 8178 1433715168
1 f none matplotlib/PKG-INFO 0644 bin bin 1068 26520 1452481659
1 f none matplotlib/README.rst 0644 bin bin 1340 56914 1452481568
1 d none matplotlib/examples 0755 bin bin
1 f none matplotlib/examples/README.txt 0644 bin bin 1695 20562 1452480193
1 d none matplotlib/examples/animation 0755 bin bin
1 f none matplotlib/examples/animation/animate_decay.py 0644 bin bin 876 504 1451879122
1 f none matplotlib/examples/animation/basic_example.py 0644 bin bin 887 3730 1451879122
1 f none matplotlib/examples/animation/basic_example_writer.py 0644 bin bin 1182 30281 1451879122
1 f none matplotlib/examples/animation/bayes_update.py 0644 bin bin 1468 48160 1451879122
1 f none matplotlib/examples/animation/double_pendulum_animated.py 0644 bin bin 2331 47166 1452480193
1 f none matplotlib/examples/animation/dynamic_image.py 0644 bin bin 570 45377 1451879122
1 f none matplotlib/examples/animation/dynamic_image2.py 0644 bin bin 764 60398 1451879122
1 f none matplotlib/examples/animation/histogram.py 0644 bin bin 1734 13998 1451879122
1 f none matplotlib/examples/animation/moviewriter.py 0644 bin bin 907 9416 1451879122
1 f none matplotlib/examples/animation/rain.py 0644 bin bin 2313 59480 1451879122
1 f none matplotlib/examples/animation/random_data.py 0644 bin bin 380 32062 1451879122
1 f none matplotlib/examples/animation/simple_3danim.py 0644 bin bin 1799 12056 1451879122
1 f none matplotlib/examples/animation/simple_anim.py 0644 bin bin 598 48391 1451879122
1 f none matplotlib/examples/animation/strip_chart_demo.py 0644 bin bin 1512 50191 1451879122
1 f none matplotlib/examples/animation/subplots.py 0644 bin bin 3553 6498 1451879122
1 f none matplotlib/examples/animation/unchained.py 0644 bin bin 1858 19897 1451879122
1 d none matplotlib/examples/api 0755 bin bin
1 f none matplotlib/examples/api/README.txt 0644 bin bin 1493 2362 1433715168
1 f none matplotlib/examples/api/agg_oo.py 0644 bin bin 419 35935 1451879122
1 f none matplotlib/examples/api/barchart_demo.py 0644 bin bin 1039 15074 1451879122
1 f none matplotlib/examples/api/bbox_intersect.py 0644 bin bin 502 40105 1451879122
1 f none matplotlib/examples/api/collections_demo.py 0644 bin bin 4155 28247 1451879122
1 f none matplotlib/examples/api/colorbar_only.py 0644 bin bin 3005 22763 1451879122
1 f none matplotlib/examples/api/compound_path.py 0644 bin bin 825 2484 1451879122
1 f none matplotlib/examples/api/custom_projection_example.py 0644 bin bin 18187 38903 1452480193
1 f none matplotlib/examples/api/custom_scale_example.py 0644 bin bin 6369 52535 1452480193
1 f none matplotlib/examples/api/date_demo.py 0644 bin bin 2014 47131 1451879122
1 f none matplotlib/examples/api/date_index_formatter.py 0644 bin bin 1102 30361 1451879122
1 f none matplotlib/examples/api/demo_affine_image.py 0644 bin bin 1698 62699 1452136290
1 f none matplotlib/examples/api/donut_demo.py 0644 bin bin 1525 53338 1451879122
1 f none matplotlib/examples/api/engineering_formatter.py 0644 bin bin 402 34419 1451879122
1 f none matplotlib/examples/api/filled_step.py 0644 bin bin 6446 49497 1452481568
1 f none matplotlib/examples/api/font_family_rc.py 0644 bin bin 785 65243 1452480193
1 f none matplotlib/examples/api/font_file.py 0644 bin bin 1170 34297 1451879122
1 f none matplotlib/examples/api/histogram_path_demo.py 0644 bin bin 1455 63874 1451879122
1 f none matplotlib/examples/api/image_zcoord.py 0644 bin bin 642 50741 1451879122
1 f none matplotlib/examples/api/joinstyle.py 0644 bin bin 818 63530 1451879122
1 f none matplotlib/examples/api/legend_demo.py 0644 bin bin 488 40185 1451879122
1 f none matplotlib/examples/api/line_with_text.py 0644 bin bin 1671 5106 1451879122
1 f none matplotlib/examples/api/logo2.py 0644 bin bin 2749 11826 1451879122
1 f none matplotlib/examples/api/mathtext_asarray.py 0644 bin bin 707 58296 1451879122
1 f none matplotlib/examples/api/patch_collection.py 0644 bin bin 1269 33922 1451879122
1 f none matplotlib/examples/api/power_norm_demo.py 0644 bin bin 831 208 1451879122
1 f none matplotlib/examples/api/quad_bezier.py 0644 bin bin 435 34817 1451879122
1 f none matplotlib/examples/api/radar_chart.py 0644 bin bin 7632 23508 1451879122
1 f none matplotlib/examples/api/sankey_demo_basics.py 0644 bin bin 3410 6564 1451879122
1 f none matplotlib/examples/api/sankey_demo_links.py 0644 bin bin 1735 5417 1451879122
1 f none matplotlib/examples/api/sankey_demo_old.py 0755 bin bin 7404 6092 1451879122
1 f none matplotlib/examples/api/sankey_demo_rankine.py 0644 bin bin 3810 14027 1451879122
1 f none matplotlib/examples/api/scatter_piecharts.py 0644 bin bin 1364 41203 1451879122
1 f none matplotlib/examples/api/skewt.py 0644 bin bin 12500 18088 1451879122
1 f none matplotlib/examples/api/span_regions.py 0644 bin bin 783 2004 1451879122
1 f none matplotlib/examples/api/two_scales.py 0644 bin bin 1264 43826 1451879122
1 f none matplotlib/examples/api/unicode_minus.py 0644 bin bin 555 49903 1451877792
1 f none matplotlib/examples/api/watermark_image.py 0644 bin bin 506 42766 1451879122
1 f none matplotlib/examples/api/watermark_text.py 0644 bin bin 394 31325 1451877792
1 d none matplotlib/examples/axes_grid 0755 bin bin
1 f none matplotlib/examples/axes_grid/demo_axes_divider.py 0644 bin bin 3104 54247 1452480193
1 f none matplotlib/examples/axes_grid/demo_axes_grid.py 0644 bin bin 3984 25402 1452480193
1 f none matplotlib/examples/axes_grid/demo_axes_grid2.py 0644 bin bin 3488 53398 1452480193
1 f none matplotlib/examples/axes_grid/demo_axes_hbox_divider.py 0644 bin bin 1535 52764 1452480193
1 f none matplotlib/examples/axes_grid/demo_axes_rgb.py 0644 bin bin 1847 6135 1452480193
1 f none matplotlib/examples/axes_grid/demo_axisline_style.py 0644 bin bin 523 42621 1452480193
1 f none matplotlib/examples/axes_grid/demo_colorbar_with_inset_locator.py 0644 bin bin 1068 13377 1452480193
1 f none matplotlib/examples/axes_grid/demo_curvelinear_grid.py 0644 bin bin 4083 53655 1452480193
1 f none matplotlib/examples/axes_grid/demo_curvelinear_grid2.py 0644 bin bin 1851 1330 1452480193
1 f none matplotlib/examples/axes_grid/demo_edge_colorbar.py 0644 bin bin 2605 54144 1452480193
1 f none matplotlib/examples/axes_grid/demo_floating_axes.py 0644 bin bin 4347 21883 1452480193
1 f none matplotlib/examples/axes_grid/demo_floating_axis.py 0644 bin bin 2116 24607 1452480193
1 f none matplotlib/examples/axes_grid/demo_imagegrid_aspect.py 0644 bin bin 399 30360 1452480193
1 f none matplotlib/examples/axes_grid/demo_parasite_axes2.py 0644 bin bin 1198 25948 1452480193
1 f none matplotlib/examples/axes_grid/inset_locator_demo.py 0644 bin bin 998 9485 1452480193
1 f none matplotlib/examples/axes_grid/inset_locator_demo2.py 0644 bin bin 1248 38077 1452480193
1 f none matplotlib/examples/axes_grid/make_room_for_ylabel_using_axesgrid.py 0644 bin bin 1700 58922 1452480193
1 f none matplotlib/examples/axes_grid/parasite_simple2.py 0644 bin bin 1251 34345 1452480193
1 f none matplotlib/examples/axes_grid/scatter_hist.py 0644 bin bin 1558 5403 1452480193
1 f none matplotlib/examples/axes_grid/simple_anchored_artists.py 0644 bin bin 1951 14493 1452480193
1 f none matplotlib/examples/axes_grid/simple_axesgrid.py 0644 bin bin 467 35608 1452480193
1 f none matplotlib/examples/axes_grid/simple_axesgrid2.py 0644 bin bin 856 64136 1452480193
1 f none matplotlib/examples/axes_grid/simple_axisline4.py 0644 bin bin 558 46388 1452480193
1 d none matplotlib/examples/color 0755 bin bin
1 f none matplotlib/examples/color/color_cycle_demo.py 0644 bin bin 1206 34533 1451879122
1 f none matplotlib/examples/color/colormaps_reference.py 0644 bin bin 3676 24617 1451879122
1 f none matplotlib/examples/color/named_colors.py 0644 bin bin 1967 29391 1452480193
1 d none matplotlib/examples/event_handling 0755 bin bin
1 f none matplotlib/examples/event_handling/README.txt 0644 bin bin 561 51317 1451879122
1 f none matplotlib/examples/event_handling/close_event.py 0644 bin bin 255 21919 1451879122
1 f none matplotlib/examples/event_handling/data_browser.py 0644 bin bin 2345 42090 1451879122
1 f none matplotlib/examples/event_handling/figure_axes_enter_leave.py 0644 bin bin 1434 62429 1451879122
1 f none matplotlib/examples/event_handling/idle_and_timeout.py 0644 bin bin 797 468 1451879122
1 f none matplotlib/examples/event_handling/keypress_demo.py 0755 bin bin 549 46149 1451879122
1 f none matplotlib/examples/event_handling/lasso_demo.py 0644 bin bin 2467 62868 1451879122
1 f none matplotlib/examples/event_handling/legend_picking.py 0644 bin bin 1292 41122 1441943628
1 f none matplotlib/examples/event_handling/looking_glass.py 0644 bin bin 1280 36733 1451879122
1 f none matplotlib/examples/event_handling/path_editor.py 0644 bin bin 4373 13938 1451879122
1 f none matplotlib/examples/event_handling/pick_event_demo.py 0755 bin bin 6353 62247 1451879122
1 f none matplotlib/examples/event_handling/pick_event_demo2.py 0644 bin bin 1028 16904 1451879122
1 f none matplotlib/examples/event_handling/pipong.py 0755 bin bin 8969 47524 1451879122
1 f none matplotlib/examples/event_handling/poly_editor.py 0644 bin bin 5546 36726 1451879122
1 f none matplotlib/examples/event_handling/pong_gtk.py 0755 bin bin 790 5137 1451879122
1 f none matplotlib/examples/event_handling/resample.py 0644 bin bin 1565 61480 1451879122
1 f none matplotlib/examples/event_handling/test_mouseclicks.py 0755 bin bin 793 64101 1441943628
1 f none matplotlib/examples/event_handling/timers.py 0644 bin bin 790 3699 1451879122
1 f none matplotlib/examples/event_handling/trifinder_event_demo.py 0644 bin bin 1771 21867 1441943628
1 f none matplotlib/examples/event_handling/viewlims.py 0644 bin bin 2889 39295 1451879122
1 f none matplotlib/examples/event_handling/zoom_window.py 0644 bin bin 1156 30798 1451879122
1 d none matplotlib/examples/images_contours_and_fields 0755 bin bin
1 f none matplotlib/examples/images_contours_and_fields/contourf_log.py 0644 bin bin 1347 45931 1451879122
1 f none matplotlib/examples/images_contours_and_fields/image_demo.py 0644 bin bin 256 22433 1451879122
1 f none matplotlib/examples/images_contours_and_fields/image_demo_clip_path.py 0644 bin bin 424 37173 1441943628
1 f none matplotlib/examples/images_contours_and_fields/interpolation_methods.py 0644 bin bin 1018 19887 1452136290
1 f none matplotlib/examples/images_contours_and_fields/interpolation_none_vs_nearest.py 0644 bin bin 2435 7021 1451879122
1 f none matplotlib/examples/images_contours_and_fields/pcolormesh_levels.py 0644 bin bin 1547 64797 1451879122
1 f none matplotlib/examples/images_contours_and_fields/streamplot_demo_features.py 0644 bin bin 789 64518 1451879122
1 f none matplotlib/examples/images_contours_and_fields/streamplot_demo_masking.py 0644 bin bin 590 47276 1451879122
1 f none matplotlib/examples/images_contours_and_fields/streamplot_demo_start_points.py 0644 bin bin 785 63182 1451879122
1 d none matplotlib/examples/lines_bars_and_markers 0755 bin bin
1 f none matplotlib/examples/lines_bars_and_markers/barh_demo.py 0644 bin bin 511 43882 1451879122
1 f none matplotlib/examples/lines_bars_and_markers/fill_demo.py 0644 bin bin 207 16493 1441943628
1 f none matplotlib/examples/lines_bars_and_markers/fill_demo_features.py 0644 bin bin 426 34786 1441943628
1 f none matplotlib/examples/lines_bars_and_markers/line_demo_dash_control.py 0644 bin bin 396 32689 1451879122
1 f none matplotlib/examples/lines_bars_and_markers/line_styles_reference.py 0644 bin bin 772 64675 1451876921
1 f none matplotlib/examples/lines_bars_and_markers/marker_fillstyle_reference.py 0644 bin bin 888 9509 1451876921
1 f none matplotlib/examples/lines_bars_and_markers/marker_reference.py 0644 bin bin 2003 36379 1451879122
1 f none matplotlib/examples/lines_bars_and_markers/scatter_with_legend.py 0644 bin bin 305 23476 1451876921
1 d none matplotlib/examples/misc 0755 bin bin
1 f none matplotlib/examples/misc/contour_manual.py 0644 bin bin 1678 2448 1451879122
1 f none matplotlib/examples/misc/font_indexing.py 0644 bin bin 1343 47750 1452480193
1 f none matplotlib/examples/misc/ftface_props.py 0755 bin bin 2421 59424 1452480193
1 f none matplotlib/examples/misc/image_thumbnail.py 0644 bin bin 906 12810 1451879122
1 f none matplotlib/examples/misc/longshort.py 0644 bin bin 1660 11526 1451879122
1 f none matplotlib/examples/misc/multiprocess.py 0644 bin bin 2157 30076 1452480193
1 f none matplotlib/examples/misc/rasterization_demo.py 0644 bin bin 1216 34455 1441943628
1 f none matplotlib/examples/misc/rc_traits.py 0644 bin bin 5520 16807 1451879122
1 f none matplotlib/examples/misc/rec_groupby_demo.py 0644 bin bin 2067 46820 1451879122
1 f none matplotlib/examples/misc/rec_join_demo.py 0644 bin bin 830 65458 1451879122
1 f none matplotlib/examples/misc/sample_data_demo.py 0644 bin bin 349 31374 1441943628
1 f none matplotlib/examples/misc/svg_filter_line.py 0644 bin bin 2146 39581 1452481568
1 f none matplotlib/examples/misc/svg_filter_pie.py 0644 bin bin 2853 36736 1452481568
1 f none matplotlib/examples/misc/tight_bbox_test.py 0644 bin bin 507 40772 1451879122
1 d none matplotlib/examples/mplot3d 0755 bin bin
1 f none matplotlib/examples/mplot3d/2dcollections3d_demo.py 0644 bin bin 487 37868 1451879122
1 f none matplotlib/examples/mplot3d/bars3d_demo.py 0644 bin bin 559 44503 1451879122
1 f none matplotlib/examples/mplot3d/contour3d_demo.py 0644 bin bin 293 25439 1451879122
1 f none matplotlib/examples/mplot3d/contour3d_demo2.py 0644 bin bin 295 25698 1451879122
1 f none matplotlib/examples/mplot3d/contour3d_demo3.py 0644 bin bin 579 47972 1451879122
1 f none matplotlib/examples/mplot3d/contourf3d_demo.py 0644 bin bin 281 24448 1451879122
1 f none matplotlib/examples/mplot3d/contourf3d_demo2.py 0644 bin bin 673 55450 1451879122
1 f none matplotlib/examples/mplot3d/custom_shaded_3d_surface.py 0644 bin bin 1071 26650 1451879122
1 f none matplotlib/examples/mplot3d/hist3d_demo.py 0644 bin bin 571 47185 1451879122
1 f none matplotlib/examples/mplot3d/lines3d_demo.py 0644 bin bin 404 33388 1451879122
1 f none matplotlib/examples/mplot3d/lorenz_attractor.py 0644 bin bin 1272 34776 1451879122
1 f none matplotlib/examples/mplot3d/mixed_subplots_demo.py 0644 bin bin 1047 11095 1451879122
1 f none matplotlib/examples/mplot3d/offset_demo.py 0644 bin bin 796 2178 1451879122
1 f none matplotlib/examples/mplot3d/pathpatch3d_demo.py 0644 bin bin 1527 53056 1441943628
1 f none matplotlib/examples/mplot3d/polys3d_demo.py 0644 bin bin 789 63033 1451879122
1 f none matplotlib/examples/mplot3d/quiver3d_demo.py 0644 bin bin 552 40154 1452480193
1 f none matplotlib/examples/mplot3d/rotate_axes3d_demo.py 0644 bin bin 312 26135 1451879122
1 f none matplotlib/examples/mplot3d/scatter3d_demo.py 0644 bin bin 529 41378 1451879122
1 f none matplotlib/examples/mplot3d/subplot3d_demo.py 0644 bin bin 850 3663 1451879122
1 f none matplotlib/examples/mplot3d/surface3d_demo.py 0644 bin bin 660 54905 1451879122
1 f none matplotlib/examples/mplot3d/surface3d_demo2.py 0644 bin bin 422 34381 1451879122
1 f none matplotlib/examples/mplot3d/surface3d_demo3.py 0644 bin bin 739 60355 1451879122
1 f none matplotlib/examples/mplot3d/surface3d_radial_demo.py 0644 bin bin 670 56187 1451879122
1 f none matplotlib/examples/mplot3d/text3d_demo.py 0644 bin bin 626 45925 1451879122
1 f none matplotlib/examples/mplot3d/tricontour3d_demo.py 0644 bin bin 962 18337 1451879122
1 f none matplotlib/examples/mplot3d/tricontourf3d_demo.py 0644 bin bin 963 18439 1451879122
1 f none matplotlib/examples/mplot3d/trisurf3d_demo.py 0644 bin bin 849 6493 1451879122
1 f none matplotlib/examples/mplot3d/trisurf3d_demo2.py 0644 bin bin 1763 17235 1451879122
1 f none matplotlib/examples/mplot3d/wire3d_animation_demo.py 0644 bin bin 845 602 1451879122
1 f none matplotlib/examples/mplot3d/wire3d_demo.py 0644 bin bin 254 21898 1451879122
1 f none matplotlib/examples/mplot3d/wire3d_zero_stride.py 0644 bin bin 411 35185 1451879122
1 d none matplotlib/examples/pie_and_polar_charts 0755 bin bin
1 f none matplotlib/examples/pie_and_polar_charts/pie_demo_features.py 0644 bin bin 2091 42822 1451879122
1 f none matplotlib/examples/pie_and_polar_charts/polar_bar_demo.py 0644 bin bin 465 37729 1451879122
1 f none matplotlib/examples/pie_and_polar_charts/polar_scatter_demo.py 0644 bin bin 490 41299 1451879122
1 d none matplotlib/examples/pylab_examples 0755 bin bin
1 f none matplotlib/examples/pylab_examples/README 0644 bin bin 890 12216 1451879122
1 f none matplotlib/examples/pylab_examples/accented_text.py 0644 bin bin 679 59137 1451879122
1 f none matplotlib/examples/pylab_examples/agg_buffer.py 0755 bin bin 910 11944 1451879122
1 f none matplotlib/examples/pylab_examples/agg_buffer_to_array.py 0644 bin bin 409 35237 1451879122
1 f none matplotlib/examples/pylab_examples/alignment_test.py 0644 bin bin 2209 49824 1451879122
1 f none matplotlib/examples/pylab_examples/anchored_artists.py 0644 bin bin 3992 24125 1451879122
1 f none matplotlib/examples/pylab_examples/animation_demo.py 0644 bin bin 569 44600 1451879122
1 f none matplotlib/examples/pylab_examples/annotation_demo.py 0644 bin bin 5610 51524 1451879122
1 f none matplotlib/examples/pylab_examples/annotation_demo2.py 0644 bin bin 6463 14554 1451879122
1 f none matplotlib/examples/pylab_examples/annotation_demo3.py 0644 bin bin 3284 27157 1451879122
1 f none matplotlib/examples/pylab_examples/anscombe.py 0755 bin bin 1899 6554 1451879122
1 f none matplotlib/examples/pylab_examples/arctest.py 0644 bin bin 300 22639 1451879122
1 f none matplotlib/examples/pylab_examples/arrow_demo.py 0644 bin bin 9182 52673 1452480193
1 f none matplotlib/examples/pylab_examples/arrow_simple_demo.py 0644 bin bin 135 10671 1441943628
1 f none matplotlib/examples/pylab_examples/aspect_loglog.py 0644 bin bin 454 36635 1451879122
1 f none matplotlib/examples/pylab_examples/axes_demo.py 0644 bin bin 858 3732 1452480193
1 f none matplotlib/examples/pylab_examples/axes_props.py 0644 bin bin 584 49336 1451879122
1 f none matplotlib/examples/pylab_examples/axes_zoom_effect.py 0644 bin bin 3303 60876 1451879122
1 f none matplotlib/examples/pylab_examples/axhspan_demo.py 0644 bin bin 762 61606 1451879122
1 f none matplotlib/examples/pylab_examples/axis_equal_demo.py 0644 bin bin 778 64544 1451879122
1 f none matplotlib/examples/pylab_examples/bar_stacked.py 0644 bin bin 726 55732 1451879122
1 f none matplotlib/examples/pylab_examples/barb_demo.py 0644 bin bin 1771 5879 1451879122
1 f none matplotlib/examples/pylab_examples/barchart_demo.py 0644 bin bin 998 7440 1450239869
1 f none matplotlib/examples/pylab_examples/barchart_demo2.py 0644 bin bin 5492 27793 1452481568
1 f none matplotlib/examples/pylab_examples/barcode_demo.py 0644 bin bin 539 43666 1451879122
1 f none matplotlib/examples/pylab_examples/boxplot_demo.py 0644 bin bin 1288 40228 1451879122
1 f none matplotlib/examples/pylab_examples/boxplot_demo2.py 0644 bin bin 4453 43695 1452480193
1 f none matplotlib/examples/pylab_examples/boxplot_demo3.py 0644 bin bin 1206 27495 1451879122
1 f none matplotlib/examples/pylab_examples/break.py 0644 bin bin 135 11354 1451879122
1 f none matplotlib/examples/pylab_examples/broken_axis.py 0644 bin bin 2525 9248 1451879122
1 f none matplotlib/examples/pylab_examples/broken_barh.py 0644 bin bin 717 54857 1451879122
1 f none matplotlib/examples/pylab_examples/centered_ticklabels.py 0644 bin bin 1674 15988 1451879122
1 f none matplotlib/examples/pylab_examples/cohere_demo.py 0644 bin bin 864 2468 1451879122
1 f none matplotlib/examples/pylab_examples/color_by_yvalue.py 0644 bin bin 425 35248 1451879122
1 f none matplotlib/examples/pylab_examples/color_demo.py 0644 bin bin 740 60437 1452480193
1 f none matplotlib/examples/pylab_examples/colorbar_tick_labelling_demo.py 0644 bin bin 1000 20926 1451879122
1 f none matplotlib/examples/pylab_examples/colours.py 0644 bin bin 1333 32277 1451879122
1 f none matplotlib/examples/pylab_examples/contour_corner_mask.py 0644 bin bin 881 7228 1451879122
1 f none matplotlib/examples/pylab_examples/contour_demo.py 0755 bin bin 3496 19672 1451879122
1 f none matplotlib/examples/pylab_examples/contour_image.py 0755 bin bin 3493 28702 1451879122
1 f none matplotlib/examples/pylab_examples/contour_label_demo.py 0644 bin bin 2306 43248 1451879122
1 f none matplotlib/examples/pylab_examples/contourf_demo.py 0755 bin bin 3246 63450 1451879122
1 f none matplotlib/examples/pylab_examples/contourf_hatching.py 0755 bin bin 1359 30228 1451879122
1 f none matplotlib/examples/pylab_examples/coords_demo.py 0755 bin bin 1011 18660 1451879122
1 f none matplotlib/examples/pylab_examples/coords_report.py 0644 bin bin 302 24889 1451879122
1 f none matplotlib/examples/pylab_examples/csd_demo.py 0644 bin bin 873 3049 1451879122
1 f none matplotlib/examples/pylab_examples/cursor_demo.py 0755 bin bin 2235 43996 1452480193
1 f none matplotlib/examples/pylab_examples/custom_cmap.py 0644 bin bin 5759 19806 1451879122
1 f none matplotlib/examples/pylab_examples/custom_figure_class.py 0644 bin bin 644 52889 1451879122
1 f none matplotlib/examples/pylab_examples/custom_ticker1.py 0755 bin bin 838 7363 1451879122
1 f none matplotlib/examples/pylab_examples/customize_rc.py 0644 bin bin 1403 50992 1451879122
1 f none matplotlib/examples/pylab_examples/dashpointlabel.py 0644 bin bin 851 56962 1451879122
1 f none matplotlib/examples/pylab_examples/data_helper.py 0755 bin bin 1500 44787 1451879122
1 f none matplotlib/examples/pylab_examples/date_demo1.py 0644 bin bin 1503 2535 1451879122
1 f none matplotlib/examples/pylab_examples/date_demo2.py 0755 bin bin 1183 39152 1451879122
1 f none matplotlib/examples/pylab_examples/date_demo_convert.py 0644 bin bin 978 20123 1451879122
1 f none matplotlib/examples/pylab_examples/date_demo_rrule.py 0644 bin bin 912 14173 1451879122
1 f none matplotlib/examples/pylab_examples/date_index_formatter.py 0644 bin bin 1268 43312 1451879122
1 f none matplotlib/examples/pylab_examples/demo_agg_filter.py 0644 bin bin 9321 49334 1451879122
1 f none matplotlib/examples/pylab_examples/demo_annotation_box.py 0644 bin bin 2460 35962 1452136290
1 f none matplotlib/examples/pylab_examples/demo_bboximage.py 0644 bin bin 1815 58938 1451879122
1 f none matplotlib/examples/pylab_examples/demo_ribbon_box.py 0644 bin bin 4287 44913 1451879122
1 f none matplotlib/examples/pylab_examples/demo_text_path.py 0644 bin bin 4446 15368 1451879122
1 f none matplotlib/examples/pylab_examples/demo_text_rotation_mode.py 0644 bin bin 1427 37625 1451879122
1 f none matplotlib/examples/pylab_examples/demo_tight_layout.py 0644 bin bin 2528 17467 1452480193
1 f none matplotlib/examples/pylab_examples/dolphin.py 0644 bin bin 3540 37525 1451879122
1 f none matplotlib/examples/pylab_examples/ellipse_collection.py 0644 bin bin 572 46749 1451879122
1 f none matplotlib/examples/pylab_examples/ellipse_demo.py 0644 bin bin 472 38705 1451879122
1 f none matplotlib/examples/pylab_examples/ellipse_rotated.py 0644 bin bin 375 29988 1451879122
1 f none matplotlib/examples/pylab_examples/equal_aspect_ratio.py 0755 bin bin 417 34044 1451879122
1 f none matplotlib/examples/pylab_examples/errorbar_limits.py 0644 bin bin 845 1164 1451879122
1 f none matplotlib/examples/pylab_examples/errorbar_subsample.py 0644 bin bin 636 55064 1441943628
1 f none matplotlib/examples/pylab_examples/eventcollection_demo.py 0644 bin bin 1442 54809 1441943628
1 f none matplotlib/examples/pylab_examples/eventplot_demo.py 0755 bin bin 1889 23702 1441943628
1 f none matplotlib/examples/pylab_examples/fancyarrow_demo.py 0644 bin bin 1397 32418 1452480193
1 f none matplotlib/examples/pylab_examples/fancybox_demo.py 0644 bin bin 4594 59060 1451879122
1 f none matplotlib/examples/pylab_examples/fancybox_demo2.py 0644 bin bin 548 43307 1451879122
1 f none matplotlib/examples/pylab_examples/fancytextbox_demo.py 0644 bin bin 516 30869 1451879122
1 f none matplotlib/examples/pylab_examples/figimage_demo.py 0644 bin bin 407 33320 1451879122
1 f none matplotlib/examples/pylab_examples/figlegend_demo.py 0644 bin bin 483 34638 1451879122
1 f none matplotlib/examples/pylab_examples/figure_title.py 0644 bin bin 596 46988 1451879122
1 f none matplotlib/examples/pylab_examples/fill_between_demo.py 0644 bin bin 2129 51499 1451879122
1 f none matplotlib/examples/pylab_examples/fill_betweenx_demo.py 0644 bin bin 1589 3308 1451879122
1 f none matplotlib/examples/pylab_examples/fill_spiral.py 0644 bin bin 472 35321 1451879122
1 f none matplotlib/examples/pylab_examples/finance_demo.py 0644 bin bin 1105 30710 1451879122
1 f none matplotlib/examples/pylab_examples/finance_work2.py 0644 bin bin 6293 56916 1452480193
1 f none matplotlib/examples/pylab_examples/findobj_demo.py 0644 bin bin 826 2156 1451879122
1 f none matplotlib/examples/pylab_examples/font_table_ttf.py 0755 bin bin 1778 2869 1452480193
1 f none matplotlib/examples/pylab_examples/fonts_demo.py 0644 bin bin 2871 33592 1452480193
1 f none matplotlib/examples/pylab_examples/fonts_demo_kw.py 0644 bin bin 2105 33448 1452480193
1 f none matplotlib/examples/pylab_examples/ganged_plots.py 0644 bin bin 1047 21241 1451879122
1 f none matplotlib/examples/pylab_examples/geo_demo.py 0644 bin bin 348 30269 1451879122
1 f none matplotlib/examples/pylab_examples/ginput_demo.py 0644 bin bin 220 18853 1451879122
1 f none matplotlib/examples/pylab_examples/ginput_manual_clabel.py 0755 bin bin 2516 59040 1451879122
1 f none matplotlib/examples/pylab_examples/gradient_bar.py 0644 bin bin 743 57041 1451879122
1 f none matplotlib/examples/pylab_examples/griddata_demo.py 0644 bin bin 887 6531 1451876921
1 f none matplotlib/examples/pylab_examples/hatch_demo.py 0644 bin bin 1124 19555 1451879122
1 f none matplotlib/examples/pylab_examples/hexbin_demo.py 0644 bin bin 868 8579 1451879122
1 f none matplotlib/examples/pylab_examples/hexbin_demo2.py 0644 bin bin 1285 35339 1451879122
1 f none matplotlib/examples/pylab_examples/hist2d_demo.py 0644 bin bin 189 15926 1451879122
1 f none matplotlib/examples/pylab_examples/hist2d_log_demo.py 0644 bin bin 263 22512 1451879122
1 f none matplotlib/examples/pylab_examples/hist_colormapped.py 0644 bin bin 560 48450 1451879122
1 f none matplotlib/examples/pylab_examples/histogram_percent_demo.py 0644 bin bin 803 3375 1451879122
1 f none matplotlib/examples/pylab_examples/hyperlinks.py 0644 bin bin 874 5579 1451879122
1 f none matplotlib/examples/pylab_examples/image_clip_path.py 0755 bin bin 746 59500 1451879122
1 f none matplotlib/examples/pylab_examples/image_demo.py 0644 bin bin 532 40988 1451879122
1 f none matplotlib/examples/pylab_examples/image_demo2.py 0755 bin bin 509 41644 1451879122
1 f none matplotlib/examples/pylab_examples/image_interp.py 0644 bin bin 1986 44021 1451879122
1 f none matplotlib/examples/pylab_examples/image_masked.py 0644 bin bin 1940 24975 1451879122
1 f none matplotlib/examples/pylab_examples/image_nonuniform.py 0644 bin bin 1509 56737 1451879122
1 f none matplotlib/examples/pylab_examples/image_origin.py 0755 bin bin 718 62452 1452480193
1 f none matplotlib/examples/pylab_examples/image_slices_viewer.py 0644 bin bin 1030 14025 1451879122
1 f none matplotlib/examples/pylab_examples/interp_demo.py 0644 bin bin 299 24957 1451879122
1 f none matplotlib/examples/pylab_examples/invert_axes.py 0644 bin bin 356 29468 1451879122
1 f none matplotlib/examples/pylab_examples/layer_images.py 0644 bin bin 1199 32755 1451879122
1 f none matplotlib/examples/pylab_examples/leftventricle_bulleye.py 0644 bin bin 7352 38429 1451879122
1 f none matplotlib/examples/pylab_examples/legend_demo2.py 0644 bin bin 683 54492 1451879122
1 f none matplotlib/examples/pylab_examples/legend_demo3.py 0644 bin bin 671 55160 1451879122
1 f none matplotlib/examples/pylab_examples/legend_demo4.py 0644 bin bin 695 50959 1451879122
1 f none matplotlib/examples/pylab_examples/legend_demo5.py 0644 bin bin 2723 17328 1451879122
1 f none matplotlib/examples/pylab_examples/line_collection.py 0644 bin bin 1381 52030 1451879122
1 f none matplotlib/examples/pylab_examples/line_collection2.py 0644 bin bin 1396 53069 1451879122
1 f none matplotlib/examples/pylab_examples/load_converter.py 0644 bin bin 592 50105 1451879122
1 f none matplotlib/examples/pylab_examples/loadrec.py 0644 bin bin 558 49798 1451879122
1 f none matplotlib/examples/pylab_examples/log_bar.py 0644 bin bin 428 31400 1451879122
1 f none matplotlib/examples/pylab_examples/log_demo.py 0644 bin bin 758 62098 1451879122
1 f none matplotlib/examples/pylab_examples/log_test.py 0644 bin bin 150 12280 1451879122
1 f none matplotlib/examples/pylab_examples/logo.py 0755 bin bin 1003 18353 1452480193
1 f none matplotlib/examples/pylab_examples/major_minor_demo1.py 0644 bin bin 1698 21262 1451879122
1 f none matplotlib/examples/pylab_examples/major_minor_demo2.py 0644 bin bin 903 13949 1451879122
1 f none matplotlib/examples/pylab_examples/manual_axis.py 0644 bin bin 1967 27847 1451879122
1 f none matplotlib/examples/pylab_examples/marker_path.py 0644 bin bin 454 40491 1441943628
1 f none matplotlib/examples/pylab_examples/markevery_demo.py 0644 bin bin 3206 3879 1451879122
1 f none matplotlib/examples/pylab_examples/masked_demo.py 0644 bin bin 627 50067 1451879122
1 f none matplotlib/examples/pylab_examples/mathtext_demo.py 0755 bin bin 711 60499 1452480193
1 f none matplotlib/examples/pylab_examples/mathtext_examples.py 0755 bin bin 4337 11917 1452480193
1 f none matplotlib/examples/pylab_examples/matplotlib_icon.py 0644 bin bin 463 36642 1452480193
1 f none matplotlib/examples/pylab_examples/matshow.py 0755 bin bin 558 46129 1451879122
1 f none matplotlib/examples/pylab_examples/movie_demo.py 0755 bin bin 690 57937 1451879122
1 f none matplotlib/examples/pylab_examples/mri_demo.py 0755 bin bin 343 30017 1451879122
1 f none matplotlib/examples/pylab_examples/mri_with_eeg.py 0755 bin bin 2066 28800 1451879122
1 f none matplotlib/examples/pylab_examples/multi_image.py 0644 bin bin 2208 46713 1451879122
1 f none matplotlib/examples/pylab_examples/multicolored_line.py 0644 bin bin 1749 16033 1451879122
1 f none matplotlib/examples/pylab_examples/multiline.py 0644 bin bin 1127 22207 1451879122
1 f none matplotlib/examples/pylab_examples/multipage_pdf.py 0644 bin bin 1626 65056 1451879122
1 f none matplotlib/examples/pylab_examples/multiple_figs_demo.py 0644 bin bin 450 37180 1451879122
1 f none matplotlib/examples/pylab_examples/multiple_yaxis_with_spines.py 0644 bin bin 1577 1678 1451879122
1 f none matplotlib/examples/pylab_examples/nan_test.py 0755 bin bin 573 45053 1451879122
1 f none matplotlib/examples/pylab_examples/newscalarformatter_demo.py 0644 bin bin 3492 34325 1451879122
1 f none matplotlib/examples/pylab_examples/patheffect_demo.py 0644 bin bin 1562 51123 1451879122
1 f none matplotlib/examples/pylab_examples/pcolor_demo.py 0644 bin bin 1426 50142 1451879122
1 f none matplotlib/examples/pylab_examples/pcolor_log.py 0644 bin bin 671 54663 1451879122
1 f none matplotlib/examples/pylab_examples/pcolor_small.py 0644 bin bin 257 21452 1451879122
1 f none matplotlib/examples/pylab_examples/pie_demo2.py 0644 bin bin 1564 60576 1451879122
1 f none matplotlib/examples/pylab_examples/plotfile_demo.py 0644 bin bin 1195 31992 1451879122
1 f none matplotlib/examples/pylab_examples/polar_demo.py 0644 bin bin 333 27156 1451879122
1 f none matplotlib/examples/pylab_examples/polar_legend.py 0644 bin bin 601 48553 1452480193
1 f none matplotlib/examples/pylab_examples/print_stdout.py 0644 bin bin 233 20460 1451879122
1 f none matplotlib/examples/pylab_examples/psd_demo.py 0644 bin bin 537 40626 1451879122
1 f none matplotlib/examples/pylab_examples/psd_demo2.py 0644 bin bin 1452 52002 1451879122
1 f none matplotlib/examples/pylab_examples/psd_demo3.py 0644 bin bin 993 15815 1451879122
1 f none matplotlib/examples/pylab_examples/psd_demo_complex.py 0644 bin bin 1180 31620 1451879122
1 f none matplotlib/examples/pylab_examples/pythonic_matplotlib.py 0644 bin bin 2421 18743 1451879122
1 f none matplotlib/examples/pylab_examples/quadmesh_demo.py 0644 bin bin 1120 26880 1452480193
1 f none matplotlib/examples/pylab_examples/quiver_demo.py 0644 bin bin 2872 17829 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_custom_symbol.py 0644 bin bin 377 30453 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_demo2.py 0644 bin bin 1397 55569 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_hist.py 0644 bin bin 1210 39485 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_masked.py 0644 bin bin 545 43745 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_profile.py 0755 bin bin 658 41615 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_star_poly.py 0644 bin bin 633 49099 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_symbol.py 0644 bin bin 356 28019 1441943628
1 f none matplotlib/examples/pylab_examples/set_and_get.py 0644 bin bin 2567 9887 1451879122
1 f none matplotlib/examples/pylab_examples/shading_example.py 0644 bin bin 1719 9331 1451879122
1 f none matplotlib/examples/pylab_examples/shared_axis_across_figures.py 0644 bin bin 674 57615 1451879122
1 f none matplotlib/examples/pylab_examples/shared_axis_demo.py 0644 bin bin 1724 19023 1451879122
1 f none matplotlib/examples/pylab_examples/simple_plot.py 0644 bin bin 267 22200 1451879122
1 f none matplotlib/examples/pylab_examples/simple_plot_fps.py 0755 bin bin 750 60793 1451879122
1 f none matplotlib/examples/pylab_examples/specgram_demo.py 0644 bin bin 880 4611 1451879122
1 f none matplotlib/examples/pylab_examples/spectrum_demo.py 0644 bin bin 505 40533 1452480193
1 f none matplotlib/examples/pylab_examples/spine_placement_demo.py 0644 bin bin 2813 40759 1451879122
1 f none matplotlib/examples/pylab_examples/spy_demos.py 0644 bin bin 393 31863 1451879122
1 f none matplotlib/examples/pylab_examples/stackplot_demo.py 0644 bin bin 318 25254 1451879122
1 f none matplotlib/examples/pylab_examples/stackplot_demo2.py 0644 bin bin 625 43796 1451879122
1 f none matplotlib/examples/pylab_examples/stem_plot.py 0644 bin bin 255 21510 1451879122
1 f none matplotlib/examples/pylab_examples/step_demo.py 0644 bin bin 431 32925 1451879122
1 f none matplotlib/examples/pylab_examples/stix_fonts_demo.py 0755 bin bin 1491 56107 1451879122
1 f none matplotlib/examples/pylab_examples/stock_demo.py 0644 bin bin 431 36835 1451879122
1 f none matplotlib/examples/pylab_examples/subplot_demo.py 0644 bin bin 439 34310 1441943628
1 f none matplotlib/examples/pylab_examples/subplot_toolbar.py 0644 bin bin 318 26277 1451879122
1 f none matplotlib/examples/pylab_examples/subplots_adjust.py 0644 bin bin 334 27675 1451879122
1 f none matplotlib/examples/pylab_examples/subplots_demo.py 0644 bin bin 2192 53421 1451879122
1 f none matplotlib/examples/pylab_examples/symlog_demo.py 0755 bin bin 534 44278 1451879122
1 f none matplotlib/examples/pylab_examples/system_monitor.py 0644 bin bin 1794 14517 1452480193
1 f none matplotlib/examples/pylab_examples/table_demo.py 0644 bin bin 1716 64665 1451879122
1 f none matplotlib/examples/pylab_examples/tex_demo.py 0644 bin bin 996 20546 1451879122
1 f none matplotlib/examples/pylab_examples/tex_unicode_demo.py 0755 bin bin 739 61804 1451879122
1 f none matplotlib/examples/pylab_examples/text_handles.py 0644 bin bin 947 11614 1452480193
1 f none matplotlib/examples/pylab_examples/text_rotation.py 0644 bin bin 1432 54009 1451879122
1 f none matplotlib/examples/pylab_examples/text_rotation_relative_to_line.py 0644 bin bin 1320 45301 1451879122
1 f none matplotlib/examples/pylab_examples/titles_demo.py 0644 bin bin 333 28691 1441943628
1 f none matplotlib/examples/pylab_examples/toggle_images.py 0644 bin bin 1371 52099 1451879122
1 f none matplotlib/examples/pylab_examples/transoffset.py 0644 bin bin 1765 19354 1451879122
1 f none matplotlib/examples/pylab_examples/tricontour_demo.py 0644 bin bin 4613 48088 1451879122
1 f none matplotlib/examples/pylab_examples/tricontour_smooth_delaunay.py 0644 bin bin 5475 43020 1451879122
1 f none matplotlib/examples/pylab_examples/tricontour_smooth_user.py 0644 bin bin 2784 6363 1451879122
1 f none matplotlib/examples/pylab_examples/tricontour_vs_griddata.py 0644 bin bin 1483 56948 1451879122
1 f none matplotlib/examples/pylab_examples/trigradient_demo.py 0644 bin bin 3079 34145 1451879122
1 f none matplotlib/examples/pylab_examples/triinterp_demo.py 0644 bin bin 1703 8972 1441943628
1 f none matplotlib/examples/pylab_examples/tripcolor_demo.py 0644 bin bin 5058 21993 1451879122
1 f none matplotlib/examples/pylab_examples/triplot_demo.py 0644 bin bin 4427 33896 1451879122
1 f none matplotlib/examples/pylab_examples/usetex_baseline_test.py 0644 bin bin 2026 27259 1451879122
1 f none matplotlib/examples/pylab_examples/usetex_demo.py 0644 bin bin 2745 7979 1451879122
1 f none matplotlib/examples/pylab_examples/usetex_fonteffects.py 0644 bin bin 789 61282 1451879122
1 f none matplotlib/examples/pylab_examples/vline_hline_demo.py 0644 bin bin 658 52073 1451879122
1 f none matplotlib/examples/pylab_examples/webapp_demo.py 0644 bin bin 1715 10016 1451879122
1 f none matplotlib/examples/pylab_examples/xcorr_demo.py 0644 bin bin 406 33920 1452480193
1 f none matplotlib/examples/pylab_examples/zorder_demo.py 0755 bin bin 1633 5993 1451879122
1 d none matplotlib/examples/scales 0755 bin bin
1 f none matplotlib/examples/scales/scales.py 0644 bin bin 791 64936 1451879122
1 d none matplotlib/examples/shapes_and_collections 0755 bin bin
1 f none matplotlib/examples/shapes_and_collections/artist_reference.py 0644 bin bin 2824 29828 1451879122
1 f none matplotlib/examples/shapes_and_collections/path_patch_demo.py 0644 bin bin 781 57522 1441943628
1 f none matplotlib/examples/shapes_and_collections/scatter_demo.py 0644 bin bin 298 24124 1451879122
1 d none matplotlib/examples/showcase 0755 bin bin
1 f none matplotlib/examples/showcase/bachelors_degrees_by_gender.py 0644 bin bin 4489 34381 1451879122
1 f none matplotlib/examples/showcase/integral_demo.py 0644 bin bin 1298 40809 1451879122
1 f none matplotlib/examples/showcase/xkcd.py 0644 bin bin 1457 40783 1451879122
1 d none matplotlib/examples/specialty_plots 0755 bin bin
1 f none matplotlib/examples/specialty_plots/advanced_hillshading.py 0644 bin bin 1849 12487 1451879122
1 f none matplotlib/examples/specialty_plots/hinton_demo.py 0644 bin bin 1254 37297 1451879122
1 f none matplotlib/examples/specialty_plots/topographic_hillshading.py 0644 bin bin 3207 5256 1451879122
1 d none matplotlib/examples/statistics 0755 bin bin
1 f none matplotlib/examples/statistics/boxplot_color_demo.py 0644 bin bin 1187 27844 1451879122
1 f none matplotlib/examples/statistics/boxplot_demo.py 0644 bin bin 2677 35259 1451879122
1 f none matplotlib/examples/statistics/boxplot_vs_violin_demo.py 0644 bin bin 1197 35658 1451879122
1 f none matplotlib/examples/statistics/bxp_demo.py 0644 bin bin 2752 41951 1451879122
1 f none matplotlib/examples/statistics/errorbar_demo.py 0644 bin bin 199 16115 1451879122
1 f none matplotlib/examples/statistics/errorbar_demo_features.py 0644 bin bin 1188 37677 1451879122
1 f none matplotlib/examples/statistics/errorbar_limits.py 0644 bin bin 1380 48573 1451879122
1 f none matplotlib/examples/statistics/histogram_demo_cumulative.py 0644 bin bin 677 56259 1451876921
1 f none matplotlib/examples/statistics/histogram_demo_features.py 0644 bin bin 1041 23277 1451879122
1 f none matplotlib/examples/statistics/histogram_demo_histtypes.py 0644 bin bin 686 56860 1451876921
1 f none matplotlib/examples/statistics/histogram_demo_multihist.py 0644 bin bin 1032 22595 1451876921
1 f none matplotlib/examples/statistics/multiple_histograms_side_by_side.py 0644 bin bin 1314 47579 1451879122
1 f none matplotlib/examples/statistics/violinplot_demo.py 0644 bin bin 1729 9433 1451879122
1 d none matplotlib/examples/style_sheets 0755 bin bin
1 f none matplotlib/examples/style_sheets/plot_bmh.py 0644 bin bin 457 37930 1451879122
1 f none matplotlib/examples/style_sheets/plot_dark_background.py 0644 bin bin 569 49403 1451876921
1 f none matplotlib/examples/style_sheets/plot_fivethirtyeight.py 0644 bin bin 434 35966 1451879122
1 f none matplotlib/examples/style_sheets/plot_ggplot.py 0644 bin bin 1385 51522 1451879122
1 f none matplotlib/examples/style_sheets/plot_grayscale.py 0644 bin bin 823 3566 1451879122
1 d none matplotlib/examples/subplots_axes_and_figures 0755 bin bin
1 f none matplotlib/examples/subplots_axes_and_figures/fahrenheit_celsius_scales.py 0644 bin bin 881 8353 1451876921
1 f none matplotlib/examples/subplots_axes_and_figures/subplot_demo.py 0644 bin bin 439 34324 1441943628
1 d none matplotlib/examples/tests 0755 bin bin
1 f none matplotlib/examples/tests/backend_driver.py 0755 bin bin 15243 21980 1452481568
1 d none matplotlib/examples/text_labels_and_annotations 0755 bin bin
1 f none matplotlib/examples/text_labels_and_annotations/autowrap_demo.py 0644 bin bin 685 55547 1451879122
1 f none matplotlib/examples/text_labels_and_annotations/rainbow_text.py 0644 bin bin 1933 25191 1451879122
1 f none matplotlib/examples/text_labels_and_annotations/text_demo_fontdict.py 0644 bin bin 604 48479 1451879122
1 f none matplotlib/examples/text_labels_and_annotations/unicode_demo.py 0644 bin bin 421 38373 1451879122
1 d none matplotlib/examples/ticks_and_spines 0755 bin bin
1 f none matplotlib/examples/ticks_and_spines/spines_demo.py 0644 bin bin 746 65221 1451876921
1 f none matplotlib/examples/ticks_and_spines/spines_demo_bounds.py 0644 bin bin 791 1026 1451879122
1 f none matplotlib/examples/ticks_and_spines/spines_demo_dropped.py 0644 bin bin 672 59474 1441943628
1 f none matplotlib/examples/ticks_and_spines/tick_labels_from_values.py 0644 bin bin 955 19260 1451879122
1 f none matplotlib/examples/ticks_and_spines/ticklabels_demo_rotation.py 0644 bin bin 490 41579 1441943628
1 d none matplotlib/examples/units 0755 bin bin
1 f none matplotlib/examples/units/annotate_with_units.py 0644 bin bin 734 58897 1451879122
1 f none matplotlib/examples/units/artist_tests.py 0644 bin bin 1474 60608 1451879122
1 f none matplotlib/examples/units/bar_demo2.py 0644 bin bin 1076 27732 1451879122
1 f none matplotlib/examples/units/bar_unit_demo.py 0644 bin bin 849 1110 1451879122
1 f none matplotlib/examples/units/basic_units.py 0644 bin bin 11136 4384 1451879122
1 f none matplotlib/examples/units/ellipse_with_units.py 0644 bin bin 1834 17927 1451879122
1 f none matplotlib/examples/units/evans_test.py 0644 bin bin 2339 53158 1451879122
1 f none matplotlib/examples/units/radian_demo.py 0644 bin bin 530 46189 1441943628
1 f none matplotlib/examples/units/units_sample.py 0644 bin bin 948 16441 1451879122
1 f none matplotlib/examples/units/units_scatter.py 0644 bin bin 904 10050 1451879122
1 d none matplotlib/examples/user_interfaces 0755 bin bin
1 f none matplotlib/examples/user_interfaces/README.txt 0644 bin bin 525 47066 1433715168
1 f none matplotlib/examples/user_interfaces/README.wx 0644 bin bin 821 8065 1433715168
1 f none matplotlib/examples/user_interfaces/embedding_in_gtk.py 0644 bin bin 836 6739 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_gtk2.py 0644 bin bin 1459 64327 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_gtk3.py 0755 bin bin 835 6461 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_gtk3_panzoom.py 0644 bin bin 885 10510 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_qt4.py 0755 bin bin 4213 6773 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_qt4_wtoolbar.py 0644 bin bin 2225 51668 1451876921
1 f none matplotlib/examples/user_interfaces/embedding_in_qt5.py 0755 bin bin 4328 16407 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_tk.py 0755 bin bin 1423 56532 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_tk2.py 0644 bin bin 887 9365 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_tk_canvas.py 0755 bin bin 2044 43291 1452481568
1 f none matplotlib/examples/user_interfaces/embedding_in_wx2.py 0644 bin bin 2190 48437 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_wx3.py 0755 bin bin 4993 317 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_wx4.py 0644 bin bin 3375 197 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_wx5.py 0644 bin bin 1973 27120 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_webagg.py 0644 bin bin 8190 44512 1451879122
1 f none matplotlib/examples/user_interfaces/fourier_demo_wx.py 0644 bin bin 8955 20813 1451879122
1 f none matplotlib/examples/user_interfaces/gtk_spreadsheet.py 0644 bin bin 2466 61589 1451879122
1 f none matplotlib/examples/user_interfaces/histogram_demo_canvasagg.py 0644 bin bin 1392 50451 1451879122
1 f none matplotlib/examples/user_interfaces/interactive.py 0755 bin bin 8198 52624 1451879122
1 f none matplotlib/examples/user_interfaces/interactive2.py 0755 bin bin 11490 43987 1451879122
1 f none matplotlib/examples/user_interfaces/lineprops_dialog_gtk.py 0644 bin bin 514 39879 1451879122
1 f none matplotlib/examples/user_interfaces/mathtext_wx.py 0644 bin bin 3884 35000 1451879122
1 f none matplotlib/examples/user_interfaces/mpl_with_glade.glade 0644 bin bin 10021 21865 1433715168
1 f none matplotlib/examples/user_interfaces/mpl_with_glade.py 0755 bin bin 3147 54706 1451879122
1 f none matplotlib/examples/user_interfaces/mpl_with_glade_316.glade 0644 bin bin 858 4905 1451879122
1 f none matplotlib/examples/user_interfaces/mpl_with_glade_316.py 0644 bin bin 1102 25553 1451879122
1 f none matplotlib/examples/user_interfaces/pylab_with_gtk.py 0644 bin bin 1431 57168 1451879122
1 f none matplotlib/examples/user_interfaces/rec_edit_gtk_custom.py 0644 bin bin 1310 51639 1451879122
1 f none matplotlib/examples/user_interfaces/rec_edit_gtk_simple.py 0644 bin bin 489 44090 1451879122
1 f none matplotlib/examples/user_interfaces/svg_histogram.py 0755 bin bin 4555 57579 1452481568
1 f none matplotlib/examples/user_interfaces/svg_tooltip.py 0644 bin bin 3328 7532 1452481568
1 f none matplotlib/examples/user_interfaces/toolmanager.py 0644 bin bin 2879 28669 1452480193
1 f none matplotlib/examples/user_interfaces/wxcursor_demo.py 0644 bin bin 2349 52703 1451879122
1 d none matplotlib/examples/widgets 0755 bin bin
1 f none matplotlib/examples/widgets/README.txt 0644 bin bin 77 7148 1433715168
1 f none matplotlib/examples/widgets/buttons.py 0644 bin bin 895 3104 1451879122
1 f none matplotlib/examples/widgets/check_buttons.py 0644 bin bin 740 56943 1451879122
1 f none matplotlib/examples/widgets/cursor.py 0644 bin bin 417 34756 1452480193
1 f none matplotlib/examples/widgets/lasso_selector_demo.py 0644 bin bin 2781 30753 1451879122
1 f none matplotlib/examples/widgets/menu.py 0644 bin bin 4958 58021 1451879122
1 f none matplotlib/examples/widgets/multicursor.py 0644 bin bin 363 29705 1451877792
1 f none matplotlib/examples/widgets/radio_buttons.py 0644 bin bin 1017 14509 1451879122
1 f none matplotlib/examples/widgets/rectangle_selector.py 0644 bin bin 2198 40334 1451879122
1 f none matplotlib/examples/widgets/slider_demo.py 0644 bin bin 1184 28960 1452480193
1 f none matplotlib/examples/widgets/span_selector.py 0644 bin bin 1094 24659 1452480193
1 i pkginfo 809 6743 1460294908
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000b00000000TRAILER!!! 0707010001f954000081a400001782000005de00000001570a54fc00000329000002600000050a00000000000000000000000800000000pkginfo CLASSES=none
PSTAMP=q20160410152828
LICFILE=python.txt
LICURL=http://www.python.org/2.4/license.html
LICINFO=Python Software Foundation License 2.4 (GPL compatible)
DESC=This package contains additional documentation for the matplotlib. Matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. matplotlib can be used in python scripts, the python and ipython shell (ala matlab or mathematica), web application servers, and various graphical user interface toolkits.
BASEDIR=/usr/share/doc
VENDOR=LINOFEE, http://www.linofee.org
EMAIL=developers@linofee.org
CATEGORY=graphics,application
NAME=Python 2.7 plotting library - documentation
SERIALNUM=001
VERSION=1.5.1
ARCH=i386
PKG=LNFmatplotlib-docs-27
0707010001f953000081a400001782000005de00000001570a54fd0000b93d000002600000050a00000000000000000000000700000000pkgmap : 1 3945
1 d none matplotlib 0755 bin bin
1 f none matplotlib/CHANGELOG 0644 bin bin 219811 14292 1452481568
1 f none matplotlib/CONTRIBUTING.md 0644 bin bin 88 8178 1433715168
1 f none matplotlib/PKG-INFO 0644 bin bin 1068 26520 1452481659
1 f none matplotlib/README.rst 0644 bin bin 1340 56914 1452481568
1 d none matplotlib/examples 0755 bin bin
1 f none matplotlib/examples/README.txt 0644 bin bin 1695 20562 1452480193
1 d none matplotlib/examples/animation 0755 bin bin
1 f none matplotlib/examples/animation/animate_decay.py 0644 bin bin 876 504 1451879122
1 f none matplotlib/examples/animation/basic_example.py 0644 bin bin 887 3730 1451879122
1 f none matplotlib/examples/animation/basic_example_writer.py 0644 bin bin 1182 30281 1451879122
1 f none matplotlib/examples/animation/bayes_update.py 0644 bin bin 1468 48160 1451879122
1 f none matplotlib/examples/animation/double_pendulum_animated.py 0644 bin bin 2331 47166 1452480193
1 f none matplotlib/examples/animation/dynamic_image.py 0644 bin bin 570 45377 1451879122
1 f none matplotlib/examples/animation/dynamic_image2.py 0644 bin bin 764 60398 1451879122
1 f none matplotlib/examples/animation/histogram.py 0644 bin bin 1734 13998 1451879122
1 f none matplotlib/examples/animation/moviewriter.py 0644 bin bin 907 9416 1451879122
1 f none matplotlib/examples/animation/rain.py 0644 bin bin 2313 59480 1451879122
1 f none matplotlib/examples/animation/random_data.py 0644 bin bin 380 32062 1451879122
1 f none matplotlib/examples/animation/simple_3danim.py 0644 bin bin 1799 12056 1451879122
1 f none matplotlib/examples/animation/simple_anim.py 0644 bin bin 598 48391 1451879122
1 f none matplotlib/examples/animation/strip_chart_demo.py 0644 bin bin 1512 50191 1451879122
1 f none matplotlib/examples/animation/subplots.py 0644 bin bin 3553 6498 1451879122
1 f none matplotlib/examples/animation/unchained.py 0644 bin bin 1858 19897 1451879122
1 d none matplotlib/examples/api 0755 bin bin
1 f none matplotlib/examples/api/README.txt 0644 bin bin 1493 2362 1433715168
1 f none matplotlib/examples/api/agg_oo.py 0644 bin bin 419 35935 1451879122
1 f none matplotlib/examples/api/barchart_demo.py 0644 bin bin 1039 15074 1451879122
1 f none matplotlib/examples/api/bbox_intersect.py 0644 bin bin 502 40105 1451879122
1 f none matplotlib/examples/api/collections_demo.py 0644 bin bin 4155 28247 1451879122
1 f none matplotlib/examples/api/colorbar_only.py 0644 bin bin 3005 22763 1451879122
1 f none matplotlib/examples/api/compound_path.py 0644 bin bin 825 2484 1451879122
1 f none matplotlib/examples/api/custom_projection_example.py 0644 bin bin 18187 38903 1452480193
1 f none matplotlib/examples/api/custom_scale_example.py 0644 bin bin 6369 52535 1452480193
1 f none matplotlib/examples/api/date_demo.py 0644 bin bin 2014 47131 1451879122
1 f none matplotlib/examples/api/date_index_formatter.py 0644 bin bin 1102 30361 1451879122
1 f none matplotlib/examples/api/demo_affine_image.py 0644 bin bin 1698 62699 1452136290
1 f none matplotlib/examples/api/donut_demo.py 0644 bin bin 1525 53338 1451879122
1 f none matplotlib/examples/api/engineering_formatter.py 0644 bin bin 402 34419 1451879122
1 f none matplotlib/examples/api/filled_step.py 0644 bin bin 6446 49497 1452481568
1 f none matplotlib/examples/api/font_family_rc.py 0644 bin bin 785 65243 1452480193
1 f none matplotlib/examples/api/font_file.py 0644 bin bin 1170 34297 1451879122
1 f none matplotlib/examples/api/histogram_path_demo.py 0644 bin bin 1455 63874 1451879122
1 f none matplotlib/examples/api/image_zcoord.py 0644 bin bin 642 50741 1451879122
1 f none matplotlib/examples/api/joinstyle.py 0644 bin bin 818 63530 1451879122
1 f none matplotlib/examples/api/legend_demo.py 0644 bin bin 488 40185 1451879122
1 f none matplotlib/examples/api/line_with_text.py 0644 bin bin 1671 5106 1451879122
1 f none matplotlib/examples/api/logo2.py 0644 bin bin 2749 11826 1451879122
1 f none matplotlib/examples/api/mathtext_asarray.py 0644 bin bin 707 58296 1451879122
1 f none matplotlib/examples/api/patch_collection.py 0644 bin bin 1269 33922 1451879122
1 f none matplotlib/examples/api/power_norm_demo.py 0644 bin bin 831 208 1451879122
1 f none matplotlib/examples/api/quad_bezier.py 0644 bin bin 435 34817 1451879122
1 f none matplotlib/examples/api/radar_chart.py 0644 bin bin 7632 23508 1451879122
1 f none matplotlib/examples/api/sankey_demo_basics.py 0644 bin bin 3410 6564 1451879122
1 f none matplotlib/examples/api/sankey_demo_links.py 0644 bin bin 1735 5417 1451879122
1 f none matplotlib/examples/api/sankey_demo_old.py 0755 bin bin 7404 6092 1451879122
1 f none matplotlib/examples/api/sankey_demo_rankine.py 0644 bin bin 3810 14027 1451879122
1 f none matplotlib/examples/api/scatter_piecharts.py 0644 bin bin 1364 41203 1451879122
1 f none matplotlib/examples/api/skewt.py 0644 bin bin 12500 18088 1451879122
1 f none matplotlib/examples/api/span_regions.py 0644 bin bin 783 2004 1451879122
1 f none matplotlib/examples/api/two_scales.py 0644 bin bin 1264 43826 1451879122
1 f none matplotlib/examples/api/unicode_minus.py 0644 bin bin 555 49903 1451877792
1 f none matplotlib/examples/api/watermark_image.py 0644 bin bin 506 42766 1451879122
1 f none matplotlib/examples/api/watermark_text.py 0644 bin bin 394 31325 1451877792
1 d none matplotlib/examples/axes_grid 0755 bin bin
1 f none matplotlib/examples/axes_grid/demo_axes_divider.py 0644 bin bin 3104 54247 1452480193
1 f none matplotlib/examples/axes_grid/demo_axes_grid.py 0644 bin bin 3984 25402 1452480193
1 f none matplotlib/examples/axes_grid/demo_axes_grid2.py 0644 bin bin 3488 53398 1452480193
1 f none matplotlib/examples/axes_grid/demo_axes_hbox_divider.py 0644 bin bin 1535 52764 1452480193
1 f none matplotlib/examples/axes_grid/demo_axes_rgb.py 0644 bin bin 1847 6135 1452480193
1 f none matplotlib/examples/axes_grid/demo_axisline_style.py 0644 bin bin 523 42621 1452480193
1 f none matplotlib/examples/axes_grid/demo_colorbar_with_inset_locator.py 0644 bin bin 1068 13377 1452480193
1 f none matplotlib/examples/axes_grid/demo_curvelinear_grid.py 0644 bin bin 4083 53655 1452480193
1 f none matplotlib/examples/axes_grid/demo_curvelinear_grid2.py 0644 bin bin 1851 1330 1452480193
1 f none matplotlib/examples/axes_grid/demo_edge_colorbar.py 0644 bin bin 2605 54144 1452480193
1 f none matplotlib/examples/axes_grid/demo_floating_axes.py 0644 bin bin 4347 21883 1452480193
1 f none matplotlib/examples/axes_grid/demo_floating_axis.py 0644 bin bin 2116 24607 1452480193
1 f none matplotlib/examples/axes_grid/demo_imagegrid_aspect.py 0644 bin bin 399 30360 1452480193
1 f none matplotlib/examples/axes_grid/demo_parasite_axes2.py 0644 bin bin 1198 25948 1452480193
1 f none matplotlib/examples/axes_grid/inset_locator_demo.py 0644 bin bin 998 9485 1452480193
1 f none matplotlib/examples/axes_grid/inset_locator_demo2.py 0644 bin bin 1248 38077 1452480193
1 f none matplotlib/examples/axes_grid/make_room_for_ylabel_using_axesgrid.py 0644 bin bin 1700 58922 1452480193
1 f none matplotlib/examples/axes_grid/parasite_simple2.py 0644 bin bin 1251 34345 1452480193
1 f none matplotlib/examples/axes_grid/scatter_hist.py 0644 bin bin 1558 5403 1452480193
1 f none matplotlib/examples/axes_grid/simple_anchored_artists.py 0644 bin bin 1951 14493 1452480193
1 f none matplotlib/examples/axes_grid/simple_axesgrid.py 0644 bin bin 467 35608 1452480193
1 f none matplotlib/examples/axes_grid/simple_axesgrid2.py 0644 bin bin 856 64136 1452480193
1 f none matplotlib/examples/axes_grid/simple_axisline4.py 0644 bin bin 558 46388 1452480193
1 d none matplotlib/examples/color 0755 bin bin
1 f none matplotlib/examples/color/color_cycle_demo.py 0644 bin bin 1206 34533 1451879122
1 f none matplotlib/examples/color/colormaps_reference.py 0644 bin bin 3676 24617 1451879122
1 f none matplotlib/examples/color/named_colors.py 0644 bin bin 1967 29391 1452480193
1 d none matplotlib/examples/event_handling 0755 bin bin
1 f none matplotlib/examples/event_handling/README.txt 0644 bin bin 561 51317 1451879122
1 f none matplotlib/examples/event_handling/close_event.py 0644 bin bin 255 21919 1451879122
1 f none matplotlib/examples/event_handling/data_browser.py 0644 bin bin 2345 42090 1451879122
1 f none matplotlib/examples/event_handling/figure_axes_enter_leave.py 0644 bin bin 1434 62429 1451879122
1 f none matplotlib/examples/event_handling/idle_and_timeout.py 0644 bin bin 797 468 1451879122
1 f none matplotlib/examples/event_handling/keypress_demo.py 0755 bin bin 549 46149 1451879122
1 f none matplotlib/examples/event_handling/lasso_demo.py 0644 bin bin 2467 62868 1451879122
1 f none matplotlib/examples/event_handling/legend_picking.py 0644 bin bin 1292 41122 1441943628
1 f none matplotlib/examples/event_handling/looking_glass.py 0644 bin bin 1280 36733 1451879122
1 f none matplotlib/examples/event_handling/path_editor.py 0644 bin bin 4373 13938 1451879122
1 f none matplotlib/examples/event_handling/pick_event_demo.py 0755 bin bin 6353 62247 1451879122
1 f none matplotlib/examples/event_handling/pick_event_demo2.py 0644 bin bin 1028 16904 1451879122
1 f none matplotlib/examples/event_handling/pipong.py 0755 bin bin 8969 47524 1451879122
1 f none matplotlib/examples/event_handling/poly_editor.py 0644 bin bin 5546 36726 1451879122
1 f none matplotlib/examples/event_handling/pong_gtk.py 0755 bin bin 790 5137 1451879122
1 f none matplotlib/examples/event_handling/resample.py 0644 bin bin 1565 61480 1451879122
1 f none matplotlib/examples/event_handling/test_mouseclicks.py 0755 bin bin 793 64101 1441943628
1 f none matplotlib/examples/event_handling/timers.py 0644 bin bin 790 3699 1451879122
1 f none matplotlib/examples/event_handling/trifinder_event_demo.py 0644 bin bin 1771 21867 1441943628
1 f none matplotlib/examples/event_handling/viewlims.py 0644 bin bin 2889 39295 1451879122
1 f none matplotlib/examples/event_handling/zoom_window.py 0644 bin bin 1156 30798 1451879122
1 d none matplotlib/examples/images_contours_and_fields 0755 bin bin
1 f none matplotlib/examples/images_contours_and_fields/contourf_log.py 0644 bin bin 1347 45931 1451879122
1 f none matplotlib/examples/images_contours_and_fields/image_demo.py 0644 bin bin 256 22433 1451879122
1 f none matplotlib/examples/images_contours_and_fields/image_demo_clip_path.py 0644 bin bin 424 37173 1441943628
1 f none matplotlib/examples/images_contours_and_fields/interpolation_methods.py 0644 bin bin 1018 19887 1452136290
1 f none matplotlib/examples/images_contours_and_fields/interpolation_none_vs_nearest.py 0644 bin bin 2435 7021 1451879122
1 f none matplotlib/examples/images_contours_and_fields/pcolormesh_levels.py 0644 bin bin 1547 64797 1451879122
1 f none matplotlib/examples/images_contours_and_fields/streamplot_demo_features.py 0644 bin bin 789 64518 1451879122
1 f none matplotlib/examples/images_contours_and_fields/streamplot_demo_masking.py 0644 bin bin 590 47276 1451879122
1 f none matplotlib/examples/images_contours_and_fields/streamplot_demo_start_points.py 0644 bin bin 785 63182 1451879122
1 d none matplotlib/examples/lines_bars_and_markers 0755 bin bin
1 f none matplotlib/examples/lines_bars_and_markers/barh_demo.py 0644 bin bin 511 43882 1451879122
1 f none matplotlib/examples/lines_bars_and_markers/fill_demo.py 0644 bin bin 207 16493 1441943628
1 f none matplotlib/examples/lines_bars_and_markers/fill_demo_features.py 0644 bin bin 426 34786 1441943628
1 f none matplotlib/examples/lines_bars_and_markers/line_demo_dash_control.py 0644 bin bin 396 32689 1451879122
1 f none matplotlib/examples/lines_bars_and_markers/line_styles_reference.py 0644 bin bin 772 64675 1451876921
1 f none matplotlib/examples/lines_bars_and_markers/marker_fillstyle_reference.py 0644 bin bin 888 9509 1451876921
1 f none matplotlib/examples/lines_bars_and_markers/marker_reference.py 0644 bin bin 2003 36379 1451879122
1 f none matplotlib/examples/lines_bars_and_markers/scatter_with_legend.py 0644 bin bin 305 23476 1451876921
1 d none matplotlib/examples/misc 0755 bin bin
1 f none matplotlib/examples/misc/contour_manual.py 0644 bin bin 1678 2448 1451879122
1 f none matplotlib/examples/misc/font_indexing.py 0644 bin bin 1343 47750 1452480193
1 f none matplotlib/examples/misc/ftface_props.py 0755 bin bin 2421 59424 1452480193
1 f none matplotlib/examples/misc/image_thumbnail.py 0644 bin bin 906 12810 1451879122
1 f none matplotlib/examples/misc/longshort.py 0644 bin bin 1660 11526 1451879122
1 f none matplotlib/examples/misc/multiprocess.py 0644 bin bin 2157 30076 1452480193
1 f none matplotlib/examples/misc/rasterization_demo.py 0644 bin bin 1216 34455 1441943628
1 f none matplotlib/examples/misc/rc_traits.py 0644 bin bin 5520 16807 1451879122
1 f none matplotlib/examples/misc/rec_groupby_demo.py 0644 bin bin 2067 46820 1451879122
1 f none matplotlib/examples/misc/rec_join_demo.py 0644 bin bin 830 65458 1451879122
1 f none matplotlib/examples/misc/sample_data_demo.py 0644 bin bin 349 31374 1441943628
1 f none matplotlib/examples/misc/svg_filter_line.py 0644 bin bin 2146 39581 1452481568
1 f none matplotlib/examples/misc/svg_filter_pie.py 0644 bin bin 2853 36736 1452481568
1 f none matplotlib/examples/misc/tight_bbox_test.py 0644 bin bin 507 40772 1451879122
1 d none matplotlib/examples/mplot3d 0755 bin bin
1 f none matplotlib/examples/mplot3d/2dcollections3d_demo.py 0644 bin bin 487 37868 1451879122
1 f none matplotlib/examples/mplot3d/bars3d_demo.py 0644 bin bin 559 44503 1451879122
1 f none matplotlib/examples/mplot3d/contour3d_demo.py 0644 bin bin 293 25439 1451879122
1 f none matplotlib/examples/mplot3d/contour3d_demo2.py 0644 bin bin 295 25698 1451879122
1 f none matplotlib/examples/mplot3d/contour3d_demo3.py 0644 bin bin 579 47972 1451879122
1 f none matplotlib/examples/mplot3d/contourf3d_demo.py 0644 bin bin 281 24448 1451879122
1 f none matplotlib/examples/mplot3d/contourf3d_demo2.py 0644 bin bin 673 55450 1451879122
1 f none matplotlib/examples/mplot3d/custom_shaded_3d_surface.py 0644 bin bin 1071 26650 1451879122
1 f none matplotlib/examples/mplot3d/hist3d_demo.py 0644 bin bin 571 47185 1451879122
1 f none matplotlib/examples/mplot3d/lines3d_demo.py 0644 bin bin 404 33388 1451879122
1 f none matplotlib/examples/mplot3d/lorenz_attractor.py 0644 bin bin 1272 34776 1451879122
1 f none matplotlib/examples/mplot3d/mixed_subplots_demo.py 0644 bin bin 1047 11095 1451879122
1 f none matplotlib/examples/mplot3d/offset_demo.py 0644 bin bin 796 2178 1451879122
1 f none matplotlib/examples/mplot3d/pathpatch3d_demo.py 0644 bin bin 1527 53056 1441943628
1 f none matplotlib/examples/mplot3d/polys3d_demo.py 0644 bin bin 789 63033 1451879122
1 f none matplotlib/examples/mplot3d/quiver3d_demo.py 0644 bin bin 552 40154 1452480193
1 f none matplotlib/examples/mplot3d/rotate_axes3d_demo.py 0644 bin bin 312 26135 1451879122
1 f none matplotlib/examples/mplot3d/scatter3d_demo.py 0644 bin bin 529 41378 1451879122
1 f none matplotlib/examples/mplot3d/subplot3d_demo.py 0644 bin bin 850 3663 1451879122
1 f none matplotlib/examples/mplot3d/surface3d_demo.py 0644 bin bin 660 54905 1451879122
1 f none matplotlib/examples/mplot3d/surface3d_demo2.py 0644 bin bin 422 34381 1451879122
1 f none matplotlib/examples/mplot3d/surface3d_demo3.py 0644 bin bin 739 60355 1451879122
1 f none matplotlib/examples/mplot3d/surface3d_radial_demo.py 0644 bin bin 670 56187 1451879122
1 f none matplotlib/examples/mplot3d/text3d_demo.py 0644 bin bin 626 45925 1451879122
1 f none matplotlib/examples/mplot3d/tricontour3d_demo.py 0644 bin bin 962 18337 1451879122
1 f none matplotlib/examples/mplot3d/tricontourf3d_demo.py 0644 bin bin 963 18439 1451879122
1 f none matplotlib/examples/mplot3d/trisurf3d_demo.py 0644 bin bin 849 6493 1451879122
1 f none matplotlib/examples/mplot3d/trisurf3d_demo2.py 0644 bin bin 1763 17235 1451879122
1 f none matplotlib/examples/mplot3d/wire3d_animation_demo.py 0644 bin bin 845 602 1451879122
1 f none matplotlib/examples/mplot3d/wire3d_demo.py 0644 bin bin 254 21898 1451879122
1 f none matplotlib/examples/mplot3d/wire3d_zero_stride.py 0644 bin bin 411 35185 1451879122
1 d none matplotlib/examples/pie_and_polar_charts 0755 bin bin
1 f none matplotlib/examples/pie_and_polar_charts/pie_demo_features.py 0644 bin bin 2091 42822 1451879122
1 f none matplotlib/examples/pie_and_polar_charts/polar_bar_demo.py 0644 bin bin 465 37729 1451879122
1 f none matplotlib/examples/pie_and_polar_charts/polar_scatter_demo.py 0644 bin bin 490 41299 1451879122
1 d none matplotlib/examples/pylab_examples 0755 bin bin
1 f none matplotlib/examples/pylab_examples/README 0644 bin bin 890 12216 1451879122
1 f none matplotlib/examples/pylab_examples/accented_text.py 0644 bin bin 679 59137 1451879122
1 f none matplotlib/examples/pylab_examples/agg_buffer.py 0755 bin bin 910 11944 1451879122
1 f none matplotlib/examples/pylab_examples/agg_buffer_to_array.py 0644 bin bin 409 35237 1451879122
1 f none matplotlib/examples/pylab_examples/alignment_test.py 0644 bin bin 2209 49824 1451879122
1 f none matplotlib/examples/pylab_examples/anchored_artists.py 0644 bin bin 3992 24125 1451879122
1 f none matplotlib/examples/pylab_examples/animation_demo.py 0644 bin bin 569 44600 1451879122
1 f none matplotlib/examples/pylab_examples/annotation_demo.py 0644 bin bin 5610 51524 1451879122
1 f none matplotlib/examples/pylab_examples/annotation_demo2.py 0644 bin bin 6463 14554 1451879122
1 f none matplotlib/examples/pylab_examples/annotation_demo3.py 0644 bin bin 3284 27157 1451879122
1 f none matplotlib/examples/pylab_examples/anscombe.py 0755 bin bin 1899 6554 1451879122
1 f none matplotlib/examples/pylab_examples/arctest.py 0644 bin bin 300 22639 1451879122
1 f none matplotlib/examples/pylab_examples/arrow_demo.py 0644 bin bin 9182 52673 1452480193
1 f none matplotlib/examples/pylab_examples/arrow_simple_demo.py 0644 bin bin 135 10671 1441943628
1 f none matplotlib/examples/pylab_examples/aspect_loglog.py 0644 bin bin 454 36635 1451879122
1 f none matplotlib/examples/pylab_examples/axes_demo.py 0644 bin bin 858 3732 1452480193
1 f none matplotlib/examples/pylab_examples/axes_props.py 0644 bin bin 584 49336 1451879122
1 f none matplotlib/examples/pylab_examples/axes_zoom_effect.py 0644 bin bin 3303 60876 1451879122
1 f none matplotlib/examples/pylab_examples/axhspan_demo.py 0644 bin bin 762 61606 1451879122
1 f none matplotlib/examples/pylab_examples/axis_equal_demo.py 0644 bin bin 778 64544 1451879122
1 f none matplotlib/examples/pylab_examples/bar_stacked.py 0644 bin bin 726 55732 1451879122
1 f none matplotlib/examples/pylab_examples/barb_demo.py 0644 bin bin 1771 5879 1451879122
1 f none matplotlib/examples/pylab_examples/barchart_demo.py 0644 bin bin 998 7440 1450239869
1 f none matplotlib/examples/pylab_examples/barchart_demo2.py 0644 bin bin 5492 27793 1452481568
1 f none matplotlib/examples/pylab_examples/barcode_demo.py 0644 bin bin 539 43666 1451879122
1 f none matplotlib/examples/pylab_examples/boxplot_demo.py 0644 bin bin 1288 40228 1451879122
1 f none matplotlib/examples/pylab_examples/boxplot_demo2.py 0644 bin bin 4453 43695 1452480193
1 f none matplotlib/examples/pylab_examples/boxplot_demo3.py 0644 bin bin 1206 27495 1451879122
1 f none matplotlib/examples/pylab_examples/break.py 0644 bin bin 135 11354 1451879122
1 f none matplotlib/examples/pylab_examples/broken_axis.py 0644 bin bin 2525 9248 1451879122
1 f none matplotlib/examples/pylab_examples/broken_barh.py 0644 bin bin 717 54857 1451879122
1 f none matplotlib/examples/pylab_examples/centered_ticklabels.py 0644 bin bin 1674 15988 1451879122
1 f none matplotlib/examples/pylab_examples/cohere_demo.py 0644 bin bin 864 2468 1451879122
1 f none matplotlib/examples/pylab_examples/color_by_yvalue.py 0644 bin bin 425 35248 1451879122
1 f none matplotlib/examples/pylab_examples/color_demo.py 0644 bin bin 740 60437 1452480193
1 f none matplotlib/examples/pylab_examples/colorbar_tick_labelling_demo.py 0644 bin bin 1000 20926 1451879122
1 f none matplotlib/examples/pylab_examples/colours.py 0644 bin bin 1333 32277 1451879122
1 f none matplotlib/examples/pylab_examples/contour_corner_mask.py 0644 bin bin 881 7228 1451879122
1 f none matplotlib/examples/pylab_examples/contour_demo.py 0755 bin bin 3496 19672 1451879122
1 f none matplotlib/examples/pylab_examples/contour_image.py 0755 bin bin 3493 28702 1451879122
1 f none matplotlib/examples/pylab_examples/contour_label_demo.py 0644 bin bin 2306 43248 1451879122
1 f none matplotlib/examples/pylab_examples/contourf_demo.py 0755 bin bin 3246 63450 1451879122
1 f none matplotlib/examples/pylab_examples/contourf_hatching.py 0755 bin bin 1359 30228 1451879122
1 f none matplotlib/examples/pylab_examples/coords_demo.py 0755 bin bin 1011 18660 1451879122
1 f none matplotlib/examples/pylab_examples/coords_report.py 0644 bin bin 302 24889 1451879122
1 f none matplotlib/examples/pylab_examples/csd_demo.py 0644 bin bin 873 3049 1451879122
1 f none matplotlib/examples/pylab_examples/cursor_demo.py 0755 bin bin 2235 43996 1452480193
1 f none matplotlib/examples/pylab_examples/custom_cmap.py 0644 bin bin 5759 19806 1451879122
1 f none matplotlib/examples/pylab_examples/custom_figure_class.py 0644 bin bin 644 52889 1451879122
1 f none matplotlib/examples/pylab_examples/custom_ticker1.py 0755 bin bin 838 7363 1451879122
1 f none matplotlib/examples/pylab_examples/customize_rc.py 0644 bin bin 1403 50992 1451879122
1 f none matplotlib/examples/pylab_examples/dashpointlabel.py 0644 bin bin 851 56962 1451879122
1 f none matplotlib/examples/pylab_examples/data_helper.py 0755 bin bin 1500 44787 1451879122
1 f none matplotlib/examples/pylab_examples/date_demo1.py 0644 bin bin 1503 2535 1451879122
1 f none matplotlib/examples/pylab_examples/date_demo2.py 0755 bin bin 1183 39152 1451879122
1 f none matplotlib/examples/pylab_examples/date_demo_convert.py 0644 bin bin 978 20123 1451879122
1 f none matplotlib/examples/pylab_examples/date_demo_rrule.py 0644 bin bin 912 14173 1451879122
1 f none matplotlib/examples/pylab_examples/date_index_formatter.py 0644 bin bin 1268 43312 1451879122
1 f none matplotlib/examples/pylab_examples/demo_agg_filter.py 0644 bin bin 9321 49334 1451879122
1 f none matplotlib/examples/pylab_examples/demo_annotation_box.py 0644 bin bin 2460 35962 1452136290
1 f none matplotlib/examples/pylab_examples/demo_bboximage.py 0644 bin bin 1815 58938 1451879122
1 f none matplotlib/examples/pylab_examples/demo_ribbon_box.py 0644 bin bin 4287 44913 1451879122
1 f none matplotlib/examples/pylab_examples/demo_text_path.py 0644 bin bin 4446 15368 1451879122
1 f none matplotlib/examples/pylab_examples/demo_text_rotation_mode.py 0644 bin bin 1427 37625 1451879122
1 f none matplotlib/examples/pylab_examples/demo_tight_layout.py 0644 bin bin 2528 17467 1452480193
1 f none matplotlib/examples/pylab_examples/dolphin.py 0644 bin bin 3540 37525 1451879122
1 f none matplotlib/examples/pylab_examples/ellipse_collection.py 0644 bin bin 572 46749 1451879122
1 f none matplotlib/examples/pylab_examples/ellipse_demo.py 0644 bin bin 472 38705 1451879122
1 f none matplotlib/examples/pylab_examples/ellipse_rotated.py 0644 bin bin 375 29988 1451879122
1 f none matplotlib/examples/pylab_examples/equal_aspect_ratio.py 0755 bin bin 417 34044 1451879122
1 f none matplotlib/examples/pylab_examples/errorbar_limits.py 0644 bin bin 845 1164 1451879122
1 f none matplotlib/examples/pylab_examples/errorbar_subsample.py 0644 bin bin 636 55064 1441943628
1 f none matplotlib/examples/pylab_examples/eventcollection_demo.py 0644 bin bin 1442 54809 1441943628
1 f none matplotlib/examples/pylab_examples/eventplot_demo.py 0755 bin bin 1889 23702 1441943628
1 f none matplotlib/examples/pylab_examples/fancyarrow_demo.py 0644 bin bin 1397 32418 1452480193
1 f none matplotlib/examples/pylab_examples/fancybox_demo.py 0644 bin bin 4594 59060 1451879122
1 f none matplotlib/examples/pylab_examples/fancybox_demo2.py 0644 bin bin 548 43307 1451879122
1 f none matplotlib/examples/pylab_examples/fancytextbox_demo.py 0644 bin bin 516 30869 1451879122
1 f none matplotlib/examples/pylab_examples/figimage_demo.py 0644 bin bin 407 33320 1451879122
1 f none matplotlib/examples/pylab_examples/figlegend_demo.py 0644 bin bin 483 34638 1451879122
1 f none matplotlib/examples/pylab_examples/figure_title.py 0644 bin bin 596 46988 1451879122
1 f none matplotlib/examples/pylab_examples/fill_between_demo.py 0644 bin bin 2129 51499 1451879122
1 f none matplotlib/examples/pylab_examples/fill_betweenx_demo.py 0644 bin bin 1589 3308 1451879122
1 f none matplotlib/examples/pylab_examples/fill_spiral.py 0644 bin bin 472 35321 1451879122
1 f none matplotlib/examples/pylab_examples/finance_demo.py 0644 bin bin 1105 30710 1451879122
1 f none matplotlib/examples/pylab_examples/finance_work2.py 0644 bin bin 6293 56916 1452480193
1 f none matplotlib/examples/pylab_examples/findobj_demo.py 0644 bin bin 826 2156 1451879122
1 f none matplotlib/examples/pylab_examples/font_table_ttf.py 0755 bin bin 1778 2869 1452480193
1 f none matplotlib/examples/pylab_examples/fonts_demo.py 0644 bin bin 2871 33592 1452480193
1 f none matplotlib/examples/pylab_examples/fonts_demo_kw.py 0644 bin bin 2105 33448 1452480193
1 f none matplotlib/examples/pylab_examples/ganged_plots.py 0644 bin bin 1047 21241 1451879122
1 f none matplotlib/examples/pylab_examples/geo_demo.py 0644 bin bin 348 30269 1451879122
1 f none matplotlib/examples/pylab_examples/ginput_demo.py 0644 bin bin 220 18853 1451879122
1 f none matplotlib/examples/pylab_examples/ginput_manual_clabel.py 0755 bin bin 2516 59040 1451879122
1 f none matplotlib/examples/pylab_examples/gradient_bar.py 0644 bin bin 743 57041 1451879122
1 f none matplotlib/examples/pylab_examples/griddata_demo.py 0644 bin bin 887 6531 1451876921
1 f none matplotlib/examples/pylab_examples/hatch_demo.py 0644 bin bin 1124 19555 1451879122
1 f none matplotlib/examples/pylab_examples/hexbin_demo.py 0644 bin bin 868 8579 1451879122
1 f none matplotlib/examples/pylab_examples/hexbin_demo2.py 0644 bin bin 1285 35339 1451879122
1 f none matplotlib/examples/pylab_examples/hist2d_demo.py 0644 bin bin 189 15926 1451879122
1 f none matplotlib/examples/pylab_examples/hist2d_log_demo.py 0644 bin bin 263 22512 1451879122
1 f none matplotlib/examples/pylab_examples/hist_colormapped.py 0644 bin bin 560 48450 1451879122
1 f none matplotlib/examples/pylab_examples/histogram_percent_demo.py 0644 bin bin 803 3375 1451879122
1 f none matplotlib/examples/pylab_examples/hyperlinks.py 0644 bin bin 874 5579 1451879122
1 f none matplotlib/examples/pylab_examples/image_clip_path.py 0755 bin bin 746 59500 1451879122
1 f none matplotlib/examples/pylab_examples/image_demo.py 0644 bin bin 532 40988 1451879122
1 f none matplotlib/examples/pylab_examples/image_demo2.py 0755 bin bin 509 41644 1451879122
1 f none matplotlib/examples/pylab_examples/image_interp.py 0644 bin bin 1986 44021 1451879122
1 f none matplotlib/examples/pylab_examples/image_masked.py 0644 bin bin 1940 24975 1451879122
1 f none matplotlib/examples/pylab_examples/image_nonuniform.py 0644 bin bin 1509 56737 1451879122
1 f none matplotlib/examples/pylab_examples/image_origin.py 0755 bin bin 718 62452 1452480193
1 f none matplotlib/examples/pylab_examples/image_slices_viewer.py 0644 bin bin 1030 14025 1451879122
1 f none matplotlib/examples/pylab_examples/interp_demo.py 0644 bin bin 299 24957 1451879122
1 f none matplotlib/examples/pylab_examples/invert_axes.py 0644 bin bin 356 29468 1451879122
1 f none matplotlib/examples/pylab_examples/layer_images.py 0644 bin bin 1199 32755 1451879122
1 f none matplotlib/examples/pylab_examples/leftventricle_bulleye.py 0644 bin bin 7352 38429 1451879122
1 f none matplotlib/examples/pylab_examples/legend_demo2.py 0644 bin bin 683 54492 1451879122
1 f none matplotlib/examples/pylab_examples/legend_demo3.py 0644 bin bin 671 55160 1451879122
1 f none matplotlib/examples/pylab_examples/legend_demo4.py 0644 bin bin 695 50959 1451879122
1 f none matplotlib/examples/pylab_examples/legend_demo5.py 0644 bin bin 2723 17328 1451879122
1 f none matplotlib/examples/pylab_examples/line_collection.py 0644 bin bin 1381 52030 1451879122
1 f none matplotlib/examples/pylab_examples/line_collection2.py 0644 bin bin 1396 53069 1451879122
1 f none matplotlib/examples/pylab_examples/load_converter.py 0644 bin bin 592 50105 1451879122
1 f none matplotlib/examples/pylab_examples/loadrec.py 0644 bin bin 558 49798 1451879122
1 f none matplotlib/examples/pylab_examples/log_bar.py 0644 bin bin 428 31400 1451879122
1 f none matplotlib/examples/pylab_examples/log_demo.py 0644 bin bin 758 62098 1451879122
1 f none matplotlib/examples/pylab_examples/log_test.py 0644 bin bin 150 12280 1451879122
1 f none matplotlib/examples/pylab_examples/logo.py 0755 bin bin 1003 18353 1452480193
1 f none matplotlib/examples/pylab_examples/major_minor_demo1.py 0644 bin bin 1698 21262 1451879122
1 f none matplotlib/examples/pylab_examples/major_minor_demo2.py 0644 bin bin 903 13949 1451879122
1 f none matplotlib/examples/pylab_examples/manual_axis.py 0644 bin bin 1967 27847 1451879122
1 f none matplotlib/examples/pylab_examples/marker_path.py 0644 bin bin 454 40491 1441943628
1 f none matplotlib/examples/pylab_examples/markevery_demo.py 0644 bin bin 3206 3879 1451879122
1 f none matplotlib/examples/pylab_examples/masked_demo.py 0644 bin bin 627 50067 1451879122
1 f none matplotlib/examples/pylab_examples/mathtext_demo.py 0755 bin bin 711 60499 1452480193
1 f none matplotlib/examples/pylab_examples/mathtext_examples.py 0755 bin bin 4337 11917 1452480193
1 f none matplotlib/examples/pylab_examples/matplotlib_icon.py 0644 bin bin 463 36642 1452480193
1 f none matplotlib/examples/pylab_examples/matshow.py 0755 bin bin 558 46129 1451879122
1 f none matplotlib/examples/pylab_examples/movie_demo.py 0755 bin bin 690 57937 1451879122
1 f none matplotlib/examples/pylab_examples/mri_demo.py 0755 bin bin 343 30017 1451879122
1 f none matplotlib/examples/pylab_examples/mri_with_eeg.py 0755 bin bin 2066 28800 1451879122
1 f none matplotlib/examples/pylab_examples/multi_image.py 0644 bin bin 2208 46713 1451879122
1 f none matplotlib/examples/pylab_examples/multicolored_line.py 0644 bin bin 1749 16033 1451879122
1 f none matplotlib/examples/pylab_examples/multiline.py 0644 bin bin 1127 22207 1451879122
1 f none matplotlib/examples/pylab_examples/multipage_pdf.py 0644 bin bin 1626 65056 1451879122
1 f none matplotlib/examples/pylab_examples/multiple_figs_demo.py 0644 bin bin 450 37180 1451879122
1 f none matplotlib/examples/pylab_examples/multiple_yaxis_with_spines.py 0644 bin bin 1577 1678 1451879122
1 f none matplotlib/examples/pylab_examples/nan_test.py 0755 bin bin 573 45053 1451879122
1 f none matplotlib/examples/pylab_examples/newscalarformatter_demo.py 0644 bin bin 3492 34325 1451879122
1 f none matplotlib/examples/pylab_examples/patheffect_demo.py 0644 bin bin 1562 51123 1451879122
1 f none matplotlib/examples/pylab_examples/pcolor_demo.py 0644 bin bin 1426 50142 1451879122
1 f none matplotlib/examples/pylab_examples/pcolor_log.py 0644 bin bin 671 54663 1451879122
1 f none matplotlib/examples/pylab_examples/pcolor_small.py 0644 bin bin 257 21452 1451879122
1 f none matplotlib/examples/pylab_examples/pie_demo2.py 0644 bin bin 1564 60576 1451879122
1 f none matplotlib/examples/pylab_examples/plotfile_demo.py 0644 bin bin 1195 31992 1451879122
1 f none matplotlib/examples/pylab_examples/polar_demo.py 0644 bin bin 333 27156 1451879122
1 f none matplotlib/examples/pylab_examples/polar_legend.py 0644 bin bin 601 48553 1452480193
1 f none matplotlib/examples/pylab_examples/print_stdout.py 0644 bin bin 233 20460 1451879122
1 f none matplotlib/examples/pylab_examples/psd_demo.py 0644 bin bin 537 40626 1451879122
1 f none matplotlib/examples/pylab_examples/psd_demo2.py 0644 bin bin 1452 52002 1451879122
1 f none matplotlib/examples/pylab_examples/psd_demo3.py 0644 bin bin 993 15815 1451879122
1 f none matplotlib/examples/pylab_examples/psd_demo_complex.py 0644 bin bin 1180 31620 1451879122
1 f none matplotlib/examples/pylab_examples/pythonic_matplotlib.py 0644 bin bin 2421 18743 1451879122
1 f none matplotlib/examples/pylab_examples/quadmesh_demo.py 0644 bin bin 1120 26880 1452480193
1 f none matplotlib/examples/pylab_examples/quiver_demo.py 0644 bin bin 2872 17829 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_custom_symbol.py 0644 bin bin 377 30453 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_demo2.py 0644 bin bin 1397 55569 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_hist.py 0644 bin bin 1210 39485 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_masked.py 0644 bin bin 545 43745 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_profile.py 0755 bin bin 658 41615 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_star_poly.py 0644 bin bin 633 49099 1451879122
1 f none matplotlib/examples/pylab_examples/scatter_symbol.py 0644 bin bin 356 28019 1441943628
1 f none matplotlib/examples/pylab_examples/set_and_get.py 0644 bin bin 2567 9887 1451879122
1 f none matplotlib/examples/pylab_examples/shading_example.py 0644 bin bin 1719 9331 1451879122
1 f none matplotlib/examples/pylab_examples/shared_axis_across_figures.py 0644 bin bin 674 57615 1451879122
1 f none matplotlib/examples/pylab_examples/shared_axis_demo.py 0644 bin bin 1724 19023 1451879122
1 f none matplotlib/examples/pylab_examples/simple_plot.py 0644 bin bin 267 22200 1451879122
1 f none matplotlib/examples/pylab_examples/simple_plot_fps.py 0755 bin bin 750 60793 1451879122
1 f none matplotlib/examples/pylab_examples/specgram_demo.py 0644 bin bin 880 4611 1451879122
1 f none matplotlib/examples/pylab_examples/spectrum_demo.py 0644 bin bin 505 40533 1452480193
1 f none matplotlib/examples/pylab_examples/spine_placement_demo.py 0644 bin bin 2813 40759 1451879122
1 f none matplotlib/examples/pylab_examples/spy_demos.py 0644 bin bin 393 31863 1451879122
1 f none matplotlib/examples/pylab_examples/stackplot_demo.py 0644 bin bin 318 25254 1451879122
1 f none matplotlib/examples/pylab_examples/stackplot_demo2.py 0644 bin bin 625 43796 1451879122
1 f none matplotlib/examples/pylab_examples/stem_plot.py 0644 bin bin 255 21510 1451879122
1 f none matplotlib/examples/pylab_examples/step_demo.py 0644 bin bin 431 32925 1451879122
1 f none matplotlib/examples/pylab_examples/stix_fonts_demo.py 0755 bin bin 1491 56107 1451879122
1 f none matplotlib/examples/pylab_examples/stock_demo.py 0644 bin bin 431 36835 1451879122
1 f none matplotlib/examples/pylab_examples/subplot_demo.py 0644 bin bin 439 34310 1441943628
1 f none matplotlib/examples/pylab_examples/subplot_toolbar.py 0644 bin bin 318 26277 1451879122
1 f none matplotlib/examples/pylab_examples/subplots_adjust.py 0644 bin bin 334 27675 1451879122
1 f none matplotlib/examples/pylab_examples/subplots_demo.py 0644 bin bin 2192 53421 1451879122
1 f none matplotlib/examples/pylab_examples/symlog_demo.py 0755 bin bin 534 44278 1451879122
1 f none matplotlib/examples/pylab_examples/system_monitor.py 0644 bin bin 1794 14517 1452480193
1 f none matplotlib/examples/pylab_examples/table_demo.py 0644 bin bin 1716 64665 1451879122
1 f none matplotlib/examples/pylab_examples/tex_demo.py 0644 bin bin 996 20546 1451879122
1 f none matplotlib/examples/pylab_examples/tex_unicode_demo.py 0755 bin bin 739 61804 1451879122
1 f none matplotlib/examples/pylab_examples/text_handles.py 0644 bin bin 947 11614 1452480193
1 f none matplotlib/examples/pylab_examples/text_rotation.py 0644 bin bin 1432 54009 1451879122
1 f none matplotlib/examples/pylab_examples/text_rotation_relative_to_line.py 0644 bin bin 1320 45301 1451879122
1 f none matplotlib/examples/pylab_examples/titles_demo.py 0644 bin bin 333 28691 1441943628
1 f none matplotlib/examples/pylab_examples/toggle_images.py 0644 bin bin 1371 52099 1451879122
1 f none matplotlib/examples/pylab_examples/transoffset.py 0644 bin bin 1765 19354 1451879122
1 f none matplotlib/examples/pylab_examples/tricontour_demo.py 0644 bin bin 4613 48088 1451879122
1 f none matplotlib/examples/pylab_examples/tricontour_smooth_delaunay.py 0644 bin bin 5475 43020 1451879122
1 f none matplotlib/examples/pylab_examples/tricontour_smooth_user.py 0644 bin bin 2784 6363 1451879122
1 f none matplotlib/examples/pylab_examples/tricontour_vs_griddata.py 0644 bin bin 1483 56948 1451879122
1 f none matplotlib/examples/pylab_examples/trigradient_demo.py 0644 bin bin 3079 34145 1451879122
1 f none matplotlib/examples/pylab_examples/triinterp_demo.py 0644 bin bin 1703 8972 1441943628
1 f none matplotlib/examples/pylab_examples/tripcolor_demo.py 0644 bin bin 5058 21993 1451879122
1 f none matplotlib/examples/pylab_examples/triplot_demo.py 0644 bin bin 4427 33896 1451879122
1 f none matplotlib/examples/pylab_examples/usetex_baseline_test.py 0644 bin bin 2026 27259 1451879122
1 f none matplotlib/examples/pylab_examples/usetex_demo.py 0644 bin bin 2745 7979 1451879122
1 f none matplotlib/examples/pylab_examples/usetex_fonteffects.py 0644 bin bin 789 61282 1451879122
1 f none matplotlib/examples/pylab_examples/vline_hline_demo.py 0644 bin bin 658 52073 1451879122
1 f none matplotlib/examples/pylab_examples/webapp_demo.py 0644 bin bin 1715 10016 1451879122
1 f none matplotlib/examples/pylab_examples/xcorr_demo.py 0644 bin bin 406 33920 1452480193
1 f none matplotlib/examples/pylab_examples/zorder_demo.py 0755 bin bin 1633 5993 1451879122
1 d none matplotlib/examples/scales 0755 bin bin
1 f none matplotlib/examples/scales/scales.py 0644 bin bin 791 64936 1451879122
1 d none matplotlib/examples/shapes_and_collections 0755 bin bin
1 f none matplotlib/examples/shapes_and_collections/artist_reference.py 0644 bin bin 2824 29828 1451879122
1 f none matplotlib/examples/shapes_and_collections/path_patch_demo.py 0644 bin bin 781 57522 1441943628
1 f none matplotlib/examples/shapes_and_collections/scatter_demo.py 0644 bin bin 298 24124 1451879122
1 d none matplotlib/examples/showcase 0755 bin bin
1 f none matplotlib/examples/showcase/bachelors_degrees_by_gender.py 0644 bin bin 4489 34381 1451879122
1 f none matplotlib/examples/showcase/integral_demo.py 0644 bin bin 1298 40809 1451879122
1 f none matplotlib/examples/showcase/xkcd.py 0644 bin bin 1457 40783 1451879122
1 d none matplotlib/examples/specialty_plots 0755 bin bin
1 f none matplotlib/examples/specialty_plots/advanced_hillshading.py 0644 bin bin 1849 12487 1451879122
1 f none matplotlib/examples/specialty_plots/hinton_demo.py 0644 bin bin 1254 37297 1451879122
1 f none matplotlib/examples/specialty_plots/topographic_hillshading.py 0644 bin bin 3207 5256 1451879122
1 d none matplotlib/examples/statistics 0755 bin bin
1 f none matplotlib/examples/statistics/boxplot_color_demo.py 0644 bin bin 1187 27844 1451879122
1 f none matplotlib/examples/statistics/boxplot_demo.py 0644 bin bin 2677 35259 1451879122
1 f none matplotlib/examples/statistics/boxplot_vs_violin_demo.py 0644 bin bin 1197 35658 1451879122
1 f none matplotlib/examples/statistics/bxp_demo.py 0644 bin bin 2752 41951 1451879122
1 f none matplotlib/examples/statistics/errorbar_demo.py 0644 bin bin 199 16115 1451879122
1 f none matplotlib/examples/statistics/errorbar_demo_features.py 0644 bin bin 1188 37677 1451879122
1 f none matplotlib/examples/statistics/errorbar_limits.py 0644 bin bin 1380 48573 1451879122
1 f none matplotlib/examples/statistics/histogram_demo_cumulative.py 0644 bin bin 677 56259 1451876921
1 f none matplotlib/examples/statistics/histogram_demo_features.py 0644 bin bin 1041 23277 1451879122
1 f none matplotlib/examples/statistics/histogram_demo_histtypes.py 0644 bin bin 686 56860 1451876921
1 f none matplotlib/examples/statistics/histogram_demo_multihist.py 0644 bin bin 1032 22595 1451876921
1 f none matplotlib/examples/statistics/multiple_histograms_side_by_side.py 0644 bin bin 1314 47579 1451879122
1 f none matplotlib/examples/statistics/violinplot_demo.py 0644 bin bin 1729 9433 1451879122
1 d none matplotlib/examples/style_sheets 0755 bin bin
1 f none matplotlib/examples/style_sheets/plot_bmh.py 0644 bin bin 457 37930 1451879122
1 f none matplotlib/examples/style_sheets/plot_dark_background.py 0644 bin bin 569 49403 1451876921
1 f none matplotlib/examples/style_sheets/plot_fivethirtyeight.py 0644 bin bin 434 35966 1451879122
1 f none matplotlib/examples/style_sheets/plot_ggplot.py 0644 bin bin 1385 51522 1451879122
1 f none matplotlib/examples/style_sheets/plot_grayscale.py 0644 bin bin 823 3566 1451879122
1 d none matplotlib/examples/subplots_axes_and_figures 0755 bin bin
1 f none matplotlib/examples/subplots_axes_and_figures/fahrenheit_celsius_scales.py 0644 bin bin 881 8353 1451876921
1 f none matplotlib/examples/subplots_axes_and_figures/subplot_demo.py 0644 bin bin 439 34324 1441943628
1 d none matplotlib/examples/tests 0755 bin bin
1 f none matplotlib/examples/tests/backend_driver.py 0755 bin bin 15243 21980 1452481568
1 d none matplotlib/examples/text_labels_and_annotations 0755 bin bin
1 f none matplotlib/examples/text_labels_and_annotations/autowrap_demo.py 0644 bin bin 685 55547 1451879122
1 f none matplotlib/examples/text_labels_and_annotations/rainbow_text.py 0644 bin bin 1933 25191 1451879122
1 f none matplotlib/examples/text_labels_and_annotations/text_demo_fontdict.py 0644 bin bin 604 48479 1451879122
1 f none matplotlib/examples/text_labels_and_annotations/unicode_demo.py 0644 bin bin 421 38373 1451879122
1 d none matplotlib/examples/ticks_and_spines 0755 bin bin
1 f none matplotlib/examples/ticks_and_spines/spines_demo.py 0644 bin bin 746 65221 1451876921
1 f none matplotlib/examples/ticks_and_spines/spines_demo_bounds.py 0644 bin bin 791 1026 1451879122
1 f none matplotlib/examples/ticks_and_spines/spines_demo_dropped.py 0644 bin bin 672 59474 1441943628
1 f none matplotlib/examples/ticks_and_spines/tick_labels_from_values.py 0644 bin bin 955 19260 1451879122
1 f none matplotlib/examples/ticks_and_spines/ticklabels_demo_rotation.py 0644 bin bin 490 41579 1441943628
1 d none matplotlib/examples/units 0755 bin bin
1 f none matplotlib/examples/units/annotate_with_units.py 0644 bin bin 734 58897 1451879122
1 f none matplotlib/examples/units/artist_tests.py 0644 bin bin 1474 60608 1451879122
1 f none matplotlib/examples/units/bar_demo2.py 0644 bin bin 1076 27732 1451879122
1 f none matplotlib/examples/units/bar_unit_demo.py 0644 bin bin 849 1110 1451879122
1 f none matplotlib/examples/units/basic_units.py 0644 bin bin 11136 4384 1451879122
1 f none matplotlib/examples/units/ellipse_with_units.py 0644 bin bin 1834 17927 1451879122
1 f none matplotlib/examples/units/evans_test.py 0644 bin bin 2339 53158 1451879122
1 f none matplotlib/examples/units/radian_demo.py 0644 bin bin 530 46189 1441943628
1 f none matplotlib/examples/units/units_sample.py 0644 bin bin 948 16441 1451879122
1 f none matplotlib/examples/units/units_scatter.py 0644 bin bin 904 10050 1451879122
1 d none matplotlib/examples/user_interfaces 0755 bin bin
1 f none matplotlib/examples/user_interfaces/README.txt 0644 bin bin 525 47066 1433715168
1 f none matplotlib/examples/user_interfaces/README.wx 0644 bin bin 821 8065 1433715168
1 f none matplotlib/examples/user_interfaces/embedding_in_gtk.py 0644 bin bin 836 6739 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_gtk2.py 0644 bin bin 1459 64327 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_gtk3.py 0755 bin bin 835 6461 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_gtk3_panzoom.py 0644 bin bin 885 10510 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_qt4.py 0755 bin bin 4213 6773 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_qt4_wtoolbar.py 0644 bin bin 2225 51668 1451876921
1 f none matplotlib/examples/user_interfaces/embedding_in_qt5.py 0755 bin bin 4328 16407 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_tk.py 0755 bin bin 1423 56532 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_tk2.py 0644 bin bin 887 9365 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_tk_canvas.py 0755 bin bin 2044 43291 1452481568
1 f none matplotlib/examples/user_interfaces/embedding_in_wx2.py 0644 bin bin 2190 48437 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_wx3.py 0755 bin bin 4993 317 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_wx4.py 0644 bin bin 3375 197 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_in_wx5.py 0644 bin bin 1973 27120 1451879122
1 f none matplotlib/examples/user_interfaces/embedding_webagg.py 0644 bin bin 8190 44512 1451879122
1 f none matplotlib/examples/user_interfaces/fourier_demo_wx.py 0644 bin bin 8955 20813 1451879122
1 f none matplotlib/examples/user_interfaces/gtk_spreadsheet.py 0644 bin bin 2466 61589 1451879122
1 f none matplotlib/examples/user_interfaces/histogram_demo_canvasagg.py 0644 bin bin 1392 50451 1451879122
1 f none matplotlib/examples/user_interfaces/interactive.py 0755 bin bin 8198 52624 1451879122
1 f none matplotlib/examples/user_interfaces/interactive2.py 0755 bin bin 11490 43987 1451879122
1 f none matplotlib/examples/user_interfaces/lineprops_dialog_gtk.py 0644 bin bin 514 39879 1451879122
1 f none matplotlib/examples/user_interfaces/mathtext_wx.py 0644 bin bin 3884 35000 1451879122
1 f none matplotlib/examples/user_interfaces/mpl_with_glade.glade 0644 bin bin 10021 21865 1433715168
1 f none matplotlib/examples/user_interfaces/mpl_with_glade.py 0755 bin bin 3147 54706 1451879122
1 f none matplotlib/examples/user_interfaces/mpl_with_glade_316.glade 0644 bin bin 858 4905 1451879122
1 f none matplotlib/examples/user_interfaces/mpl_with_glade_316.py 0644 bin bin 1102 25553 1451879122
1 f none matplotlib/examples/user_interfaces/pylab_with_gtk.py 0644 bin bin 1431 57168 1451879122
1 f none matplotlib/examples/user_interfaces/rec_edit_gtk_custom.py 0644 bin bin 1310 51639 1451879122
1 f none matplotlib/examples/user_interfaces/rec_edit_gtk_simple.py 0644 bin bin 489 44090 1451879122
1 f none matplotlib/examples/user_interfaces/svg_histogram.py 0755 bin bin 4555 57579 1452481568
1 f none matplotlib/examples/user_interfaces/svg_tooltip.py 0644 bin bin 3328 7532 1452481568
1 f none matplotlib/examples/user_interfaces/toolmanager.py 0644 bin bin 2879 28669 1452480193
1 f none matplotlib/examples/user_interfaces/wxcursor_demo.py 0644 bin bin 2349 52703 1451879122
1 d none matplotlib/examples/widgets 0755 bin bin
1 f none matplotlib/examples/widgets/README.txt 0644 bin bin 77 7148 1433715168
1 f none matplotlib/examples/widgets/buttons.py 0644 bin bin 895 3104 1451879122
1 f none matplotlib/examples/widgets/check_buttons.py 0644 bin bin 740 56943 1451879122
1 f none matplotlib/examples/widgets/cursor.py 0644 bin bin 417 34756 1452480193
1 f none matplotlib/examples/widgets/lasso_selector_demo.py 0644 bin bin 2781 30753 1451879122
1 f none matplotlib/examples/widgets/menu.py 0644 bin bin 4958 58021 1451879122
1 f none matplotlib/examples/widgets/multicursor.py 0644 bin bin 363 29705 1451877792
1 f none matplotlib/examples/widgets/radio_buttons.py 0644 bin bin 1017 14509 1451879122
1 f none matplotlib/examples/widgets/rectangle_selector.py 0644 bin bin 2198 40334 1451879122
1 f none matplotlib/examples/widgets/slider_demo.py 0644 bin bin 1184 28960 1452480193
1 f none matplotlib/examples/widgets/span_selector.py 0644 bin bin 1094 24659 1452480193
1 i pkginfo 809 6743 1460294908
0707010001f955000041ed00001782000005de00000003570a54fd00000000000002600000050a00000000000000000000000600000000reloc 0707010001f956000041ed00001782000005de00000003570a54fd00000000000002600000050a00000000000000000000001100000000reloc/matplotlib 0707010001f958000081a400001782000005de000000015574c1e000000058000002600000050a00000000000000000000002100000000reloc/matplotlib/CONTRIBUTING.md Please refer to the [Coding
Guidelines](http://matplotlib.org/devel/coding_guide.html).
0707010001f959000081a400001782000005de0000000156931c7b0000042c000002600000050a00000000000000000000001a00000000reloc/matplotlib/PKG-INFO Metadata-Version: 1.1
Name: matplotlib
Version: 1.5.1
Summary: Python plotting package
Home-page: http://matplotlib.org
Author: John D. Hunter, Michael Droettboom
Author-email: matplotlib-users@python.org
License: BSD
Download-URL: http://matplotlib.org/users/installing.html
Description:
matplotlib strives to produce publication quality 2D graphics
for interactive graphing, scientific publishing, user interface
development and web application servers targeting multiple user
interfaces and hardcopy output formats. There is a 'pylab' mode
which emulates matlab graphics.
Platform: any
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Python Software Foundation License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Visualization
0707010001f95b000041ed00001782000005de0000001a570a550000000000000002600000050a00000000000000000000001a00000000reloc/matplotlib/examples 0707010001fb0e000041ed00001782000005de00000002570a550000000000000002600000050a00000000000000000000002000000000reloc/matplotlib/examples/tests 0707010001fb0f000081ed00001782000005de0000000156931c2000003b8b000002600000050a00000000000000000000003200000000reloc/matplotlib/examples/tests/backend_driver.py #!/usr/bin/env python
from __future__ import print_function, division
"""
This is used to drive many of the examples across the backends, for
regression testing, and comparing backend efficiency.
You can specify the backends to be tested either via the --backends
switch, which takes a comma-separated list, or as separate arguments,
e.g.
python backend_driver.py agg ps
would test the agg and ps backends. If no arguments are given, a
default list of backends will be tested.
Interspersed with the backend arguments can be switches for the Python
interpreter executing the tests. If entering such arguments causes an
option parsing error with the driver script, separate them from driver
switches with a --.
"""
import os
import time
import sys
import glob
from optparse import OptionParser
import matplotlib.rcsetup as rcsetup
from matplotlib.cbook import Bunch, dedent
all_backends = list(rcsetup.all_backends) # to leave the original list alone
# actual physical directory for each dir
dirs = dict(files=os.path.join('..', 'lines_bars_and_markers'),
shapes=os.path.join('..', 'shapes_and_collections'),
images=os.path.join('..', 'images_contours_and_fields'),
pie=os.path.join('..', 'pie_and_polar_charts'),
text=os.path.join('..', 'text_labels_and_annotations'),
ticks=os.path.join('..', 'ticks_and_spines'),
subplots=os.path.join('..', 'subplots_axes_and_figures'),
specialty=os.path.join('..', 'specialty_plots'),
showcase=os.path.join('..', 'showcase'),
pylab=os.path.join('..', 'pylab_examples'),
api=os.path.join('..', 'api'),
units=os.path.join('..', 'units'),
mplot3d=os.path.join('..', 'mplot3d'))
# files in each dir
files = dict()
files['lines'] = [
'barh_demo.py',
'fill_demo.py',
'fill_demo_features.py',
'line_demo_dash_control.py',
'line_styles_reference.py',
'scatter_with_legend.py'
]
files['shapes'] = [
'path_patch_demo.py',
'scatter_demo.py',
]
files['colors'] = [
'color_cycle_demo.py',
]
files['images'] = [
'image_demo.py',
'contourf_log.py',
]
files['statistics'] = [
'errorbar_demo.py',
'errorbar_demo_features.py',
'histogram_demo_cumulative.py',
'histogram_demo_features.py',
'histogram_demo_histtypes.py',
'histogram_demo_multihist.py',
]
files['pie'] = [
'pie_demo.py',
'polar_bar_demo.py',
'polar_scatter_demo.py',
]
files['text_labels_and_annotations'] = [
'text_demo_fontdict.py',
'unicode_demo.py',
]
files['ticks_and_spines'] = [
'spines_demo_bounds.py',
'ticklabels_demo_rotation.py',
]
files['subplots_axes_and_figures'] = [
'subplot_demo.py',
]
files['showcase'] = [
'integral_demo.py',
]
files['pylab'] = [
'accented_text.py',
'alignment_test.py',
'annotation_demo.py',
'annotation_demo.py',
'annotation_demo2.py',
'annotation_demo2.py',
'anscombe.py',
'arctest.py',
'arrow_demo.py',
'axes_demo.py',
'axes_props.py',
'axhspan_demo.py',
'axis_equal_demo.py',
'bar_stacked.py',
'barb_demo.py',
'barchart_demo.py',
'barcode_demo.py',
'boxplot_demo.py',
'broken_barh.py',
'cohere_demo.py',
'color_by_yvalue.py',
'color_demo.py',
'colorbar_tick_labelling_demo.py',
'contour_demo.py',
'contour_image.py',
'contour_label_demo.py',
'contourf_demo.py',
'coords_demo.py',
'coords_report.py',
'csd_demo.py',
'cursor_demo.py',
'custom_cmap.py',
'custom_figure_class.py',
'custom_ticker1.py',
'customize_rc.py',
'dashpointlabel.py',
'date_demo1.py',
'date_demo2.py',
'date_demo_convert.py',
'date_demo_rrule.py',
'date_index_formatter.py',
'dolphin.py',
'ellipse_collection.py',
'ellipse_demo.py',
'ellipse_rotated.py',
'equal_aspect_ratio.py',
'errorbar_limits.py',
'fancyarrow_demo.py',
'fancybox_demo.py',
'fancybox_demo2.py',
'fancytextbox_demo.py',
'figimage_demo.py',
'figlegend_demo.py',
'figure_title.py',
'fill_between_demo.py',
'fill_spiral.py',
'finance_demo.py',
'findobj_demo.py',
'fonts_demo.py',
'fonts_demo_kw.py',
'ganged_plots.py',
'geo_demo.py',
'gradient_bar.py',
'griddata_demo.py',
'hatch_demo.py',
'hexbin_demo.py',
'hexbin_demo2.py',
'hist_colormapped.py',
'vline_hline_demo.py',
'image_clip_path.py',
'image_demo.py',
'image_demo2.py',
'image_interp.py',
'image_masked.py',
'image_nonuniform.py',
'image_origin.py',
'image_slices_viewer.py',
'interp_demo.py',
'invert_axes.py',
'layer_images.py',
'legend_demo2.py',
'legend_demo3.py',
'line_collection.py',
'line_collection2.py',
'log_bar.py',
'log_demo.py',
'log_test.py',
'major_minor_demo1.py',
'major_minor_demo2.py',
'manual_axis.py',
'masked_demo.py',
'mathtext_demo.py',
'mathtext_examples.py',
'matplotlib_icon.py',
'matshow.py',
'mri_demo.py',
'mri_with_eeg.py',
'multi_image.py',
'multiline.py',
'multiple_figs_demo.py',
'nan_test.py',
'newscalarformatter_demo.py',
'pcolor_demo.py',
'pcolor_log.py',
'pcolor_small.py',
'pie_demo2.py',
'plotfile_demo.py',
'polar_demo.py',
'polar_legend.py',
'psd_demo.py',
'psd_demo2.py',
'psd_demo3.py',
'quadmesh_demo.py',
'quiver_demo.py',
'scatter_custom_symbol.py',
'scatter_demo2.py',
'scatter_masked.py',
'scatter_profile.py',
'scatter_star_poly.py',
#'set_and_get.py',
'shared_axis_across_figures.py',
'shared_axis_demo.py',
'simple_plot.py',
'specgram_demo.py',
'spine_placement_demo.py',
'spy_demos.py',
'stem_plot.py',
'step_demo.py',
'stix_fonts_demo.py',
'stock_demo.py',
'subplots_adjust.py',
'symlog_demo.py',
'table_demo.py',
'text_handles.py',
'text_rotation.py',
'text_rotation_relative_to_line.py',
'transoffset.py',
'xcorr_demo.py',
'zorder_demo.py',
]
files['api'] = [
'agg_oo.py',
'barchart_demo.py',
'bbox_intersect.py',
'collections_demo.py',
'colorbar_only.py',
'custom_projection_example.py',
'custom_scale_example.py',
'date_demo.py',
'date_index_formatter.py',
'donut_demo.py',
'font_family_rc.py',
'image_zcoord.py',
'joinstyle.py',
'legend_demo.py',
'line_with_text.py',
'logo2.py',
'mathtext_asarray.py',
'patch_collection.py',
'quad_bezier.py',
'scatter_piecharts.py',
'span_regions.py',
'two_scales.py',
'unicode_minus.py',
'watermark_image.py',
'watermark_text.py',
]
files['units'] = [
'annotate_with_units.py',
#'artist_tests.py', # broken, fixme
'bar_demo2.py',
#'bar_unit_demo.py', # broken, fixme
#'ellipse_with_units.py', # broken, fixme
'radian_demo.py',
'units_sample.py',
#'units_scatter.py', # broken, fixme
]
files['mplot3d'] = [
'2dcollections3d_demo.py',
'bars3d_demo.py',
'contour3d_demo.py',
'contour3d_demo2.py',
'contourf3d_demo.py',
'lines3d_demo.py',
'polys3d_demo.py',
'scatter3d_demo.py',
'surface3d_demo.py',
'surface3d_demo2.py',
'text3d_demo.py',
'wire3d_demo.py',
]
# dict from dir to files we know we don't want to test (e.g., examples
# not using pyplot, examples requiring user input, animation examples,
# examples that may only work in certain environs (usetex examples?),
# examples that generate multiple figures
excluded = {
'pylab': ['__init__.py', 'toggle_images.py', ],
'units': ['__init__.py', 'date_support.py', ],
}
def report_missing(dir, flist):
'report the py files in dir that are not in flist'
globstr = os.path.join(dir, '*.py')
fnames = glob.glob(globstr)
pyfiles = set([os.path.split(fullpath)[-1] for fullpath in set(fnames)])
exclude = set(excluded.get(dir, []))
flist = set(flist)
missing = list(pyfiles - flist - exclude)
missing.sort()
if missing:
print('%s files not tested: %s' % (dir, ', '.join(missing)))
def report_all_missing(directories):
for f in directories:
report_missing(dirs[f], files[f])
# tests known to fail on a given backend
failbackend = dict(
svg=('tex_demo.py', ),
agg=('hyperlinks.py', ),
pdf=('hyperlinks.py', ),
ps=('hyperlinks.py', ),
)
try:
import subprocess
def run(arglist):
try:
ret = subprocess.call(arglist)
except KeyboardInterrupt:
sys.exit()
else:
return ret
except ImportError:
def run(arglist):
os.system(' '.join(arglist))
def drive(backend, directories, python=['python'], switches=[]):
exclude = failbackend.get(backend, [])
# Clear the destination directory for the examples
path = backend
if os.path.exists(path):
import glob
for fname in os.listdir(path):
os.unlink(os.path.join(path, fname))
else:
os.mkdir(backend)
failures = []
testcases = [os.path.join(dirs[d], fname)
for d in directories
for fname in files[d]]
for fullpath in testcases:
print('\tdriving %-40s' % (fullpath))
sys.stdout.flush()
fpath, fname = os.path.split(fullpath)
if fname in exclude:
print('\tSkipping %s, known to fail on backend: %s' % backend)
continue
basename, ext = os.path.splitext(fname)
outfile = os.path.join(path, basename)
tmpfile_name = '_tmp_%s.py' % basename
tmpfile = open(tmpfile_name, 'w')
future_imports = 'from __future__ import division, print_function'
for line in open(fullpath):
line_lstrip = line.lstrip()
if line_lstrip.startswith("#"):
tmpfile.write(line)
elif 'unicode_literals' in line:
future_imports = future_imports + ', unicode_literals'
tmpfile.writelines((
future_imports + '\n',
'import sys\n',
'sys.path.append("%s")\n' % fpath.replace('\\', '\\\\'),
'import matplotlib\n',
'matplotlib.use("%s")\n' % backend,
'from pylab import savefig\n',
'import numpy\n',
'numpy.seterr(invalid="ignore")\n',
))
for line in open(fullpath):
line_lstrip = line.lstrip()
if (line_lstrip.startswith('from __future__ import') or
line_lstrip.startswith('matplotlib.use') or
line_lstrip.startswith('savefig') or
line_lstrip.startswith('show')):
continue
tmpfile.write(line)
if backend in rcsetup.interactive_bk:
tmpfile.write('show()')
else:
tmpfile.write('\nsavefig(r"%s", dpi=150)' % outfile)
tmpfile.close()
start_time = time.time()
program = [x % {'name': basename} for x in python]
ret = run(program + [tmpfile_name] + switches)
end_time = time.time()
print("%s %s" % ((end_time - start_time), ret))
#os.system('%s %s %s' % (python, tmpfile_name, ' '.join(switches)))
os.remove(tmpfile_name)
if ret:
failures.append(fullpath)
return failures
def parse_options():
doc = (__doc__ and __doc__.split('\n\n')) or " "
op = OptionParser(description=doc[0].strip(),
usage='%prog [options] [--] [backends and switches]',
#epilog='\n'.join(doc[1:]) # epilog not supported on my python2.4 machine: JDH
)
op.disable_interspersed_args()
op.set_defaults(dirs='pylab,api,units,mplot3d',
clean=False, coverage=False, valgrind=False)
op.add_option('-d', '--dirs', '--directories', type='string',
dest='dirs', help=dedent('''
Run only the tests in these directories; comma-separated list of
one or more of: pylab (or pylab_examples), api, units, mplot3d'''))
op.add_option('-b', '--backends', type='string', dest='backends',
help=dedent('''
Run tests only for these backends; comma-separated list of
one or more of: agg, ps, svg, pdf, template, cairo,
Default is everything except cairo.'''))
op.add_option('--clean', action='store_true', dest='clean',
help='Remove result directories, run no tests')
op.add_option('-c', '--coverage', action='store_true', dest='coverage',
help='Run in coverage.py')
op.add_option('-v', '--valgrind', action='store_true', dest='valgrind',
help='Run in valgrind')
options, args = op.parse_args()
switches = [x for x in args if x.startswith('--')]
backends = [x.lower() for x in args if not x.startswith('--')]
if options.backends:
backends += [be.lower() for be in options.backends.split(',')]
result = Bunch(
dirs=options.dirs.split(','),
backends=backends or ['agg', 'ps', 'svg', 'pdf', 'template'],
clean=options.clean,
coverage=options.coverage,
valgrind=options.valgrind,
switches=switches)
if 'pylab_examples' in result.dirs:
result.dirs[result.dirs.index('pylab_examples')] = 'pylab'
#print(result)
return (result)
if __name__ == '__main__':
times = {}
failures = {}
options = parse_options()
if options.clean:
localdirs = [d for d in glob.glob('*') if os.path.isdir(d)]
all_backends_set = set(all_backends)
for d in localdirs:
if d.lower() not in all_backends_set:
continue
print('removing %s' % d)
for fname in glob.glob(os.path.join(d, '*')):
os.remove(fname)
os.rmdir(d)
for fname in glob.glob('_tmp*.py'):
os.remove(fname)
print('all clean...')
raise SystemExit
if options.coverage:
python = ['coverage.py', '-x']
elif options.valgrind:
python = ['valgrind', '--tool=memcheck', '--leak-check=yes',
'--log-file=%(name)s', sys.executable]
elif sys.platform == 'win32':
python = [sys.executable]
else:
python = [sys.executable]
report_all_missing(options.dirs)
for backend in options.backends:
print('testing %s %s' % (backend, ' '.join(options.switches)))
t0 = time.time()
failures[backend] = \
drive(backend, options.dirs, python, options.switches)
t1 = time.time()
times[backend] = (t1 - t0)/60.0
#print(times)
for backend, elapsed in times.items():
print('Backend %s took %1.2f minutes to complete' % (backend, elapsed))
failed = failures[backend]
if failed:
print(' Failures: %s' % failed)
if 'template' in times:
print('\ttemplate ratio %1.3f, template residual %1.3f' % (
elapsed/times['template'], elapsed - times['template']))
0707010001f9ae000041ed00001782000005de00000002570a54fe00000000000002600000050a00000000000000000000002000000000reloc/matplotlib/examples/color 0707010001f9b0000081a400001782000005de000000015689ead200000e5c000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/color/colormaps_reference.py """
Reference for colormaps included with Matplotlib.
This reference example shows all colormaps included with Matplotlib. Note that
any colormap listed here can be reversed by appending "_r" (e.g., "pink_r").
These colormaps are divided into the following categories:
Sequential:
These colormaps are approximately monochromatic colormaps varying smoothly
between two color tones---usually from low saturation (e.g. white) to high
saturation (e.g. a bright blue). Sequential colormaps are ideal for
representing most scientific data since they show a clear progression from
low-to-high values.
Diverging:
These colormaps have a median value (usually light in color) and vary
smoothly to two different color tones at high and low values. Diverging
colormaps are ideal when your data has a median value that is significant
(e.g. 0, such that positive and negative values are represented by
different colors of the colormap).
Qualitative:
These colormaps vary rapidly in color. Qualitative colormaps are useful for
choosing a set of discrete colors. For example::
color_list = plt.cm.Set3(np.linspace(0, 1, 12))
gives a list of RGB colors that are good for plotting a series of lines on
a dark background.
Miscellaneous:
Colormaps that don't fit into the categories above.
"""
import numpy as np
import matplotlib.pyplot as plt
# Have colormaps separated into categories:
# http://matplotlib.org/examples/color/colormaps_reference.html
cmaps = [('Perceptually Uniform Sequential',
['viridis', 'inferno', 'plasma', 'magma']),
('Sequential', ['Blues', 'BuGn', 'BuPu',
'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd',
'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',
'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']),
('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool',
'copper', 'gist_heat', 'gray', 'hot',
'pink', 'spring', 'summer', 'winter']),
('Diverging', ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr',
'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
'seismic']),
('Qualitative', ['Accent', 'Dark2', 'Paired', 'Pastel1',
'Pastel2', 'Set1', 'Set2', 'Set3']),
('Miscellaneous', ['gist_earth', 'terrain', 'ocean', 'gist_stern',
'brg', 'CMRmap', 'cubehelix',
'gnuplot', 'gnuplot2', 'gist_ncar',
'nipy_spectral', 'jet', 'rainbow',
'gist_rainbow', 'hsv', 'flag', 'prism'])]
nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps)
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
fig, axes = plt.subplots(nrows=nrows)
fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
axes[0].set_title(cmap_category + ' colormaps', fontsize=14)
for ax, name in zip(axes, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
pos = list(ax.get_position().bounds)
x_text = pos[0] - 0.01
y_text = pos[1] + pos[3]/2.
fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axes:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)
plt.show()
0707010001f9af000081a400001782000005de000000015689ead2000004b6000002600000050a00000000000000000000003400000000reloc/matplotlib/examples/color/color_cycle_demo.py """
Demo of custom property-cycle settings to control colors and such
for multi-line plots.
This example demonstrates two different APIs:
1. Setting the default rc-parameter specifying the property cycle.
This affects all subsequent axes (but not axes already created).
2. Setting the property cycle for a specific axes. This only
affects a single axes.
"""
from cycler import cycler
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi)
offsets = np.linspace(0, 2*np.pi, 4, endpoint=False)
# Create array with shifted-sine curve along each column
yy = np.transpose([np.sin(x + phi) for phi in offsets])
plt.rc('lines', linewidth=4)
plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y']) +
cycler('linestyle', ['-', '--', ':', '-.'])))
fig, (ax0, ax1) = plt.subplots(nrows=2)
ax0.plot(yy)
ax0.set_title('Set default color cycle to rgby')
ax1.set_prop_cycle(cycler('color', ['c', 'm', 'y', 'k']) +
cycler('lw', [1, 2, 3, 4]))
ax1.plot(yy)
ax1.set_title('Set axes color cycle to cmyk')
# Tweak spacing between subplots to prevent labels from overlapping
plt.subplots_adjust(hspace=0.3)
plt.show()
0707010001f9b1000081a400001782000005de00000001569316c1000007af000002600000050a00000000000000000000003000000000reloc/matplotlib/examples/color/named_colors.py """
Visualization of named colors.
Simple plot example with the named colors and its visual representation.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
colors_ = list(six.iteritems(colors.cnames))
# Add the single letter colors.
for name, rgb in six.iteritems(colors.ColorConverter.colors):
hex_ = colors.rgb2hex(rgb)
colors_.append((name, hex_))
# Transform to hex color values.
hex_ = [color[1] for color in colors_]
# Get the rgb equivalent.
rgb = [colors.hex2color(color) for color in hex_]
# Get the hsv equivalent.
hsv = [colors.rgb_to_hsv(color) for color in rgb]
# Split the hsv values to sort.
hue = [color[0] for color in hsv]
sat = [color[1] for color in hsv]
val = [color[2] for color in hsv]
# Sort by hue, saturation and value.
ind = np.lexsort((val, sat, hue))
sorted_colors = [colors_[i] for i in ind]
n = len(sorted_colors)
ncols = 4
nrows = int(np.ceil(1. * n / ncols))
fig, ax = plt.subplots()
X, Y = fig.get_dpi() * fig.get_size_inches()
# row height
h = Y / (nrows + 1)
# col width
w = X / ncols
for i, (name, color) in enumerate(sorted_colors):
col = i % ncols
row = int(i / ncols)
y = Y - (row * h) - h
xi_line = w * (col + 0.05)
xf_line = w * (col + 0.25)
xi_text = w * (col + 0.3)
ax.text(xi_text, y, name, fontsize=(h * 0.8),
horizontalalignment='left',
verticalalignment='center')
# Add extra black line a little bit thicker to make
# clear colors more visible.
ax.hlines(y, xi_line, xf_line, color='black', linewidth=(h * 0.7))
ax.hlines(y + h * 0.1, xi_line, xf_line, color=color, linewidth=(h * 0.6))
ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()
fig.subplots_adjust(left=0, right=1,
top=1, bottom=0,
hspace=0, wspace=0)
plt.show()
0707010001fb0b000041ed00001782000005de00000002570a550000000000000002600000050a00000000000000000000003400000000reloc/matplotlib/examples/subplots_axes_and_figures 0707010001fb0c000081a400001782000005de000000015689e23900000371000002600000050a00000000000000000000005100000000reloc/matplotlib/examples/subplots_axes_and_figures/fahrenheit_celsius_scales.py """
Demo of how to display two scales on the left and right y axis.
This example uses the Fahrenheit and Celsius scales.
"""
import matplotlib.pyplot as plt
import numpy as np
def fahrenheit2celsius(temp):
"""
Returns temperature in Celsius.
"""
return (5. / 9.) * (temp - 32)
def convert_ax_c_to_celsius(ax_f):
"""
Update second axis according with first axis.
"""
y1, y2 = ax_f.get_ylim()
ax_c.set_ylim(fahrenheit2celsius(y1), fahrenheit2celsius(y2))
ax_c.figure.canvas.draw()
fig, ax_f = plt.subplots()
ax_c = ax_f.twinx()
# automatically update ylim of ax2 when ylim of ax1 changes.
ax_f.callbacks.connect("ylim_changed", convert_ax_c_to_celsius)
ax_f.plot(np.linspace(-40, 120, 100))
ax_f.set_xlim(0, 100)
ax_f.set_title('Two scales: Fahrenheit and Celsius')
ax_f.set_ylabel('Fahrenheit')
ax_c.set_ylabel('Celsius')
plt.show()
0707010001fb0d000081a400001782000005de0000000155f2504c000001b7000002600000050a00000000000000000000004400000000reloc/matplotlib/examples/subplots_axes_and_figures/subplot_demo.py """
Simple demo with multiple subplots.
"""
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'yo-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')
plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
0707010001f9db000041ed00001782000005de00000002570a54fe00000000000002600000050a00000000000000000000001f00000000reloc/matplotlib/examples/misc 0707010001f9e1000081a400001782000005de00000001569316c10000086d000002600000050a00000000000000000000002f00000000reloc/matplotlib/examples/misc/multiprocess.py # Demo of using multiprocessing for generating data in one process and plotting
# in another.
# Written by Robert Cimrman
# Requires >= Python 2.6 for the multiprocessing module or having the
# standalone processing module installed
from __future__ import print_function
import time
try:
from multiprocessing import Process, Pipe
except ImportError:
from processing import Process, Pipe
import numpy as np
import matplotlib
matplotlib.use('GtkAgg')
import matplotlib.pyplot as plt
import gobject
class ProcessPlotter(object):
def __init__(self):
self.x = []
self.y = []
def terminate(self):
plt.close('all')
def poll_draw(self):
def call_back():
while 1:
if not self.pipe.poll():
break
command = self.pipe.recv()
if command is None:
self.terminate()
return False
else:
self.x.append(command[0])
self.y.append(command[1])
self.ax.plot(self.x, self.y, 'ro')
self.fig.canvas.draw()
return True
return call_back
def __call__(self, pipe):
print('starting plotter...')
self.pipe = pipe
self.fig, self.ax = plt.subplots()
self.gid = gobject.timeout_add(1000, self.poll_draw())
print('...done')
plt.show()
class NBPlot(object):
def __init__(self):
self.plot_pipe, plotter_pipe = Pipe()
self.plotter = ProcessPlotter()
self.plot_process = Process(target=self.plotter,
args=(plotter_pipe,))
self.plot_process.daemon = True
self.plot_process.start()
def plot(self, finished=False):
send = self.plot_pipe.send
if finished:
send(None)
else:
data = np.random.random(2)
send(data)
def main():
pl = NBPlot()
for ii in range(10):
pl.plot()
time.sleep(0.5)
raw_input('press Enter...')
pl.plot(finished=True)
if __name__ == '__main__':
main()
0707010001f9de000081ed00001782000005de00000001569316c100000975000002600000050a00000000000000000000002f00000000reloc/matplotlib/examples/misc/ftface_props.py #!/usr/bin/env python
from __future__ import print_function
"""
This is a demo script to show you how to use all the properties of an
FT2Font object. These describe global font properties. For
individual character metrices, use the Glyp object, as returned by
load_char
"""
import matplotlib
import matplotlib.ft2font as ft
#fname = '/usr/local/share/matplotlib/VeraIt.ttf'
fname = matplotlib.get_data_path() + '/fonts/ttf/VeraIt.ttf'
#fname = '/usr/local/share/matplotlib/cmr10.ttf'
font = ft.FT2Font(fname)
print('Num faces :', font.num_faces) # number of faces in file
print('Num glyphs :', font.num_glyphs) # number of glyphs in the face
print('Family name :', font.family_name) # face family name
print('Syle name :', font.style_name) # face syle name
print('PS name :', font.postscript_name) # the postscript name
print('Num fixed :', font.num_fixed_sizes) # number of embedded bitmap in face
# the following are only available if face.scalable
if font.scalable:
# the face global bounding box (xmin, ymin, xmax, ymax)
print('Bbox :', font.bbox)
# number of font units covered by the EM
print('EM :', font.units_per_EM)
# the ascender in 26.6 units
print('Ascender :', font.ascender)
# the descender in 26.6 units
print('Descender :', font.descender)
# the height in 26.6 units
print('Height :', font.height)
# maximum horizontal cursor advance
print('Max adv width :', font.max_advance_width)
# same for vertical layout
print('Max adv height :', font.max_advance_height)
# vertical position of the underline bar
print('Underline pos :', font.underline_position)
# vertical thickness of the underline
print('Underline thickness :', font.underline_thickness)
for style in ('Italic',
'Bold',
'Scalable',
'Fixed sizes',
'Fixed width',
'SFNT',
'Horizontal',
'Vertical',
'Kerning',
'Fast glyphs',
'Multiple masters',
'Glyph names',
'External stream'):
bitpos = getattr(ft, style.replace(' ', '_').upper()) - 1
print('%-17s:' % style, bool(font.style_flags & (1 << bitpos)))
print(dir(font))
cmap = font.get_charmap()
print(font.get_kerning)
0707010001f9e3000081a400001782000005de000000015689ead200001590000002600000050a00000000000000000000002c00000000reloc/matplotlib/examples/misc/rc_traits.py # Here is some example code showing how to define some representative
# rc properties and construct a matplotlib artist using traits.
# matplotlib does not ship with enthought.traits, so you will need to
# install it separately.
from __future__ import print_function
import sys
import os
import re
import traits.api as traits
from matplotlib.cbook import is_string_like
from matplotlib.artist import Artist
doprint = True
flexible_true_trait = traits.Trait(
True,
{'true': True, 't': True, 'yes': True, 'y': True, 'on': True, True: True,
'false': False, 'f': False, 'no': False, 'n': False, 'off': False, False: False
})
flexible_false_trait = traits.Trait(False, flexible_true_trait)
colors = {
'c': '#00bfbf',
'b': '#0000ff',
'g': '#008000',
'k': '#000000',
'm': '#bf00bf',
'r': '#ff0000',
'w': '#ffffff',
'y': '#bfbf00',
'gold': '#FFD700',
'peachpuff': '#FFDAB9',
'navajowhite': '#FFDEAD',
}
def hex2color(s):
"Convert hex string (like html uses, eg, #efefef) to a r,g,b tuple"
return tuple([int(n, 16)/255.0 for n in (s[1:3], s[3:5], s[5:7])])
class RGBA(traits.HasTraits):
# r,g,b,a in the range 0-1 with default color 0,0,0,1 (black)
r = traits.Range(0., 1., 0.)
g = traits.Range(0., 1., 0.)
b = traits.Range(0., 1., 0.)
a = traits.Range(0., 1., 1.)
def __init__(self, r=0., g=0., b=0., a=1.):
self.r = r
self.g = g
self.b = b
self.a = a
def __repr__(self):
return 'r,g,b,a = (%1.2f, %1.2f, %1.2f, %1.2f)' %\
(self.r, self.g, self.b, self.a)
def tuple_to_rgba(ob, name, val):
tup = [float(x) for x in val]
if len(tup) == 3:
r, g, b = tup
return RGBA(r, g, b)
elif len(tup) == 4:
r, g, b, a = tup
return RGBA(r, g, b, a)
else:
raise ValueError
tuple_to_rgba.info = 'a RGB or RGBA tuple of floats'
def hex_to_rgba(ob, name, val):
rgx = re.compile('^#[0-9A-Fa-f]{6}$')
if not is_string_like(val):
raise TypeError
if rgx.match(val) is None:
raise ValueError
r, g, b = hex2color(val)
return RGBA(r, g, b, 1.0)
hex_to_rgba.info = 'a hex color string'
def colorname_to_rgba(ob, name, val):
hex = colors[val.lower()]
r, g, b = hex2color(hex)
return RGBA(r, g, b, 1.0)
colorname_to_rgba.info = 'a named color'
def float_to_rgba(ob, name, val):
val = float(val)
return RGBA(val, val, val, 1.)
float_to_rgba.info = 'a grayscale intensity'
Color = traits.Trait(RGBA(), float_to_rgba, colorname_to_rgba, RGBA,
hex_to_rgba, tuple_to_rgba)
def file_exists(ob, name, val):
fh = file(val, 'r')
return val
linestyles = ('-', '--', '-.', ':', 'steps', 'None')
TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN = range(4)
linemarkers = (None, '.', ',', 'o', '^', 'v', '<', '>', 's',
'+', 'x', 'd', 'D', '|', '_', 'h', 'H',
'p', '1', '2', '3', '4',
TICKLEFT,
TICKRIGHT,
TICKUP,
TICKDOWN,
'None'
)
class LineRC(traits.HasTraits):
linewidth = traits.Float(0.5)
linestyle = traits.Trait(*linestyles)
color = Color
marker = traits.Trait(*linemarkers)
markerfacecolor = Color
markeredgecolor = Color
markeredgewidth = traits.Float(0.5)
markersize = traits.Float(6)
antialiased = flexible_true_trait
data_clipping = flexible_false_trait
class PatchRC(traits.HasTraits):
linewidth = traits.Float(1.0)
facecolor = Color
edgecolor = Color
antialiased = flexible_true_trait
timezones = 'UTC', 'US/Central', 'ES/Eastern' # fixme: and many more
backends = ('GTKAgg', 'Cairo', 'GDK', 'GTK', 'Agg',
'GTKCairo', 'PS', 'SVG', 'Template', 'TkAgg',
'WX')
class RC(traits.HasTraits):
backend = traits.Trait(*backends)
interactive = flexible_false_trait
toolbar = traits.Trait('toolbar2', 'classic', None)
timezone = traits.Trait(*timezones)
lines = traits.Trait(LineRC())
patch = traits.Trait(PatchRC())
rc = RC()
rc.lines.color = 'r'
if doprint:
print('RC')
rc.print_traits()
print('RC lines')
rc.lines.print_traits()
print('RC patches')
rc.patch.print_traits()
class Patch(Artist, traits.HasTraits):
linewidth = traits.Float(0.5)
facecolor = Color
fc = facecolor
edgecolor = Color
fill = flexible_true_trait
def __init__(self,
edgecolor=None,
facecolor=None,
linewidth=None,
antialiased=None,
fill=1,
**kwargs
):
Artist.__init__(self)
if edgecolor is None:
edgecolor = rc.patch.edgecolor
if facecolor is None:
facecolor = rc.patch.facecolor
if linewidth is None:
linewidth = rc.patch.linewidth
if antialiased is None:
antialiased = rc.patch.antialiased
self.edgecolor = edgecolor
self.facecolor = facecolor
self.linewidth = linewidth
self.antialiased = antialiased
self.fill = fill
p = Patch()
p.facecolor = '#bfbf00'
p.edgecolor = 'gold'
p.facecolor = (1, .5, .5, .25)
p.facecolor = 0.25
p.fill = 'f'
print('p.facecolor', type(p.facecolor), p.facecolor)
print('p.fill', type(p.fill), p.fill)
if p.fill_:
print('fill')
else:
print('no fill')
if doprint:
print()
print('Patch')
p.print_traits()
0707010001f9e4000081a400001782000005de000000015689ead200000813000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/misc/rec_groupby_demo.py from __future__ import print_function
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
datafile = cbook.get_sample_data('aapl.csv', asfileobj=False)
print('loading', datafile)
r = mlab.csv2rec(datafile)
r.sort()
def daily_return(prices):
'an array of daily returns from price array'
g = np.zeros_like(prices)
g[1:] = (prices[1:] - prices[:-1])/prices[:-1]
return g
def volume_code(volume):
'code the continuous volume data categorically'
ind = np.searchsorted([1e5, 1e6, 5e6, 10e6, 1e7], volume)
return ind
# a list of (dtype_name, summary_function, output_dtype_name).
# rec_summarize will call on each function on the indicated recarray
# attribute, and the result assigned to output name in the return
# record array.
summaryfuncs = (
('date', lambda x: [thisdate.year for thisdate in x], 'years'),
('date', lambda x: [thisdate.month for thisdate in x], 'months'),
('date', lambda x: [thisdate.weekday() for thisdate in x], 'weekday'),
('adj_close', daily_return, 'dreturn'),
('volume', volume_code, 'volcode'),
)
rsum = mlab.rec_summarize(r, summaryfuncs)
# stats is a list of (dtype_name, function, output_dtype_name).
# rec_groupby will summarize the attribute identified by the
# dtype_name over the groups in the groupby list, and assign the
# result to the output_dtype_name
stats = (
('dreturn', len, 'rcnt'),
('dreturn', np.mean, 'rmean'),
('dreturn', np.median, 'rmedian'),
('dreturn', np.std, 'rsigma'),
)
# you can summarize over a single variable, like years or months
print('summary by years')
ry = mlab.rec_groupby(rsum, ('years',), stats)
print(mlab. rec2txt(ry))
print('summary by months')
rm = mlab.rec_groupby(rsum, ('months',), stats)
print(mlab.rec2txt(rm))
# or over multiple variables like years and months
print('summary by year and month')
rym = mlab.rec_groupby(rsum, ('years', 'months'), stats)
print(mlab.rec2txt(rym))
print('summary by volume')
rv = mlab.rec_groupby(rsum, ('volcode',), stats)
print(mlab.rec2txt(rv))
0707010001f9e5000081a400001782000005de000000015689ead20000033e000002600000050a00000000000000000000003000000000reloc/matplotlib/examples/misc/rec_join_demo.py from __future__ import print_function
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
datafile = cbook.get_sample_data('aapl.csv', asfileobj=False)
print('loading', datafile)
r = mlab.csv2rec(datafile)
r.sort()
r1 = r[-10:]
# Create a new array
r2 = np.empty(12, dtype=[('date', '|O4'), ('high', np.float),
('marker', np.float)])
r2 = r2.view(np.recarray)
r2.date = r.date[-17:-5]
r2.high = r.high[-17:-5]
r2.marker = np.arange(12)
print("r1:")
print(mlab.rec2txt(r1))
print("r2:")
print(mlab.rec2txt(r2))
defaults = {'marker': -1, 'close': np.NaN, 'low': -4444.}
for s in ('inner', 'outer', 'leftouter'):
rec = mlab.rec_join(['date', 'high'], r1, r2,
jointype=s, defaults=defaults)
print("\n%sjoin :\n%s" % (s, mlab.rec2txt(rec)))
0707010001f9e9000081a400001782000005de000000015689ead2000001fb000002600000050a00000000000000000000003200000000reloc/matplotlib/examples/misc/tight_bbox_test.py from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
ax = plt.axes([0.1, 0.3, 0.5, 0.5])
ax.pcolormesh(np.array([[1, 2], [3, 4]]))
plt.yticks([0.5, 1.5], ["long long tick label",
"tick label"])
plt.ylabel("My y-label")
plt.title("Check saved figures for their bboxes")
for ext in ["png", "pdf", "svg", "svgz", "eps"]:
print("saving tight_bbox_test.%s" % (ext,))
plt.savefig("tight_bbox_test.%s" % (ext,), bbox_inches="tight")
plt.show()
0707010001f9e7000081a400001782000005de0000000156931c2000000862000002600000050a00000000000000000000003200000000reloc/matplotlib/examples/misc/svg_filter_line.py """
Demonstrate SVG filtering effects which might be used with mpl.
Note that the filtering effects are only effective if your svg rederer
support it.
"""
from __future__ import print_function
import matplotlib
matplotlib.use("Svg")
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig1 = plt.figure()
ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8])
# draw lines
l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-",
mec="b", lw=5, ms=10, label="Line 1")
l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "rs-",
mec="r", lw=5, ms=10, color="r", label="Line 2")
for l in [l1, l2]:
# draw shadows with same lines with slight offset and gray colors.
xx = l.get_xdata()
yy = l.get_ydata()
shadow, = ax.plot(xx, yy)
shadow.update_from(l)
# adjust color
shadow.set_color("0.2")
# adjust zorder of the shadow lines so that it is drawn below the
# original lines
shadow.set_zorder(l.get_zorder() - 0.5)
# offset transform
ot = mtransforms.offset_copy(l.get_transform(), fig1,
x=4.0, y=-6.0, units='points')
shadow.set_transform(ot)
# set the id for a later use
shadow.set_gid(l.get_label() + "_shadow")
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
# save the figure as a string in the svg format.
from io import StringIO
f = StringIO()
plt.savefig(f, format="svg")
import xml.etree.cElementTree as ET
# filter definition for a gaussian blur
filter_def = """
"""
# read in the saved svg
tree, xmlid = ET.XMLID(f.getvalue())
# insert the filter definition in the svg dom tree.
tree.insert(0, ET.XML(filter_def))
for l in [l1, l2]:
# pick up the svg element with given id
shadow = xmlid[l.get_label() + "_shadow"]
# apply shdow filter
shadow.set("filter", 'url(#dropshadow)')
fn = "svg_filter_line.svg"
print("Saving '%s'" % fn)
ET.ElementTree(tree).write(fn)
0707010001f9e0000081a400001782000005de000000015689ead20000067c000002600000050a00000000000000000000002c00000000reloc/matplotlib/examples/misc/longshort.py """
Illustrate the rec array utility funcitons by loading prices from a
csv file, computing the daily returns, appending the results to the
record arrays, joining on date
"""
import urllib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
# grab the price data off yahoo
u1 = urllib.urlretrieve('http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=9&e=14&f=2008&g=d&a=8&b=7&c=1984&ignore=.csv')
u2 = urllib.urlretrieve('http://ichart.finance.yahoo.com/table.csv?s=GOOG&d=9&e=14&f=2008&g=d&a=8&b=7&c=1984&ignore=.csv')
# load the CSV files into record arrays
r1 = mlab.csv2rec(file(u1[0]))
r2 = mlab.csv2rec(file(u2[0]))
# compute the daily returns and add these columns to the arrays
gains1 = np.zeros_like(r1.adj_close)
gains2 = np.zeros_like(r2.adj_close)
gains1[1:] = np.diff(r1.adj_close)/r1.adj_close[:-1]
gains2[1:] = np.diff(r2.adj_close)/r2.adj_close[:-1]
r1 = mlab.rec_append_fields(r1, 'gains', gains1)
r2 = mlab.rec_append_fields(r2, 'gains', gains2)
# now join them by date; the default postfixes are 1 and 2. The
# default jointype is inner so it will do an intersection of dates and
# drop the dates in AAPL which occurred before GOOG started trading in
# 2004. r1 and r2 are reverse ordered by date since Yahoo returns
# most recent first in the CSV files, but rec_join will sort by key so
# r below will be properly sorted
r = mlab.rec_join('date', r1, r2)
# long appl, short goog
g = r.gains1 - r.gains2
tr = (1 + g).cumprod() # the total return
# plot the return
fig, ax = plt.subplots()
ax.plot(r.date, tr)
ax.set_title('total return: long APPL, short GOOG')
ax.grid()
fig.autofmt_xdate()
plt.show()
0707010001f9df000081a400001782000005de000000015689ead20000038a000002600000050a00000000000000000000003200000000reloc/matplotlib/examples/misc/image_thumbnail.py """
You can use matplotlib to generate thumbnails from existing images.
matplotlib natively supports PNG files on the input side, and other
image types transparently if your have PIL installed
"""
from __future__ import print_function
# build thumbnails of all images in a directory
import sys
import os
import glob
import matplotlib.image as image
if len(sys.argv) != 2:
print('Usage: python %s IMAGEDIR' % __file__)
raise SystemExit
indir = sys.argv[1]
if not os.path.isdir(indir):
print('Could not find input directory "%s"' % indir)
raise SystemExit
outdir = 'thumbs'
if not os.path.exists(outdir):
os.makedirs(outdir)
for fname in glob.glob(os.path.join(indir, '*.png')):
basedir, basename = os.path.split(fname)
outfile = os.path.join(outdir, basename)
fig = image.thumbnail(fname, outfile, scale=0.15)
print('saved thumbnail of %s to %s' % (fname, outfile))
0707010001f9dc000081a400001782000005de000000015689ead20000068e000002600000050a00000000000000000000003100000000reloc/matplotlib/examples/misc/contour_manual.py """
Example of displaying your own contour lines and polygons using ContourSet.
"""
import matplotlib.pyplot as plt
from matplotlib.contour import ContourSet
import matplotlib.cm as cm
# Contour lines for each level are a list/tuple of polygons.
lines0 = [[[0, 0], [0, 4]]]
lines1 = [[[2, 0], [1, 2], [1, 3]]]
lines2 = [[[3, 0], [3, 2]], [[3, 3], [3, 4]]] # Note two lines.
# Filled contours between two levels are also a list/tuple of polygons.
# Points can be ordered clockwise or anticlockwise.
filled01 = [[[0, 0], [0, 4], [1, 3], [1, 2], [2, 0]]]
filled12 = [[[2, 0], [3, 0], [3, 2], [1, 3], [1, 2]], # Note two polygons.
[[1, 4], [3, 4], [3, 3]]]
plt.figure()
# Filled contours using filled=True.
cs = ContourSet(plt.gca(), [0, 1, 2], [filled01, filled12], filled=True, cmap=cm.bone)
cbar = plt.colorbar(cs)
# Contour lines (non-filled).
lines = ContourSet(plt.gca(), [0, 1, 2], [lines0, lines1, lines2], cmap=cm.cool,
linewidths=3)
cbar.add_lines(lines)
plt.axis([-0.5, 3.5, -0.5, 4.5])
plt.title('User-specified contours')
# Multiple filled contour lines can be specified in a single list of polygon
# vertices along with a list of vertex kinds (code types) as described in the
# Path class. This is particularly useful for polygons with holes.
# Here a code type of 1 is a MOVETO, and 2 is a LINETO.
plt.figure()
filled01 = [[[0, 0], [3, 0], [3, 3], [0, 3], [1, 1], [1, 2], [2, 2], [2, 1]]]
kinds01 = [[1, 2, 2, 2, 1, 2, 2, 2]]
cs = ContourSet(plt.gca(), [0, 1], [filled01], [kinds01], filled=True)
cbar = plt.colorbar(cs)
plt.axis([-0.5, 3.5, -0.5, 3.5])
plt.title('User specified filled contours with holes')
plt.show()
0707010001f9e6000081a400001782000005de0000000155f2504c0000015d000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/misc/sample_data_demo.py """
Grab mpl data from the ~/.matplotlib/sample_data cache if it exists, else
fetch it from github and cache it
"""
from __future__ import print_function
import matplotlib.cbook as cbook
import matplotlib.pyplot as plt
fname = cbook.get_sample_data('ada.png', asfileobj=False)
print('fname', fname)
im = plt.imread(fname)
plt.imshow(im)
plt.show()
0707010001f9e2000081a400001782000005de0000000155f2504c000004c0000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/misc/rasterization_demo.py import numpy as np
import matplotlib.pyplot as plt
d = np.arange(100).reshape(10, 10)
x, y = np.meshgrid(np.arange(11), np.arange(11))
theta = 0.25*np.pi
xx = x*np.cos(theta) - y*np.sin(theta)
yy = x*np.sin(theta) + y*np.cos(theta)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
ax1.set_aspect(1)
ax1.pcolormesh(xx, yy, d)
ax1.set_title("No Rasterization")
ax2.set_aspect(1)
ax2.set_title("Rasterization")
m = ax2.pcolormesh(xx, yy, d)
m.set_rasterized(True)
ax3.set_aspect(1)
ax3.pcolormesh(xx, yy, d)
ax3.text(0.5, 0.5, "Text", alpha=0.2,
va="center", ha="center", size=50, transform=ax3.transAxes)
ax3.set_title("No Rasterization")
ax4.set_aspect(1)
m = ax4.pcolormesh(xx, yy, d)
m.set_zorder(-20)
ax4.text(0.5, 0.5, "Text", alpha=0.2,
zorder=-15,
va="center", ha="center", size=50, transform=ax4.transAxes)
ax4.set_rasterization_zorder(-10)
ax4.set_title("Rasterization z$<-10$")
# ax2.title.set_rasterized(True) # should display a warning
plt.savefig("test_rasterization.pdf", dpi=150)
plt.savefig("test_rasterization.eps", dpi=150)
if not plt.rcParams["text.usetex"]:
plt.savefig("test_rasterization.svg", dpi=150)
# svg backend currently ignores the dpi
0707010001f9e8000081a400001782000005de0000000156931c2000000b25000002600000050a00000000000000000000003100000000reloc/matplotlib/examples/misc/svg_filter_pie.py """
Demonstrate SVG filtering effects which might be used with mpl.
The pie chart drawing code is borrowed from pie_demo.py
Note that the filtering effects are only effective if your svg rederer
support it.
"""
import matplotlib
matplotlib.use("Svg")
import matplotlib.pyplot as plt
from matplotlib.patches import Shadow
# make a square figure and axes
fig1 = plt.figure(1, figsize=(6, 6))
ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode = (0, 0.05, 0, 0)
# We want to draw the shadow for each pie but we will not use "shadow"
# option as it does'n save the references to the shadow patches.
pies = ax.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%')
for w in pies[0]:
# set the id with the label.
w.set_gid(w.get_label())
# we don't want to draw the edge of the pie
w.set_ec("none")
for w in pies[0]:
# create shadow patch
s = Shadow(w, -0.01, -0.01)
s.set_gid(w.get_gid() + "_shadow")
s.set_zorder(w.get_zorder() - 0.1)
ax.add_patch(s)
# save
from io import StringIO
f = StringIO()
plt.savefig(f, format="svg")
import xml.etree.cElementTree as ET
# filter definition for shadow using a gaussian blur
# and lighteneing effect.
# The lightnening filter is copied from http://www.w3.org/TR/SVG/filters.html
# I tested it with Inkscape and Firefox3. "Gaussian blur" is supported
# in both, but the lightnening effect only in the inkscape. Also note
# that, inkscape's exporting also may not support it.
filter_def = """
"""
tree, xmlid = ET.XMLID(f.getvalue())
# insert the filter definition in the svg dom tree.
tree.insert(0, ET.XML(filter_def))
for i, pie_name in enumerate(labels):
pie = xmlid[pie_name]
pie.set("filter", 'url(#MyFilter)')
shadow = xmlid[pie_name + "_shadow"]
shadow.set("filter", 'url(#dropshadow)')
fn = "svg_filter_pie.svg"
print("Saving '%s'" % fn)
ET.ElementTree(tree).write(fn)
0707010001f9dd000081a400001782000005de00000001569316c10000053f000002600000050a00000000000000000000003000000000reloc/matplotlib/examples/misc/font_indexing.py """
A little example that shows how the various indexing into the font
tables relate to one another. Mainly for mpl developers....
"""
from __future__ import print_function
import matplotlib
from matplotlib.ft2font import FT2Font, KERNING_DEFAULT, KERNING_UNFITTED, KERNING_UNSCALED
#fname = '/usr/share/fonts/sfd/FreeSans.ttf'
fname = matplotlib.get_data_path() + '/fonts/ttf/Vera.ttf'
font = FT2Font(fname)
font.set_charmap(0)
codes = font.get_charmap().items()
#dsu = [(ccode, glyphind) for ccode, glyphind in codes]
#dsu.sort()
#for ccode, glyphind in dsu:
# try: name = font.get_glyph_name(glyphind)
# except RuntimeError: pass
# else: print('% 4d % 4d %s %s' % (glyphind, ccode, hex(int(ccode)), name))
# make a charname to charcode and glyphind dictionary
coded = {}
glyphd = {}
for ccode, glyphind in codes:
name = font.get_glyph_name(glyphind)
coded[name] = ccode
glyphd[name] = glyphind
code = coded['A']
glyph = font.load_char(code)
#print(glyph.bbox)
print(glyphd['A'], glyphd['V'], coded['A'], coded['V'])
print('AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_DEFAULT))
print('AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_UNFITTED))
print('AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_UNSCALED))
print('AV', font.get_kerning(glyphd['A'], glyphd['T'], KERNING_UNSCALED))
0707010001fb4a000041ed00001782000005de00000002570a550000000000000002600000050a00000000000000000000002200000000reloc/matplotlib/examples/widgets 0707010001fb53000081a400001782000005de000000015689ead200000896000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/widgets/rectangle_selector.py from __future__ import print_function
"""
Do a mouseclick somewhere, move the mouse to some destination, release
the button. This class gives click- and release-events and also draws
a line or a box from the click-point to the actual mouseposition
(within the same axes) until the button is released. Within the
method 'self.ignore()' it is checked wether the button from eventpress
and eventrelease are the same.
"""
from matplotlib.widgets import RectangleSelector
import numpy as np
import matplotlib.pyplot as plt
def line_select_callback(eclick, erelease):
'eclick and erelease are the press and release events'
x1, y1 = eclick.xdata, eclick.ydata
x2, y2 = erelease.xdata, erelease.ydata
print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2))
print(" The button you used were: %s %s" % (eclick.button, erelease.button))
def toggle_selector(event):
print(' Key pressed.')
if event.key in ['Q', 'q'] and toggle_selector.RS.active:
print(' RectangleSelector deactivated.')
toggle_selector.RS.set_active(False)
if event.key in ['A', 'a'] and not toggle_selector.RS.active:
print(' RectangleSelector activated.')
toggle_selector.RS.set_active(True)
fig, current_ax = plt.subplots() # make a new plotingrange
N = 100000 # If N is large one can see
x = np.linspace(0.0, 10.0, N) # improvement by use blitting!
plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7) # plot something
plt.plot(x, +np.cos(.2*np.pi*x), lw=3.5, c='r', alpha=.5)
plt.plot(x, -np.sin(.2*np.pi*x), lw=3.5, c='g', alpha=.3)
print("\n click --> release")
# drawtype is 'box' or 'line' or 'none'
toggle_selector.RS = RectangleSelector(current_ax, line_select_callback,
drawtype='box', useblit=True,
button=[1, 3], # don't use middle button
minspanx=5, minspany=5,
spancoords='pixels',
interactive=True)
plt.connect('key_press_event', toggle_selector)
plt.show()
0707010001fb4c000081a400001782000005de000000015689ead20000037f000002600000050a00000000000000000000002d00000000reloc/matplotlib/examples/widgets/buttons.py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
freqs = np.arange(2, 20, 3)
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
t = np.arange(0.0, 1.0, 0.001)
s = np.sin(2*np.pi*freqs[0]*t)
l, = plt.plot(t, s, lw=2)
class Index(object):
ind = 0
def next(self, event):
self.ind += 1
i = self.ind % len(freqs)
ydata = np.sin(2*np.pi*freqs[i]*t)
l.set_ydata(ydata)
plt.draw()
def prev(self, event):
self.ind -= 1
i = self.ind % len(freqs)
ydata = np.sin(2*np.pi*freqs[i]*t)
l.set_ydata(ydata)
plt.draw()
callback = Index()
axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)
plt.show()
0707010001fb51000081a400001782000005de000000015689e5a00000016b000002600000050a00000000000000000000003100000000reloc/matplotlib/examples/widgets/multicursor.py import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import MultiCursor
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.sin(4*np.pi*t)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot(t, s1)
ax2 = fig.add_subplot(212, sharex=ax1)
ax2.plot(t, s2)
multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1)
plt.show()
0707010001fb50000081a400001782000005de000000015689ead20000135e000002600000050a00000000000000000000002a00000000reloc/matplotlib/examples/widgets/menu.py from __future__ import division, print_function
import numpy as np
import matplotlib
import matplotlib.colors as colors
import matplotlib.patches as patches
import matplotlib.mathtext as mathtext
import matplotlib.pyplot as plt
import matplotlib.artist as artist
import matplotlib.image as image
class ItemProperties(object):
def __init__(self, fontsize=14, labelcolor='black', bgcolor='yellow',
alpha=1.0):
self.fontsize = fontsize
self.labelcolor = labelcolor
self.bgcolor = bgcolor
self.alpha = alpha
self.labelcolor_rgb = colors.colorConverter.to_rgb(labelcolor)
self.bgcolor_rgb = colors.colorConverter.to_rgb(bgcolor)
class MenuItem(artist.Artist):
parser = mathtext.MathTextParser("Bitmap")
padx = 5
pady = 5
def __init__(self, fig, labelstr, props=None, hoverprops=None,
on_select=None):
artist.Artist.__init__(self)
self.set_figure(fig)
self.labelstr = labelstr
if props is None:
props = ItemProperties()
if hoverprops is None:
hoverprops = ItemProperties()
self.props = props
self.hoverprops = hoverprops
self.on_select = on_select
x, self.depth = self.parser.to_mask(
labelstr, fontsize=props.fontsize, dpi=fig.dpi)
if props.fontsize != hoverprops.fontsize:
raise NotImplementedError(
'support for different font sizes not implemented')
self.labelwidth = x.shape[1]
self.labelheight = x.shape[0]
self.labelArray = np.zeros((x.shape[0], x.shape[1], 4))
self.labelArray[:, :, -1] = x/255.
self.label = image.FigureImage(fig, origin='upper')
self.label.set_array(self.labelArray)
# we'll update these later
self.rect = patches.Rectangle((0, 0), 1, 1)
self.set_hover_props(False)
fig.canvas.mpl_connect('button_release_event', self.check_select)
def check_select(self, event):
over, junk = self.rect.contains(event)
if not over:
return
if self.on_select is not None:
self.on_select(self)
def set_extent(self, x, y, w, h):
print(x, y, w, h)
self.rect.set_x(x)
self.rect.set_y(y)
self.rect.set_width(w)
self.rect.set_height(h)
self.label.ox = x + self.padx
self.label.oy = y - self.depth + self.pady/2.
self.rect._update_patch_transform()
self.hover = False
def draw(self, renderer):
self.rect.draw(renderer)
self.label.draw(renderer)
def set_hover_props(self, b):
if b:
props = self.hoverprops
else:
props = self.props
r, g, b = props.labelcolor_rgb
self.labelArray[:, :, 0] = r
self.labelArray[:, :, 1] = g
self.labelArray[:, :, 2] = b
self.label.set_array(self.labelArray)
self.rect.set(facecolor=props.bgcolor, alpha=props.alpha)
def set_hover(self, event):
'check the hover status of event and return true if status is changed'
b, junk = self.rect.contains(event)
changed = (b != self.hover)
if changed:
self.set_hover_props(b)
self.hover = b
return changed
class Menu(object):
def __init__(self, fig, menuitems):
self.figure = fig
fig.suppressComposite = True
self.menuitems = menuitems
self.numitems = len(menuitems)
maxw = max([item.labelwidth for item in menuitems])
maxh = max([item.labelheight for item in menuitems])
totalh = self.numitems*maxh + (self.numitems + 1)*2*MenuItem.pady
x0 = 100
y0 = 400
width = maxw + 2*MenuItem.padx
height = maxh + MenuItem.pady
for item in menuitems:
left = x0
bottom = y0 - maxh - MenuItem.pady
item.set_extent(left, bottom, width, height)
fig.artists.append(item)
y0 -= maxh + MenuItem.pady
fig.canvas.mpl_connect('motion_notify_event', self.on_move)
def on_move(self, event):
draw = False
for item in self.menuitems:
draw = item.set_hover(event)
if draw:
self.figure.canvas.draw()
break
fig = plt.figure()
fig.subplots_adjust(left=0.3)
props = ItemProperties(labelcolor='black', bgcolor='yellow',
fontsize=15, alpha=0.2)
hoverprops = ItemProperties(labelcolor='white', bgcolor='blue',
fontsize=15, alpha=0.2)
menuitems = []
for label in ('open', 'close', 'save', 'save as', 'quit'):
def on_select(item):
print('you selected %s' % item.labelstr)
item = MenuItem(fig, label, props=props, hoverprops=hoverprops,
on_select=on_select)
menuitems.append(item)
menu = Menu(fig, menuitems)
plt.show()
0707010001fb52000081a400001782000005de000000015689ead2000003f9000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/widgets/radio_buttons.py import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(8*np.pi*t)
fig, ax = plt.subplots()
l, = ax.plot(t, s0, lw=2, color='red')
plt.subplots_adjust(left=0.3)
axcolor = 'lightgoldenrodyellow'
rax = plt.axes([0.05, 0.7, 0.15, 0.15], axisbg=axcolor)
radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz'))
def hzfunc(label):
hzdict = {'2 Hz': s0, '4 Hz': s1, '8 Hz': s2}
ydata = hzdict[label]
l.set_ydata(ydata)
plt.draw()
radio.on_clicked(hzfunc)
rax = plt.axes([0.05, 0.4, 0.15, 0.15], axisbg=axcolor)
radio2 = RadioButtons(rax, ('red', 'blue', 'green'))
def colorfunc(label):
l.set_color(label)
plt.draw()
radio2.on_clicked(colorfunc)
rax = plt.axes([0.05, 0.1, 0.15, 0.15], axisbg=axcolor)
radio3 = RadioButtons(rax, ('-', '--', '-.', 'steps', ':'))
def stylefunc(label):
l.set_linestyle(label)
plt.draw()
radio3.on_clicked(stylefunc)
plt.show()
0707010001fb4d000081a400001782000005de000000015689ead2000002e4000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/widgets/check_buttons.py import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(6*np.pi*t)
fig, ax = plt.subplots()
l0, = ax.plot(t, s0, visible=False, lw=2)
l1, = ax.plot(t, s1, lw=2)
l2, = ax.plot(t, s2, lw=2)
plt.subplots_adjust(left=0.2)
rax = plt.axes([0.05, 0.4, 0.1, 0.15])
check = CheckButtons(rax, ('2 Hz', '4 Hz', '6 Hz'), (False, True, True))
def func(label):
if label == '2 Hz':
l0.set_visible(not l0.get_visible())
elif label == '4 Hz':
l1.set_visible(not l1.get_visible())
elif label == '6 Hz':
l2.set_visible(not l2.get_visible())
plt.draw()
check.on_clicked(func)
plt.show()
0707010001fb54000081a400001782000005de00000001569316c1000004a0000002600000050a00000000000000000000003100000000reloc/matplotlib/examples/widgets/slider_demo.py import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
s = a0*np.sin(2*np.pi*f0*t)
l, = plt.plot(t, s, lw=2, color='red')
plt.axis([0, 1, -10, 10])
axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axamp = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)
def update(val):
amp = samp.val
freq = sfreq.val
l.set_ydata(amp*np.sin(2*np.pi*freq*t))
fig.canvas.draw_idle()
sfreq.on_changed(update)
samp.on_changed(update)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
def reset(event):
sfreq.reset()
samp.reset()
button.on_clicked(reset)
rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
def colorfunc(label):
l.set_color(label)
fig.canvas.draw_idle()
radio.on_clicked(colorfunc)
plt.show()
0707010001fb55000081a400001782000005de00000001569316c100000446000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/widgets/span_selector.py #!/usr/bin/env python
"""
The SpanSelector is a mouse widget to select a xmin/xmax range and plot the
detail view of the selected region in the lower axes
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(211, axisbg='#FFFFCC')
x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x))
ax.plot(x, y, '-')
ax.set_ylim(-2, 2)
ax.set_title('Press left mouse button and drag to test')
ax2 = fig.add_subplot(212, axisbg='#FFFFCC')
line2, = ax2.plot(x, y, '-')
def onselect(xmin, xmax):
indmin, indmax = np.searchsorted(x, (xmin, xmax))
indmax = min(len(x) - 1, indmax)
thisx = x[indmin:indmax]
thisy = y[indmin:indmax]
line2.set_data(thisx, thisy)
ax2.set_xlim(thisx[0], thisx[-1])
ax2.set_ylim(thisy.min(), thisy.max())
fig.canvas.draw()
# set useblit True on gtkagg for enhanced performance
span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
rectprops=dict(alpha=0.5, facecolor='red'))
plt.show()
0707010001fb4b000081a400001782000005de000000015574c1e00000004d000002600000050a00000000000000000000002d00000000reloc/matplotlib/examples/widgets/README.txt Examples of how to write primitive, but GUI agnoistic, widgets in
matplotlib
0707010001fb4f000081a400001782000005de000000015689ead200000add000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/widgets/lasso_selector_demo.py from __future__ import print_function
import numpy as np
from matplotlib.widgets import LassoSelector
from matplotlib.path import Path
try:
raw_input
except NameError:
# Python 3
raw_input = input
class SelectFromCollection(object):
"""Select indices from a matplotlib collection using `LassoSelector`.
Selected indices are saved in the `ind` attribute. This tool highlights
selected points by fading them out (i.e., reducing their alpha values).
If your collection has alpha < 1, this tool will permanently alter them.
Note that this tool selects collection objects based on their *origins*
(i.e., `offsets`).
Parameters
----------
ax : :class:`~matplotlib.axes.Axes`
Axes to interact with.
collection : :class:`matplotlib.collections.Collection` subclass
Collection you want to select from.
alpha_other : 0 <= float <= 1
To highlight a selection, this tool sets all selected points to an
alpha value of 1 and non-selected points to `alpha_other`.
"""
def __init__(self, ax, collection, alpha_other=0.3):
self.canvas = ax.figure.canvas
self.collection = collection
self.alpha_other = alpha_other
self.xys = collection.get_offsets()
self.Npts = len(self.xys)
# Ensure that we have separate colors for each object
self.fc = collection.get_facecolors()
if len(self.fc) == 0:
raise ValueError('Collection must have a facecolor')
elif len(self.fc) == 1:
self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1)
self.lasso = LassoSelector(ax, onselect=self.onselect)
self.ind = []
def onselect(self, verts):
path = Path(verts)
self.ind = np.nonzero([path.contains_point(xy) for xy in self.xys])[0]
self.fc[:, -1] = self.alpha_other
self.fc[self.ind, -1] = 1
self.collection.set_facecolors(self.fc)
self.canvas.draw_idle()
def disconnect(self):
self.lasso.disconnect_events()
self.fc[:, -1] = 1
self.collection.set_facecolors(self.fc)
self.canvas.draw_idle()
if __name__ == '__main__':
import matplotlib.pyplot as plt
plt.ion()
data = np.random.rand(100, 2)
subplot_kw = dict(xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
fig, ax = plt.subplots(subplot_kw=subplot_kw)
pts = ax.scatter(data[:, 0], data[:, 1], s=80)
selector = SelectFromCollection(ax, pts)
plt.draw()
raw_input('Press any key to accept selected points')
print("Selected points:")
print(selector.xys[selector.ind])
selector.disconnect()
# Block end of script so you can check that the lasso is disconnected.
raw_input('Press any key to quit')
0707010001fb4e000081a400001782000005de00000001569316c1000001a1000002600000050a00000000000000000000002c00000000reloc/matplotlib/examples/widgets/cursor.py #!/usr/bin/env python
from matplotlib.widgets import Cursor
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, axisbg='#FFFFCC')
x, y = 4*(np.random.rand(2, 100) - .5)
ax.plot(x, y, 'o')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
# set useblit = True on gtkagg for enhanced performance
cursor = Cursor(ax, useblit=True, color='red', linewidth=2)
plt.show()
0707010001fb26000041ed00001782000005de00000002570a550000000000000002600000050a00000000000000000000002a00000000reloc/matplotlib/examples/user_interfaces 0707010001fb40000081ed00001782000005de000000015689ead200000c4b000002600000050a00000000000000000000003c00000000reloc/matplotlib/examples/user_interfaces/mpl_with_glade.py #!/usr/bin/env python
from __future__ import print_function
import matplotlib
matplotlib.use('GTK')
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar
from matplotlib.widgets import SpanSelector
from numpy import arange, sin, pi
import gtk
import gtk.glade
def simple_msg(msg, parent=None, title=None):
dialog = gtk.MessageDialog(
parent=None,
type=gtk.MESSAGE_INFO,
buttons=gtk.BUTTONS_OK,
message_format=msg)
if parent is not None:
dialog.set_transient_for(parent)
if title is not None:
dialog.set_title(title)
dialog.show()
dialog.run()
dialog.destroy()
return None
class GladeHandlers(object):
def on_buttonClickMe_clicked(event):
simple_msg('Nothing to say, really',
parent=widgets['windowMain'],
title='Thanks!')
class WidgetsWrapper(object):
def __init__(self):
self.widgets = gtk.glade.XML('mpl_with_glade.glade')
self.widgets.signal_autoconnect(GladeHandlers.__dict__)
self['windowMain'].connect('destroy', lambda x: gtk.main_quit())
self['windowMain'].move(10, 10)
self.figure = Figure(figsize=(8, 6), dpi=72)
self.axis = self.figure.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
self.axis.plot(t, s)
self.axis.set_xlabel('time (s)')
self.axis.set_ylabel('voltage')
self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea
self.canvas.show()
self.canvas.set_size_request(600, 400)
self.canvas.set_events(
gtk.gdk.BUTTON_PRESS_MASK |
gtk.gdk.KEY_PRESS_MASK |
gtk.gdk.KEY_RELEASE_MASK
)
self.canvas.set_flags(gtk.HAS_FOCUS | gtk.CAN_FOCUS)
self.canvas.grab_focus()
def keypress(widget, event):
print('key press')
def buttonpress(widget, event):
print('button press')
self.canvas.connect('key_press_event', keypress)
self.canvas.connect('button_press_event', buttonpress)
def onselect(xmin, xmax):
print(xmin, xmax)
span = SpanSelector(self.axis, onselect, 'horizontal', useblit=False,
rectprops=dict(alpha=0.5, facecolor='red'))
self['vboxMain'].pack_start(self.canvas, True, True)
self['vboxMain'].show()
# below is optional if you want the navigation toolbar
self.navToolbar = NavigationToolbar(self.canvas, self['windowMain'])
self.navToolbar.lastDir = '/var/tmp/'
self['vboxMain'].pack_start(self.navToolbar)
self.navToolbar.show()
sep = gtk.HSeparator()
sep.show()
self['vboxMain'].pack_start(sep, True, True)
self['vboxMain'].reorder_child(self['buttonClickMe'], -1)
def __getitem__(self, key):
return self.widgets.get_widget(key)
widgets = WidgetsWrapper()
gtk.main()
0707010001fb33000081a400001782000005de000000015689ead20000088e000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/user_interfaces/embedding_in_wx2.py #!/usr/bin/env python
"""
An example of how to use wx or wxagg in an application with the new
toolbar - comment out the setA_toolbar line for no toolbar
"""
# matplotlib requires wxPython 2.8+
# set the wxPython version in lib\site-packages\wx.pth file
# or if you have wxversion installed un-comment the lines below
#import wxversion
#wxversion.ensureMinimal('2.8')
from numpy import arange, sin, pi
import matplotlib
# uncomment the following to use wx rather than wxagg
#matplotlib.use('WX')
#from matplotlib.backends.backend_wx import FigureCanvasWx as FigureCanvas
# comment out the following to use wx rather than wxagg
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure
import wx
import wx.lib.mixins.inspection as WIT
class CanvasFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1,
'CanvasFrame', size=(550, 350))
self.figure = Figure()
self.axes = self.figure.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2 * pi * t)
self.axes.plot(t, s)
self.canvas = FigureCanvas(self, -1, self.figure)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND)
self.SetSizer(self.sizer)
self.Fit()
self.add_toolbar() # comment this out for no toolbar
def add_toolbar(self):
self.toolbar = NavigationToolbar2Wx(self.canvas)
self.toolbar.Realize()
# By adding toolbar in sizer, we are able to put it at the bottom
# of the frame - so appearance is closer to GTK version.
self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
# update the axes menu on the toolbar
self.toolbar.update()
# alternatively you could use
#class App(wx.App):
class App(WIT.InspectableApp):
def OnInit(self):
'Create the main window and insert the custom frame'
self.Init()
frame = CanvasFrame()
frame.Show(True)
return True
app = App(0)
app.MainLoop()
0707010001fb45000081a400001782000005de000000015689ead2000001e9000002600000050a00000000000000000000004100000000reloc/matplotlib/examples/user_interfaces/rec_edit_gtk_simple.py """
Load a CSV file into a record array and edit it in a gtk treeview
"""
import gtk
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import mpl_toolkits.gtktools as gtktools
datafile = cbook.get_sample_data('demodata.csv', asfileobj=False)
r = mlab.csv2rec(datafile, converterd={'weekdays': str})
liststore, treeview, win = gtktools.edit_recarray(r)
win.set_title('click to edit')
win.connect('delete-event', lambda *args: gtk.main_quit())
gtk.main()
0707010001fb3b000081ed00001782000005de000000015689ead200002006000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/user_interfaces/interactive.py #!/usr/bin/env python
"""Multithreaded interactive interpreter with GTK and Matplotlib support.
WARNING:
As of 2010/06/25, this is not working, at least on Linux.
I have disabled it as a runnable script. - EF
Usage:
pyint-gtk.py -> starts shell with gtk thread running separately
pyint-gtk.py -pylab [filename] -> initializes matplotlib, optionally running
the named file. The shell starts after the file is executed.
Threading code taken from:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
McErlean and John Finlay.
Matplotlib support taken from interactive.py in the matplotlib distribution.
Also borrows liberally from code.py in the Python standard library."""
from __future__ import print_function
__author__ = "Fernando Perez "
import sys
import code
import threading
import gobject
import gtk
try:
import readline
except ImportError:
has_readline = False
else:
has_readline = True
class MTConsole(code.InteractiveConsole):
"""Simple multi-threaded shell"""
def __init__(self, on_kill=None, *args, **kw):
code.InteractiveConsole.__init__(self, *args, **kw)
self.code_to_run = None
self.ready = threading.Condition()
self._kill = False
if on_kill is None:
on_kill = []
# Check that all things to kill are callable:
for _ in on_kill:
if not callable(_):
raise TypeError('on_kill must be a list of callables')
self.on_kill = on_kill
# Set up tab-completer
if has_readline:
import rlcompleter
try: # this form only works with python 2.3
self.completer = rlcompleter.Completer(self.locals)
except: # simpler for py2.2
self.completer = rlcompleter.Completer()
readline.set_completer(self.completer.complete)
# Use tab for completions
readline.parse_and_bind('tab: complete')
# This forces readline to automatically print the above list when tab
# completion is set to 'complete'.
readline.parse_and_bind('set show-all-if-ambiguous on')
# Bindings for incremental searches in the history. These searches
# use the string typed so far on the command line and search
# anything in the previous input history containing them.
readline.parse_and_bind('"\C-r": reverse-search-history')
readline.parse_and_bind('"\C-s": forward-search-history')
def runsource(self, source, filename="", symbol="single"):
"""Compile and run some source in the interpreter.
Arguments are as for compile_command().
One several things can happen:
1) The input is incorrect; compile_command() raised an
exception (SyntaxError or OverflowError). A syntax traceback
will be printed by calling the showsyntaxerror() method.
2) The input is incomplete, and more input is required;
compile_command() returned None. Nothing happens.
3) The input is complete; compile_command() returned a code
object. The code is executed by calling self.runcode() (which
also handles run-time exceptions, except for SystemExit).
The return value is True in case 2, False in the other cases (unless
an exception is raised). The return value can be used to
decide whether to use sys.ps1 or sys.ps2 to prompt the next
line.
"""
try:
code = self.compile(source, filename, symbol)
except (OverflowError, SyntaxError, ValueError):
# Case 1
self.showsyntaxerror(filename)
return False
if code is None:
# Case 2
return True
# Case 3
# Store code in self, so the execution thread can handle it
self.ready.acquire()
self.code_to_run = code
self.ready.wait() # Wait until processed in timeout interval
self.ready.release()
return False
def runcode(self):
"""Execute a code object.
When an exception occurs, self.showtraceback() is called to display a
traceback."""
self.ready.acquire()
if self._kill:
print('Closing threads...')
sys.stdout.flush()
for tokill in self.on_kill:
tokill()
print('Done.')
if self.code_to_run is not None:
self.ready.notify()
code.InteractiveConsole.runcode(self, self.code_to_run)
self.code_to_run = None
self.ready.release()
return True
def kill(self):
"""Kill the thread, returning when it has been shut down."""
self.ready.acquire()
self._kill = True
self.ready.release()
class GTKInterpreter(threading.Thread):
"""Run gtk.main in the main thread and a python interpreter in a
separate thread.
Python commands can be passed to the thread where they will be executed.
This is implemented by periodically checking for passed code using a
GTK timeout callback.
"""
TIMEOUT = 100 # Millisecond interval between timeouts.
def __init__(self, banner=None):
threading.Thread.__init__(self)
self.banner = banner
self.shell = MTConsole(on_kill=[gtk.main_quit])
def run(self):
self.pre_interact()
self.shell.interact(self.banner)
self.shell.kill()
def mainloop(self):
self.start()
gobject.timeout_add(self.TIMEOUT, self.shell.runcode)
try:
if gtk.gtk_version[0] >= 2:
gtk.gdk.threads_init()
except AttributeError:
pass
gtk.main()
self.join()
def pre_interact(self):
"""This method should be overridden by subclasses.
It gets called right before interact(), but after the thread starts.
Typically used to push initialization code into the interpreter"""
pass
class MatplotLibInterpreter(GTKInterpreter):
"""Threaded interpreter with matplotlib support.
Note that this explicitly sets GTKAgg as the backend, since it has
specific GTK hooks in it."""
def __init__(self, banner=None):
banner = """\nWelcome to matplotlib, a MATLAB-like python environment.
help(matlab) -> help on matlab compatible commands from matplotlib.
help(plotting) -> help on plotting commands.
"""
GTKInterpreter.__init__(self, banner)
def pre_interact(self):
"""Initialize matplotlib before user interaction begins"""
push = self.shell.push
# Code to execute in user's namespace
lines = ["import matplotlib",
"matplotlib.use('GTKAgg')",
"matplotlib.interactive(1)",
"import matplotlib.pylab as pylab",
"from matplotlib.pylab import *\n"]
map(push, lines)
# Execute file if given.
if len(sys.argv) > 1:
import matplotlib
matplotlib.interactive(0) # turn off interaction
fname = sys.argv[1]
try:
inFile = file(fname, 'r')
except IOError:
print('*** ERROR *** Could not read file <%s>' % fname)
else:
print('*** Executing file <%s>:' % fname)
for line in inFile:
if line.lstrip().find('show()') == 0:
continue
print('>>', line)
push(line)
inFile.close()
matplotlib.interactive(1) # turn on interaction
if __name__ == '__main__':
print("This demo is not presently functional, so running")
print("it as a script has been disabled.")
sys.exit()
# Quick sys.argv hack to extract the option and leave filenames in sys.argv.
# For real option handling, use optparse or getopt.
if len(sys.argv) > 1 and sys.argv[1] == '-pylab':
sys.argv = [sys.argv[0]] + sys.argv[2:]
MatplotLibInterpreter().mainloop()
else:
GTKInterpreter().mainloop()
0707010001fb34000081ed00001782000005de000000015689ead200001381000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/user_interfaces/embedding_in_wx3.py #!/usr/bin/env python
"""
Copyright (C) 2003-2004 Andrew Straw, Jeremy O'Donoghue and others
License: This work is licensed under the PSF. A copy should be included
with this source code, and is also available at
http://www.python.org/psf/license.html
This is yet another example of using matplotlib with wx. Hopefully
this is pretty full-featured:
- both matplotlib toolbar and WX buttons manipulate plot
- full wxApp framework, including widget interaction
- XRC (XML wxWidgets resource) file to create GUI (made with XRCed)
This was derived from embedding_in_wx and dynamic_image_wxagg.
Thanks to matplotlib and wx teams for creating such great software!
"""
from __future__ import print_function
# matplotlib requires wxPython 2.8+
# set the wxPython version in lib\site-packages\wx.pth file
# or if you have wxversion installed un-comment the lines below
#import wxversion
#wxversion.ensureMinimal('2.8')
import sys
import time
import os
import gc
import matplotlib
matplotlib.use('WXAgg')
import matplotlib.cm as cm
import matplotlib.cbook as cbook
from matplotlib.backends.backend_wxagg import Toolbar, FigureCanvasWxAgg
from matplotlib.figure import Figure
import numpy as np
import wx
import wx.xrc as xrc
ERR_TOL = 1e-5 # floating point slop for peak-detection
matplotlib.rc('image', origin='lower')
class PlotPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
self.fig = Figure((5, 4), 75)
self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
self.toolbar = Toolbar(self.canvas) # matplotlib toolbar
self.toolbar.Realize()
# self.toolbar.set_active([0,1])
# Now put all into a sizer
sizer = wx.BoxSizer(wx.VERTICAL)
# This way of adding to sizer allows resizing
sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
# Best to allow the toolbar to resize!
sizer.Add(self.toolbar, 0, wx.GROW)
self.SetSizer(sizer)
self.Fit()
def init_plot_data(self):
a = self.fig.add_subplot(111)
x = np.arange(120.0) * 2 * np.pi / 60.0
y = np.arange(100.0) * 2 * np.pi / 50.0
self.x, self.y = np.meshgrid(x, y)
z = np.sin(self.x) + np.cos(self.y)
self.im = a.imshow(z, cmap=cm.jet) # , interpolation='nearest')
zmax = np.amax(z) - ERR_TOL
ymax_i, xmax_i = np.nonzero(z >= zmax)
if self.im.origin == 'upper':
ymax_i = z.shape[0] - ymax_i
self.lines = a.plot(xmax_i, ymax_i, 'ko')
self.toolbar.update() # Not sure why this is needed - ADS
def GetToolBar(self):
# You will need to override GetToolBar if you are using an
# unmanaged toolbar in your frame
return self.toolbar
def OnWhiz(self, evt):
self.x += np.pi / 15
self.y += np.pi / 20
z = np.sin(self.x) + np.cos(self.y)
self.im.set_array(z)
zmax = np.amax(z) - ERR_TOL
ymax_i, xmax_i = np.nonzero(z >= zmax)
if self.im.origin == 'upper':
ymax_i = z.shape[0] - ymax_i
self.lines[0].set_data(xmax_i, ymax_i)
self.canvas.draw()
def onEraseBackground(self, evt):
# this is supposed to prevent redraw flicker on some X servers...
pass
class MyApp(wx.App):
def OnInit(self):
xrcfile = cbook.get_sample_data('embedding_in_wx3.xrc',
asfileobj=False)
print('loading', xrcfile)
self.res = xrc.XmlResource(xrcfile)
# main frame and panel ---------
self.frame = self.res.LoadFrame(None, "MainFrame")
self.panel = xrc.XRCCTRL(self.frame, "MainPanel")
# matplotlib panel -------------
# container for matplotlib panel (I like to make a container
# panel for our panel so I know where it'll go when in XRCed.)
plot_container = xrc.XRCCTRL(self.frame, "plot_container_panel")
sizer = wx.BoxSizer(wx.VERTICAL)
# matplotlib panel itself
self.plotpanel = PlotPanel(plot_container)
self.plotpanel.init_plot_data()
# wx boilerplate
sizer.Add(self.plotpanel, 1, wx.EXPAND)
plot_container.SetSizer(sizer)
# whiz button ------------------
whiz_button = xrc.XRCCTRL(self.frame, "whiz_button")
whiz_button.Bind(wx.EVT_BUTTON, self.plotpanel.OnWhiz)
# bang button ------------------
bang_button = xrc.XRCCTRL(self.frame, "bang_button")
bang_button.Bind(wx.EVT_BUTTON, self.OnBang)
# final setup ------------------
sizer = self.panel.GetSizer()
self.frame.Show(1)
self.SetTopWindow(self.frame)
return True
def OnBang(self, event):
bang_count = xrc.XRCCTRL(self.frame, "bang_count")
bangs = bang_count.GetValue()
bangs = int(bangs) + 1
bang_count.SetValue(str(bangs))
if __name__ == '__main__':
app = MyApp(0)
app.MainLoop()
0707010001fb3f000081a400001782000005de000000015574c1e000002725000002600000050a00000000000000000000003f00000000reloc/matplotlib/examples/user_interfaces/mpl_with_glade.glade
Truewindow1GTK_WINDOW_TOPLEVELGTK_WIN_POS_NONEFalseTrueFalseTrueFalseFalseGDK_WINDOW_TYPE_HINT_NORMALGDK_GRAVITY_NORTH_WESTTrue4TrueFalse2TrueTrue_FileTrueTruegtk-newTrueTruegtk-openTrueTruegtk-saveTrueTruegtk-save-asTrueTrueTruegtk-quitTrueTrue_EditTrueTruegtk-cutTrueTruegtk-copyTrueTruegtk-pasteTrueTruegtk-deleteTrueTrue_ViewTrueTrue_HelpTrueTrue_AboutTrue0FalseFalseTrueTrueGTK_RELIEF_NORMALTrueTrue0.50.5000000TrueFalse2Truegtk-dialog-info40.50.5000FalseFalseTrueClick Me!TrueFalseGTK_JUSTIFY_LEFTFalseFalse0.50.500PANGO_ELLIPSIZE_NONE-1False00FalseFalse0FalseFalse
0707010001fb38000081a400001782000005de000000015689ead2000022fb000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/user_interfaces/fourier_demo_wx.py #!/usr/bin/env python
import numpy as np
# matplotlib requires wxPython 2.8+
# set the wxPython version in lib\site-packages\wx.pth file
# or if you have wxversion installed un-comment the lines below
#import wxversion
#wxversion.ensureMinimal('2.8')
import wx
import matplotlib
matplotlib.interactive(False)
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.figure import Figure
from matplotlib.pyplot import gcf, setp
class Knob(object):
"""
Knob - simple class with a "setKnob" method.
A Knob instance is attached to a Param instance, e.g., param.attach(knob)
Base class is for documentation purposes.
"""
def setKnob(self, value):
pass
class Param(object):
"""
The idea of the "Param" class is that some parameter in the GUI may have
several knobs that both control it and reflect the parameter's state, e.g.
a slider, text, and dragging can all change the value of the frequency in
the waveform of this example.
The class allows a cleaner way to update/"feedback" to the other knobs when
one is being changed. Also, this class handles min/max constraints for all
the knobs.
Idea - knob list - in "set" method, knob object is passed as well
- the other knobs in the knob list have a "set" method which gets
called for the others.
"""
def __init__(self, initialValue=None, minimum=0., maximum=1.):
self.minimum = minimum
self.maximum = maximum
if initialValue != self.constrain(initialValue):
raise ValueError('illegal initial value')
self.value = initialValue
self.knobs = []
def attach(self, knob):
self.knobs += [knob]
def set(self, value, knob=None):
self.value = value
self.value = self.constrain(value)
for feedbackKnob in self.knobs:
if feedbackKnob != knob:
feedbackKnob.setKnob(self.value)
return self.value
def constrain(self, value):
if value <= self.minimum:
value = self.minimum
if value >= self.maximum:
value = self.maximum
return value
class SliderGroup(Knob):
def __init__(self, parent, label, param):
self.sliderLabel = wx.StaticText(parent, label=label)
self.sliderText = wx.TextCtrl(parent, -1, style=wx.TE_PROCESS_ENTER)
self.slider = wx.Slider(parent, -1)
# self.slider.SetMax(param.maximum*1000)
self.slider.SetRange(0, param.maximum * 1000)
self.setKnob(param.value)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.sliderLabel, 0,
wx.EXPAND | wx.ALIGN_CENTER | wx.ALL,
border=2)
sizer.Add(self.sliderText, 0,
wx.EXPAND | wx.ALIGN_CENTER | wx.ALL,
border=2)
sizer.Add(self.slider, 1, wx.EXPAND)
self.sizer = sizer
self.slider.Bind(wx.EVT_SLIDER, self.sliderHandler)
self.sliderText.Bind(wx.EVT_TEXT_ENTER, self.sliderTextHandler)
self.param = param
self.param.attach(self)
def sliderHandler(self, evt):
value = evt.GetInt() / 1000.
self.param.set(value)
def sliderTextHandler(self, evt):
value = float(self.sliderText.GetValue())
self.param.set(value)
def setKnob(self, value):
self.sliderText.SetValue('%g' % value)
self.slider.SetValue(value * 1000)
class FourierDemoFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.fourierDemoWindow = FourierDemoWindow(self)
self.frequencySliderGroup = SliderGroup(
self,
label='Frequency f0:',
param=self.fourierDemoWindow.f0)
self.amplitudeSliderGroup = SliderGroup(self, label=' Amplitude a:',
param=self.fourierDemoWindow.A)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.fourierDemoWindow, 1, wx.EXPAND)
sizer.Add(self.frequencySliderGroup.sizer, 0,
wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, border=5)
sizer.Add(self.amplitudeSliderGroup.sizer, 0,
wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, border=5)
self.SetSizer(sizer)
class FourierDemoWindow(wx.Window, Knob):
def __init__(self, *args, **kwargs):
wx.Window.__init__(self, *args, **kwargs)
self.lines = []
self.figure = Figure()
self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
self.canvas.callbacks.connect('button_press_event', self.mouseDown)
self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion)
self.canvas.callbacks.connect('button_release_event', self.mouseUp)
self.state = ''
self.mouseInfo = (None, None, None, None)
self.f0 = Param(2., minimum=0., maximum=6.)
self.A = Param(1., minimum=0.01, maximum=2.)
self.draw()
# Not sure I like having two params attached to the same Knob,
# but that is what we have here... it works but feels kludgy -
# although maybe it's not too bad since the knob changes both params
# at the same time (both f0 and A are affected during a drag)
self.f0.attach(self)
self.A.attach(self)
self.Bind(wx.EVT_SIZE, self.sizeHandler)
self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint(self, event):
self.canvas.draw()
event.Skip()
def sizeHandler(self, *args, **kwargs):
self.canvas.SetSize(self.GetSize())
def mouseDown(self, evt):
if self.lines[0] in self.figure.hitlist(evt):
self.state = 'frequency'
elif self.lines[1] in self.figure.hitlist(evt):
self.state = 'time'
else:
self.state = ''
self.mouseInfo = (evt.xdata, evt.ydata,
max(self.f0.value, .1),
self.A.value)
def mouseMotion(self, evt):
if self.state == '':
return
x, y = evt.xdata, evt.ydata
if x is None: # outside the axes
return
x0, y0, f0Init, AInit = self.mouseInfo
self.A.set(AInit + (AInit * (y - y0) / y0), self)
if self.state == 'frequency':
self.f0.set(f0Init + (f0Init * (x - x0) / x0))
elif self.state == 'time':
if (x - x0) / x0 != -1.:
self.f0.set(1. / (1. / f0Init + (1. / f0Init * (x - x0) / x0)))
def mouseUp(self, evt):
self.state = ''
def draw(self):
if not hasattr(self, 'subplot1'):
self.subplot1 = self.figure.add_subplot(211)
self.subplot2 = self.figure.add_subplot(212)
x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
color = (1., 0., 0.)
self.lines += self.subplot1.plot(x1, y1, color=color, linewidth=2)
self.lines += self.subplot2.plot(x2, y2, color=color, linewidth=2)
# Set some plot attributes
self.subplot1.set_title(
"Click and drag waveforms to change frequency and amplitude",
fontsize=12)
self.subplot1.set_ylabel("Frequency Domain Waveform X(f)", fontsize=8)
self.subplot1.set_xlabel("frequency f", fontsize=8)
self.subplot2.set_ylabel("Time Domain Waveform x(t)", fontsize=8)
self.subplot2.set_xlabel("time t", fontsize=8)
self.subplot1.set_xlim([-6, 6])
self.subplot1.set_ylim([0, 1])
self.subplot2.set_xlim([-2, 2])
self.subplot2.set_ylim([-2, 2])
self.subplot1.text(0.05, .95,
r'$X(f) = \mathcal{F}\{x(t)\}$',
verticalalignment='top',
transform=self.subplot1.transAxes)
self.subplot2.text(0.05, .95,
r'$x(t) = a \cdot \cos(2\pi f_0 t) e^{-\pi t^2}$',
verticalalignment='top',
transform=self.subplot2.transAxes)
def compute(self, f0, A):
f = np.arange(-6., 6., 0.02)
t = np.arange(-2., 2., 0.01)
x = A * np.cos(2 * np.pi * f0 * t) * np.exp(-np.pi * t ** 2)
X = A / 2 * \
(np.exp(-np.pi * (f - f0) ** 2) + np.exp(-np.pi * (f + f0) ** 2))
return f, X, t, x
def repaint(self):
self.canvas.draw()
def setKnob(self, value):
# Note, we ignore value arg here and just go by state of the params
x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
setp(self.lines[0], xdata=x1, ydata=y1)
setp(self.lines[1], xdata=x2, ydata=y2)
self.repaint()
class App(wx.App):
def OnInit(self):
self.frame1 = FourierDemoFrame(parent=None, title="Fourier Demo",
size=(640, 480))
self.frame1.Show()
return True
app = App()
app.MainLoop()
0707010001fb2d000081ed00001782000005de000000015689ead200001075000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/user_interfaces/embedding_in_qt4.py #!/usr/bin/env python
# embedding_in_qt4.py --- Simple Qt4 application embedding matplotlib canvases
#
# Copyright (C) 2005 Florent Rougon
# 2006 Darren Dale
#
# This file is an example program for matplotlib. It may be used and
# modified with no restriction; raw copies as well as modified versions
# may be distributed without limitation.
from __future__ import unicode_literals
import sys
import os
import random
from matplotlib.backends import qt_compat
use_pyside = qt_compat.QT_API == qt_compat.QT_API_PYSIDE
if use_pyside:
from PySide import QtGui, QtCore
else:
from PyQt4 import QtGui, QtCore
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
progname = os.path.basename(sys.argv[0])
progversion = "0.1"
class MyMplCanvas(FigureCanvas):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
# We want the axes cleared every time plot() is called
self.axes.hold(False)
self.compute_initial_figure()
#
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def compute_initial_figure(self):
pass
class MyStaticMplCanvas(MyMplCanvas):
"""Simple canvas with a sine plot."""
def compute_initial_figure(self):
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
self.axes.plot(t, s)
class MyDynamicMplCanvas(MyMplCanvas):
"""A canvas that updates itself every second with a new plot."""
def __init__(self, *args, **kwargs):
MyMplCanvas.__init__(self, *args, **kwargs)
timer = QtCore.QTimer(self)
timer.timeout.connect(self.update_figure)
timer.start(1000)
def compute_initial_figure(self):
self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')
def update_figure(self):
# Build a list of 4 random integers between 0 and 10 (both inclusive)
l = [random.randint(0, 10) for i in range(4)]
self.axes.plot([0, 1, 2, 3], l, 'r')
self.draw()
class ApplicationWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setWindowTitle("application main window")
self.file_menu = QtGui.QMenu('&File', self)
self.file_menu.addAction('&Quit', self.fileQuit,
QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
self.menuBar().addMenu(self.file_menu)
self.help_menu = QtGui.QMenu('&Help', self)
self.menuBar().addSeparator()
self.menuBar().addMenu(self.help_menu)
self.help_menu.addAction('&About', self.about)
self.main_widget = QtGui.QWidget(self)
l = QtGui.QVBoxLayout(self.main_widget)
sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)
dc = MyDynamicMplCanvas(self.main_widget, width=5, height=4, dpi=100)
l.addWidget(sc)
l.addWidget(dc)
self.main_widget.setFocus()
self.setCentralWidget(self.main_widget)
self.statusBar().showMessage("All hail matplotlib!", 2000)
def fileQuit(self):
self.close()
def closeEvent(self, ce):
self.fileQuit()
def about(self):
QtGui.QMessageBox.about(self, "About",
"""embedding_in_qt4.py example
Copyright 2005 Florent Rougon, 2006 Darren Dale
This program is a simple example of a Qt4 application embedding matplotlib
canvases.
It may be used and modified with no restriction; raw copies as well as
modified versions may be distributed without limitation."""
)
qApp = QtGui.QApplication(sys.argv)
aw = ApplicationWindow()
aw.setWindowTitle("%s" % progname)
aw.show()
sys.exit(qApp.exec_())
#qApp.exec_()
0707010001fb43000081a400001782000005de000000015689ead200000597000002600000050a00000000000000000000003c00000000reloc/matplotlib/examples/user_interfaces/pylab_with_gtk.py """
An example of how to use pylab to manage your figure windows, but
modify the GUI by accessing the underlying gtk widgets
"""
from __future__ import print_function
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.plot([1, 2, 3], 'ro-', label='easy as 1 2 3')
plt.plot([1, 4, 9], 'gs--', label='easy as 1 2 3 squared')
plt.legend()
manager = plt.get_current_fig_manager()
# you can also access the window or vbox attributes this way
toolbar = manager.toolbar
# now let's add a button to the toolbar
import gtk
next = 8 # where to insert this in the mpl toolbar
button = gtk.Button('Click me')
button.show()
def clicked(button):
print('hi mom')
button.connect('clicked', clicked)
toolitem = gtk.ToolItem()
toolitem.show()
toolitem.set_tooltip(
toolbar.tooltips,
'Click me for fun and profit')
toolitem.add(button)
toolbar.insert(toolitem, next)
next += 1
# now let's add a widget to the vbox
label = gtk.Label()
label.set_markup('Drag mouse over axes for position')
label.show()
vbox = manager.vbox
vbox.pack_start(label, False, False)
vbox.reorder_child(manager.toolbar, -1)
def update(event):
if event.xdata is None:
label.set_markup('Drag mouse over axes for position')
else:
label.set_markup('x,y=(%f, %f)' % (event.xdata, event.ydata))
plt.connect('motion_notify_event', update)
plt.show()
0707010001fb2f000081ed00001782000005de000000015689ead2000010e8000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/user_interfaces/embedding_in_qt5.py #!/usr/bin/env python
# embedding_in_qt5.py --- Simple Qt5 application embedding matplotlib canvases
#
# Copyright (C) 2005 Florent Rougon
# 2006 Darren Dale
# 2015 Jens H Nielsen
#
# This file is an example program for matplotlib. It may be used and
# modified with no restriction; raw copies as well as modified versions
# may be distributed without limitation.
from __future__ import unicode_literals
import sys
import os
import random
import matplotlib
# Make sure that we are using QT5
matplotlib.use('Qt5Agg')
from PyQt5 import QtGui, QtCore, QtWidgets
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
progname = os.path.basename(sys.argv[0])
progversion = "0.1"
class MyMplCanvas(FigureCanvas):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
# We want the axes cleared every time plot() is called
self.axes.hold(False)
self.compute_initial_figure()
#
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def compute_initial_figure(self):
pass
class MyStaticMplCanvas(MyMplCanvas):
"""Simple canvas with a sine plot."""
def compute_initial_figure(self):
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
self.axes.plot(t, s)
class MyDynamicMplCanvas(MyMplCanvas):
"""A canvas that updates itself every second with a new plot."""
def __init__(self, *args, **kwargs):
MyMplCanvas.__init__(self, *args, **kwargs)
timer = QtCore.QTimer(self)
timer.timeout.connect(self.update_figure)
timer.start(1000)
def compute_initial_figure(self):
self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')
def update_figure(self):
# Build a list of 4 random integers between 0 and 10 (both inclusive)
l = [random.randint(0, 10) for i in range(4)]
self.axes.plot([0, 1, 2, 3], l, 'r')
self.draw()
class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setWindowTitle("application main window")
self.file_menu = QtWidgets.QMenu('&File', self)
self.file_menu.addAction('&Quit', self.fileQuit,
QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
self.menuBar().addMenu(self.file_menu)
self.help_menu = QtWidgets.QMenu('&Help', self)
self.menuBar().addSeparator()
self.menuBar().addMenu(self.help_menu)
self.help_menu.addAction('&About', self.about)
self.main_widget = QtWidgets.QWidget(self)
l = QtWidgets.QVBoxLayout(self.main_widget)
sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)
dc = MyDynamicMplCanvas(self.main_widget, width=5, height=4, dpi=100)
l.addWidget(sc)
l.addWidget(dc)
self.main_widget.setFocus()
self.setCentralWidget(self.main_widget)
self.statusBar().showMessage("All hail matplotlib!", 2000)
def fileQuit(self):
self.close()
def closeEvent(self, ce):
self.fileQuit()
def about(self):
QtGui.QMessageBox.about(self, "About",
"""embedding_in_qt5.py example
Copyright 2005 Florent Rougon, 2006 Darren Dale, 2015 Jens H Nielsen
This program is a simple example of a Qt5 application embedding matplotlib
canvases.
It may be used and modified with no restriction; raw copies as well as
modified versions may be distributed without limitation.
This is modified from the embedding in qt4 example to show the difference
between qt4 and qt5"""
)
qApp = QtWidgets.QApplication(sys.argv)
aw = ApplicationWindow()
aw.setWindowTitle("%s" % progname)
aw.show()
sys.exit(qApp.exec_())
#qApp.exec_()
0707010001fb48000081a400001782000005de00000001569316c100000b3f000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/user_interfaces/toolmanager.py '''This example demonstrates how to:
* Modify the Toolbar
* Create tools
* Add tools
* Remove tools
Using `matplotlib.backend_managers.ToolManager`
'''
from __future__ import print_function
import matplotlib
matplotlib.use('GTK3Cairo')
matplotlib.rcParams['toolbar'] = 'toolmanager'
import matplotlib.pyplot as plt
from matplotlib.backend_tools import ToolBase, ToolToggleBase
from gi.repository import Gtk, Gdk
class ListTools(ToolBase):
'''List all the tools controlled by the `ToolManager`'''
# keyboard shortcut
default_keymap = 'm'
description = 'List Tools'
def trigger(self, *args, **kwargs):
print('_' * 80)
print("{0:12} {1:45} {2}".format('Name (id)',
'Tool description',
'Keymap'))
print('-' * 80)
tools = self.toolmanager.tools
for name in sorted(tools.keys()):
if not tools[name].description:
continue
keys = ', '.join(sorted(self.toolmanager.get_tool_keymap(name)))
print("{0:12} {1:45} {2}".format(name,
tools[name].description,
keys))
print('_' * 80)
print("Active Toggle tools")
print("{0:12} {1:45}".format("Group", "Active"))
print('-' * 80)
for group, active in self.toolmanager.active_toggle.items():
print("{0:12} {1:45}".format(group, active))
class GroupHideTool(ToolToggleBase):
'''Hide lines with a given gid'''
default_keymap = 'G'
description = 'Hide by gid'
def __init__(self, *args, **kwargs):
self.gid = kwargs.pop('gid')
ToolToggleBase.__init__(self, *args, **kwargs)
def enable(self, *args):
self.set_lines_visibility(False)
def disable(self, *args):
self.set_lines_visibility(True)
def set_lines_visibility(self, state):
gr_lines = []
for ax in self.figure.get_axes():
for line in ax.get_lines():
if line.get_gid() == self.gid:
line.set_visible(state)
self.figure.canvas.draw()
fig = plt.figure()
plt.plot([1, 2, 3], gid='mygroup')
plt.plot([2, 3, 4], gid='unknown')
plt.plot([3, 2, 1], gid='mygroup')
# Add the custom tools that we created
fig.canvas.manager.toolmanager.add_tool('List', ListTools)
fig.canvas.manager.toolmanager.add_tool('Hide', GroupHideTool, gid='mygroup')
# Add an existing tool to new group `foo`.
# It can be added as many times as we want
fig.canvas.manager.toolbar.add_tool('zoom', 'foo')
# Remove the forward button
fig.canvas.manager.toolmanager.remove_tool('forward')
# To add a custom tool to the toolbar at specific location inside
# the navigation group
fig.canvas.manager.toolbar.add_tool('Hide', 'navigation', 1)
plt.show()
0707010001fb27000081a400001782000005de000000015574c1e00000020d000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/user_interfaces/README.txt Embedding matplotlib in graphical user interfaces
=================================================
You can embed matplotlib directly into a user interface application by
following the embedding_in_SOMEGUI.py examples here. Currently
matplotlib supports wxpython, pygtk, tkinter, pyqt, fltk and cocoa.
When embedding matplotlib in a GUI, you must use the matplotlib API
directly rather than the pylab/pyplot proceedural interface, so take a
look at the examples/api directory for some example code working with
the API.
0707010001fb49000081a400001782000005de000000015689ead20000092d000002600000050a00000000000000000000003b00000000reloc/matplotlib/examples/user_interfaces/wxcursor_demo.py """
Example to draw a cursor and report the data coords in wx
"""
# matplotlib requires wxPython 2.8+
# set the wxPython version in lib\site-packages\wx.pth file
# or if you have wxversion installed un-comment the lines below
#import wxversion
#wxversion.ensureMinimal('2.8')
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx, wxc
from matplotlib.figure import Figure
from numpy import arange, sin, pi
import wx
class CanvasFrame(wx.Frame):
def __init__(self, ):
wx.Frame.__init__(self, None, -1,
'CanvasFrame', size=(550, 350))
self.SetBackgroundColour(wxc.NamedColour("WHITE"))
self.figure = Figure()
self.axes = self.figure.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
self.axes.plot(t, s)
self.axes.set_xlabel('t')
self.axes.set_ylabel('sin(t)')
self.figure_canvas = FigureCanvas(self, -1, self.figure)
# Note that event is a MplEvent
self.figure_canvas.mpl_connect('motion_notify_event', self.UpdateStatusBar)
self.figure_canvas.Bind(wx.EVT_ENTER_WINDOW, self.ChangeCursor)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.figure_canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
self.SetSizer(self.sizer)
self.Fit()
self.statusBar = wx.StatusBar(self, -1)
self.SetStatusBar(self.statusBar)
self.toolbar = NavigationToolbar2Wx(self.figure_canvas)
self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
self.toolbar.Show()
def ChangeCursor(self, event):
self.figure_canvas.SetCursor(wxc.StockCursor(wx.CURSOR_BULLSEYE))
def UpdateStatusBar(self, event):
if event.inaxes:
x, y = event.xdata, event.ydata
self.statusBar.SetStatusText(("x= " + str(x) +
" y=" + str(y)),
0)
class App(wx.App):
def OnInit(self):
'Create the main window and insert the custom frame'
frame = CanvasFrame()
self.SetTopWindow(frame)
frame.Show(True)
return True
if __name__ == '__main__':
app = App(0)
app.MainLoop()
0707010001fb35000081a400001782000005de000000015689ead200000d2f000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/user_interfaces/embedding_in_wx4.py #!/usr/bin/env python
"""
An example of how to use wx or wxagg in an application with a custom
toolbar
"""
# matplotlib requires wxPython 2.8+
# set the wxPython version in lib\site-packages\wx.pth file
# or if you have wxversion installed un-comment the lines below
#import wxversion
#wxversion.ensureMinimal('2.8')
from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg
from matplotlib.backends.backend_wx import _load_bitmap
from matplotlib.figure import Figure
from numpy.random import rand
import wx
class MyNavigationToolbar(NavigationToolbar2WxAgg):
"""
Extend the default wx toolbar with your own event handlers
"""
ON_CUSTOM = wx.NewId()
def __init__(self, canvas, cankill):
NavigationToolbar2WxAgg.__init__(self, canvas)
# for simplicity I'm going to reuse a bitmap from wx, you'll
# probably want to add your own.
if 'phoenix' in wx.PlatformInfo:
self.AddTool(self.ON_CUSTOM, 'Click me',
_load_bitmap('stock_left.xpm'),
'Activate custom contol')
self.Bind(wx.EVT_TOOL, self._on_custom, id=self.ON_CUSTOM)
else:
self.AddSimpleTool(self.ON_CUSTOM, _load_bitmap('stock_left.xpm'),
'Click me', 'Activate custom contol')
self.Bind(wx.EVT_TOOL, self._on_custom, id=self.ON_CUSTOM)
def _on_custom(self, evt):
# add some text to the axes in a random location in axes (0,1)
# coords) with a random color
# get the axes
ax = self.canvas.figure.axes[0]
# generate a random location can color
x, y = tuple(rand(2))
rgb = tuple(rand(3))
# add the text and draw
ax.text(x, y, 'You clicked me',
transform=ax.transAxes,
color=rgb)
self.canvas.draw()
evt.Skip()
class CanvasFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1,
'CanvasFrame', size=(550, 350))
self.figure = Figure(figsize=(5, 4), dpi=100)
self.axes = self.figure.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2 * pi * t)
self.axes.plot(t, s)
self.canvas = FigureCanvas(self, -1, self.figure)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
# Capture the paint message
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.toolbar = MyNavigationToolbar(self.canvas, True)
self.toolbar.Realize()
# By adding toolbar in sizer, we are able to put it at the bottom
# of the frame - so appearance is closer to GTK version.
self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
# update the axes menu on the toolbar
self.toolbar.update()
self.SetSizer(self.sizer)
self.Fit()
def OnPaint(self, event):
self.canvas.draw()
event.Skip()
class App(wx.App):
def OnInit(self):
'Create the main window and insert the custom frame'
frame = CanvasFrame()
frame.Show(True)
return True
app = App(0)
app.MainLoop()
0707010001fb36000081a400001782000005de000000015689ead2000007b5000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/user_interfaces/embedding_in_wx5.py #!/usr/bin/env python
# matplotlib requires wxPython 2.8+
# set the wxPython version in lib\site-packages\wx.pth file
# or if you have wxversion installed un-comment the lines below
#import wxversion
#wxversion.ensureMinimal('2.8')
import wx
import wx.lib.mixins.inspection as wit
if 'phoenix' in wx.PlatformInfo:
import wx.lib.agw.aui as aui
else:
import wx.aui as aui
import matplotlib as mpl
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as Canvas
from matplotlib.backends.backend_wxagg import NavigationToolbar2Wx as Toolbar
class Plot(wx.Panel):
def __init__(self, parent, id=-1, dpi=None, **kwargs):
wx.Panel.__init__(self, parent, id=id, **kwargs)
self.figure = mpl.figure.Figure(dpi=dpi, figsize=(2, 2))
self.canvas = Canvas(self, -1, self.figure)
self.toolbar = Toolbar(self.canvas)
self.toolbar.Realize()
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas, 1, wx.EXPAND)
sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
self.SetSizer(sizer)
class PlotNotebook(wx.Panel):
def __init__(self, parent, id=-1):
wx.Panel.__init__(self, parent, id=id)
self.nb = aui.AuiNotebook(self)
sizer = wx.BoxSizer()
sizer.Add(self.nb, 1, wx.EXPAND)
self.SetSizer(sizer)
def add(self, name="plot"):
page = Plot(self.nb)
self.nb.AddPage(page, name)
return page.figure
def demo():
# alternatively you could use
#app = wx.App()
# InspectableApp is a great debug tool, see:
# http://wiki.wxpython.org/Widget%20Inspection%20Tool
app = wit.InspectableApp()
frame = wx.Frame(None, -1, 'Plotter')
plotter = PlotNotebook(frame)
axes1 = plotter.add('figure 1').gca()
axes1.plot([1, 2, 3], [2, 1, 4])
axes2 = plotter.add('figure 2').gca()
axes2.plot([1, 2, 3, 4, 5], [2, 1, 4, 2, 3])
frame.Show()
app.MainLoop()
if __name__ == "__main__":
demo()
0707010001fb2c000081a400001782000005de000000015689ead200000375000002600000050a00000000000000000000004700000000reloc/matplotlib/examples/user_interfaces/embedding_in_gtk3_panzoom.py #!/usr/bin/env python
"""
demonstrate NavigationToolbar with GTK3 accessed via pygobject
"""
from gi.repository import Gtk
from matplotlib.figure import Figure
from numpy import arange, sin, pi
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3 as NavigationToolbar
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_default_size(400, 300)
win.set_title("Embedding in GTK")
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(1, 1, 1)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
a.plot(t, s)
vbox = Gtk.VBox()
win.add(vbox)
# Add canvas to vbox
canvas = FigureCanvas(f) # a Gtk.DrawingArea
vbox.pack_start(canvas, True, True, 0)
# Create toolbar
toolbar = NavigationToolbar(canvas, win)
vbox.pack_start(toolbar, False, False, 0)
win.show_all()
Gtk.main()
0707010001fb29000081a400001782000005de000000015689ead200000344000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/user_interfaces/embedding_in_gtk.py #!/usr/bin/env python
"""
show how to add a matplotlib FigureCanvasGTK or FigureCanvasGTKAgg widget to a
gtk.Window
"""
import gtk
from matplotlib.figure import Figure
from numpy import arange, sin, pi
# uncomment to select /GTK/GTKAgg/GTKCairo
#from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
#from matplotlib.backends.backend_gtkcairo import FigureCanvasGTKCairo as FigureCanvas
win = gtk.Window()
win.connect("destroy", lambda x: gtk.main_quit())
win.set_default_size(400, 300)
win.set_title("Embedding in GTK")
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
a.plot(t, s)
canvas = FigureCanvas(f) # a gtk.DrawingArea
win.add(canvas)
win.show_all()
gtk.main()
0707010001fb41000081a400001782000005de000000015689ead20000035a000002600000050a00000000000000000000004300000000reloc/matplotlib/examples/user_interfaces/mpl_with_glade_316.glade
0707010001fb37000081a400001782000005de000000015689ead200001ffe000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/user_interfaces/embedding_webagg.py """
This example demonstrates how to embed matplotlib WebAgg interactive
plotting in your own web application and framework. It is not
necessary to do all this if you merely want to display a plot in a
browser or use matplotlib's built-in Tornado-based server "on the
side".
The framework being used must support web sockets.
"""
import io
try:
import tornado
except ImportError:
raise RuntimeError("This example requires tornado.")
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.websocket
from matplotlib.backends.backend_webagg_core import (
FigureManagerWebAgg, new_figure_manager_given_figure)
from matplotlib.figure import Figure
import numpy as np
import json
def create_figure():
"""
Creates a simple example figure.
"""
fig = Figure()
a = fig.add_subplot(111)
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2 * np.pi * t)
a.plot(t, s)
return fig
# The following is the content of the web page. You would normally
# generate this using some sort of template facility in your web
# framework, but here we just use Python string formatting.
html_content = """
matplotlib
"""
class MyApplication(tornado.web.Application):
class MainPage(tornado.web.RequestHandler):
"""
Serves the main HTML page.
"""
def get(self):
manager = self.application.manager
ws_uri = "ws://{req.host}/".format(req=self.request)
content = html_content % {
"ws_uri": ws_uri, "fig_id": manager.num}
self.write(content)
class MplJs(tornado.web.RequestHandler):
"""
Serves the generated matplotlib javascript file. The content
is dynamically generated based on which toolbar functions the
user has defined. Call `FigureManagerWebAgg` to get its
content.
"""
def get(self):
self.set_header('Content-Type', 'application/javascript')
js_content = FigureManagerWebAgg.get_javascript()
self.write(js_content)
class Download(tornado.web.RequestHandler):
"""
Handles downloading of the figure in various file formats.
"""
def get(self, fmt):
manager = self.application.manager
mimetypes = {
'ps': 'application/postscript',
'eps': 'application/postscript',
'pdf': 'application/pdf',
'svg': 'image/svg+xml',
'png': 'image/png',
'jpeg': 'image/jpeg',
'tif': 'image/tiff',
'emf': 'application/emf'
}
self.set_header('Content-Type', mimetypes.get(fmt, 'binary'))
buff = io.BytesIO()
manager.canvas.print_figure(buff, format=fmt)
self.write(buff.getvalue())
class WebSocket(tornado.websocket.WebSocketHandler):
"""
A websocket for interactive communication between the plot in
the browser and the server.
In addition to the methods required by tornado, it is required to
have two callback methods:
- ``send_json(json_content)`` is called by matplotlib when
it needs to send json to the browser. `json_content` is
a JSON tree (Python dictionary), and it is the responsibility
of this implementation to encode it as a string to send over
the socket.
- ``send_binary(blob)`` is called to send binary image data
to the browser.
"""
supports_binary = True
def open(self):
# Register the websocket with the FigureManager.
manager = self.application.manager
manager.add_web_socket(self)
if hasattr(self, 'set_nodelay'):
self.set_nodelay(True)
def on_close(self):
# When the socket is closed, deregister the websocket with
# the FigureManager.
manager = self.application.manager
manager.remove_web_socket(self)
def on_message(self, message):
# The 'supports_binary' message is relevant to the
# websocket itself. The other messages get passed along
# to matplotlib as-is.
# Every message has a "type" and a "figure_id".
message = json.loads(message)
if message['type'] == 'supports_binary':
self.supports_binary = message['value']
else:
manager = self.application.manager
manager.handle_json(message)
def send_json(self, content):
self.write_message(json.dumps(content))
def send_binary(self, blob):
if self.supports_binary:
self.write_message(blob, binary=True)
else:
data_uri = "data:image/png;base64,{0}".format(
blob.encode('base64').replace('\n', ''))
self.write_message(data_uri)
def __init__(self, figure):
self.figure = figure
self.manager = new_figure_manager_given_figure(
id(figure), figure)
super(MyApplication, self).__init__([
# Static files for the CSS and JS
(r'/_static/(.*)',
tornado.web.StaticFileHandler,
{'path': FigureManagerWebAgg.get_static_file_path()}),
# The page that contains all of the pieces
('/', self.MainPage),
('/mpl.js', self.MplJs),
# Sends images and events to the browser, and receives
# events from the browser
('/ws', self.WebSocket),
# Handles the downloading (i.e., saving) of static images
(r'/download.([a-z0-9.]+)', self.Download),
])
if __name__ == "__main__":
figure = create_figure()
application = MyApplication(figure)
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8080)
print("http://127.0.0.1:8080/")
print("Press Ctrl+C to quit")
tornado.ioloop.IOLoop.instance().start()
0707010001fb2e000081a400001782000005de000000015689e239000008b1000002600000050a00000000000000000000004700000000reloc/matplotlib/examples/user_interfaces/embedding_in_qt4_wtoolbar.py from __future__ import print_function
import sys
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backend_bases import key_press_handler
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)
from matplotlib.backends import qt4_compat
use_pyside = qt4_compat.QT_API == qt4_compat.QT_API_PYSIDE
if use_pyside:
from PySide.QtCore import *
from PySide.QtGui import *
else:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class AppForm(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
#self.x, self.y = self.get_data()
self.data = self.get_data2()
self.create_main_frame()
self.on_draw()
def create_main_frame(self):
self.main_frame = QWidget()
self.fig = Figure((5.0, 4.0), dpi=100)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.canvas.setFocusPolicy(Qt.StrongFocus)
self.canvas.setFocus()
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
self.canvas.mpl_connect('key_press_event', self.on_key_press)
vbox = QVBoxLayout()
vbox.addWidget(self.canvas) # the matplotlib canvas
vbox.addWidget(self.mpl_toolbar)
self.main_frame.setLayout(vbox)
self.setCentralWidget(self.main_frame)
def get_data2(self):
return np.arange(20).reshape([4, 5]).copy()
def on_draw(self):
self.fig.clear()
self.axes = self.fig.add_subplot(111)
#self.axes.plot(self.x, self.y, 'ro')
self.axes.imshow(self.data, interpolation='nearest')
#self.axes.plot([1,2,3])
self.canvas.draw()
def on_key_press(self, event):
print('you pressed', event.key)
# implement the default mpl key press events described at
# http://matplotlib.org/users/navigation_toolbar.html#navigation-keyboard-shortcuts
key_press_handler(event, self.canvas, self.mpl_toolbar)
def main():
app = QApplication(sys.argv)
form = AppForm()
form.show()
app.exec_()
if __name__ == "__main__":
main()
0707010001fb3d000081a400001782000005de000000015689ead200000202000002600000050a00000000000000000000004200000000reloc/matplotlib/examples/user_interfaces/lineprops_dialog_gtk.py import matplotlib
matplotlib.use('GTKAgg')
from matplotlib.backends.backend_gtk import DialogLineprops
import numpy as np
import matplotlib.pyplot as plt
def f(t):
s1 = np.cos(2*np.pi*t)
e1 = np.exp(-t)
return np.multiply(s1, e1)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
t3 = np.arange(0.0, 2.0, 0.01)
fig, ax = plt.subplots()
l1, = ax.plot(t1, f(t1), 'bo', label='line 1')
l2, = ax.plot(t2, f(t2), 'k--', label='line 2')
dlg = DialogLineprops([l1, l2])
dlg.show()
plt.show()
0707010001fb46000081ed00001782000005de0000000156931c20000011cb000002600000050a00000000000000000000003b00000000reloc/matplotlib/examples/user_interfaces/svg_histogram.py #!/usr/bin/env python
#-*- encoding:utf-8 -*-
"""
Demonstrate how to create an interactive histogram, in which bars
are hidden or shown by cliking on legend markers.
The interactivity is encoded in ecmascript (javascript) and inserted in
the SVG code in a post-processing step. To render the image, open it in
a web browser. SVG is supported in most web browsers used by Linux and
OSX users. Windows IE9 supports SVG, but earlier versions do not.
Notes
-----
The matplotlib backend lets us assign ids to each object. This is the
mechanism used here to relate matplotlib objects created in python and
the corresponding SVG constructs that are parsed in the second step.
While flexible, ids are cumbersome to use for large collection of
objects. Two mechanisms could be used to simplify things:
* systematic grouping of objects into SVG tags,
* assingning classes to each SVG object according to its origin.
For example, instead of modifying the properties of each individual bar,
the bars from the `hist` function could either be grouped in
a PatchCollection, or be assigned a class="hist_##" attribute.
CSS could also be used more extensively to replace repetitive markup
troughout the generated SVG.
__author__="david.huard@gmail.com"
"""
import numpy as np
import matplotlib.pyplot as plt
import xml.etree.ElementTree as ET
from io import StringIO
import json
plt.rcParams['svg.embed_char_paths'] = 'none'
# Apparently, this `register_namespace` method works only with
# python 2.7 and up and is necessary to avoid garbling the XML name
# space with ns0.
ET.register_namespace("", "http://www.w3.org/2000/svg")
# --- Create histogram, legend and title ---
plt.figure()
r = np.random.randn(100)
r1 = r + 1
labels = ['Rabbits', 'Frogs']
H = plt.hist([r, r1], label=labels)
containers = H[-1]
leg = plt.legend(frameon=False)
plt.title("From a web browser, click on the legend\n"
"marker to toggle the corresponding histogram.")
# --- Add ids to the svg objects we'll modify
hist_patches = {}
for ic, c in enumerate(containers):
hist_patches['hist_%d' % ic] = []
for il, element in enumerate(c):
element.set_gid('hist_%d_patch_%d' % (ic, il))
hist_patches['hist_%d' % ic].append('hist_%d_patch_%d' % (ic, il))
# Set ids for the legend patches
for i, t in enumerate(leg.get_patches()):
t.set_gid('leg_patch_%d' % i)
# Set ids for the text patches
for i, t in enumerate(leg.get_texts()):
t.set_gid('leg_text_%d' % i)
# Save SVG in a fake file object.
f = StringIO()
plt.savefig(f, format="svg")
# Create XML tree from the SVG file.
tree, xmlid = ET.XMLID(f.getvalue())
# --- Add interactivity ---
# Add attributes to the patch objects.
for i, t in enumerate(leg.get_patches()):
el = xmlid['leg_patch_%d' % i]
el.set('cursor', 'pointer')
el.set('onclick', "toggle_hist(this)")
# Add attributes to the text objects.
for i, t in enumerate(leg.get_texts()):
el = xmlid['leg_text_%d' % i]
el.set('cursor', 'pointer')
el.set('onclick', "toggle_hist(this)")
# Create script defining the function `toggle_hist`.
# We create a global variable `container` that stores the patches id
# belonging to each histogram. Then a function "toggle_element" sets the
# visibility attribute of all patches of each histogram and the opacity
# of the marker itself.
script = """
""" % json.dumps(hist_patches)
# Add a transition effect
css = tree.getchildren()[0][0]
css.text = css.text + "g {-webkit-transition:opacity 0.4s ease-out;" + \
"-moz-transition:opacity 0.4s ease-out;}"
# Insert the script and save to file.
tree.insert(0, ET.XML(script))
ET.ElementTree(tree).write("svg_histogram.svg")
0707010001fb2b000081ed00001782000005de000000015689ead200000343000002600000050a00000000000000000000003f00000000reloc/matplotlib/examples/user_interfaces/embedding_in_gtk3.py #!/usr/bin/env python
"""
demonstrate adding a FigureCanvasGTK3Agg widget to a Gtk.ScrolledWindow
using GTK3 accessed via pygobject
"""
from gi.repository import Gtk
from matplotlib.figure import Figure
from numpy import arange, sin, pi
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_default_size(400, 300)
win.set_title("Embedding in GTK")
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
a.plot(t, s)
sw = Gtk.ScrolledWindow()
win.add(sw)
# A scrolled window border goes outside the scrollbars and viewport
sw.set_border_width(10)
canvas = FigureCanvas(f) # a Gtk.DrawingArea
canvas.set_size_request(800, 600)
sw.add_with_viewport(canvas)
win.show_all()
Gtk.main()
0707010001fb2a000081a400001782000005de000000015689ead2000005b3000002600000050a00000000000000000000003f00000000reloc/matplotlib/examples/user_interfaces/embedding_in_gtk2.py #!/usr/bin/env python
"""
show how to add a matplotlib FigureCanvasGTK or FigureCanvasGTKAgg widget and
a toolbar to a gtk.Window
"""
import gtk
from matplotlib.figure import Figure
from numpy import arange, sin, pi
# uncomment to select /GTK/GTKAgg/GTKCairo
#from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
#from matplotlib.backends.backend_gtkcairo import FigureCanvasGTKCairo as FigureCanvas
# or NavigationToolbar for classic
#from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar
from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar
# implement the default mpl key bindings
from matplotlib.backend_bases import key_press_handler
win = gtk.Window()
win.connect("destroy", lambda x: gtk.main_quit())
win.set_default_size(400, 300)
win.set_title("Embedding in GTK")
vbox = gtk.VBox()
win.add(vbox)
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
ax.plot(t, s)
canvas = FigureCanvas(fig) # a gtk.DrawingArea
vbox.pack_start(canvas)
toolbar = NavigationToolbar(canvas, win)
vbox.pack_start(toolbar, False, False)
def on_key_event(event):
print('you pressed %s' % event.key)
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect('key_press_event', on_key_event)
win.show_all()
gtk.main()
0707010001fb42000081a400001782000005de000000015689ead20000044e000002600000050a00000000000000000000004000000000reloc/matplotlib/examples/user_interfaces/mpl_with_glade_316.py #!/usr/bin/env python3
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.axes import Subplot
from numpy import arange, sin, pi
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
class Window1Signals(object):
def on_window1_destroy(self, widget):
Gtk.main_quit()
def main():
builder = Gtk.Builder()
builder.add_objects_from_file("mpl_with_glade_316.glade", ("window1", ""))
builder.connect_signals(Window1Signals())
window = builder.get_object("window1")
sw = builder.get_object("scrolledwindow1")
# Start of Matplotlib specific code
figure = Figure(figsize=(8, 6), dpi=71)
axis = figure.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
axis.plot(t, s)
axis.set_xlabel('time [s]')
axis.set_ylabel('voltage [V]')
canvas = FigureCanvas(figure) # a Gtk.DrawingArea
canvas.set_size_request(800, 600)
sw.add_with_viewport(canvas)
# End of Matplotlib specific code
window.show_all()
Gtk.main()
if __name__ == "__main__":
main()
0707010001fb30000081ed00001782000005de000000015689ead20000058f000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/user_interfaces/embedding_in_tk.py #!/usr/bin/env python
import matplotlib
matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
# implement the default mpl key bindings
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import sys
if sys.version_info[0] < 3:
import Tkinter as Tk
else:
import tkinter as Tk
root = Tk.Tk()
root.wm_title("Embedding in TK")
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
a.plot(t, s)
# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
def on_key_event(event):
print('you pressed %s' % event.key)
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect('key_press_event', on_key_event)
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = Tk.Button(master=root, text='Quit', command=_quit)
button.pack(side=Tk.BOTTOM)
Tk.mainloop()
# If you put root.destroy() here, it will cause an error if
# the window is closed with the window manager.
0707010001fb3c000081ed00001782000005de000000015689ead200002ce2000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/user_interfaces/interactive2.py #!/usr/bin/env python
from __future__ import print_function
# GTK Interactive Console
# (C) 2003, Jon Anderson
# See www.python.org/2.2/license.html for
# license details.
#
import gtk
import gtk.gdk
import code
import os
import sys
import pango
import __builtin__
import __main__
banner = """GTK Interactive Python Console
Thanks to Jon Anderson
%s
""" % sys.version
banner += """
Welcome to matplotlib.
help(matplotlib) -- some general information about matplotlib
help(plotting) -- shows a list of plot specific commands
"""
class Completer(object):
"""
Taken from rlcompleter, with readline references stripped, and a local dictionary to use.
"""
def __init__(self, locals):
self.locals = locals
def complete(self, text, state):
"""Return the next possible completion for 'text'.
This is called successively with state == 0, 1, 2, ... until it
returns None. The completion should begin with 'text'.
"""
if state == 0:
if "." in text:
self.matches = self.attr_matches(text)
else:
self.matches = self.global_matches(text)
try:
return self.matches[state]
except IndexError:
return None
def global_matches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names
currently defines in __main__ that match.
"""
import keyword
matches = []
n = len(text)
for list in [keyword.kwlist, __builtin__.__dict__.keys(), __main__.__dict__.keys(), self.locals.keys()]:
for word in list:
if word[:n] == text and word != "__builtins__":
matches.append(word)
return matches
def attr_matches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in the globals of __main__, it will be evaluated
and its attributes (as revealed by dir()) are used as possible
completions. (For class instances, class members are are also
considered.)
WARNING: this can still invoke arbitrary C code, if an object
with a __getattr__ hook is evaluated.
"""
import re
m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
if not m:
return
expr, attr = m.group(1, 3)
object = eval(expr, __main__.__dict__, self.locals)
words = dir(object)
if hasattr(object, '__class__'):
words.append('__class__')
words = words + get_class_members(object.__class__)
matches = []
n = len(attr)
for word in words:
if word[:n] == attr and word != "__builtins__":
matches.append("%s.%s" % (expr, word))
return matches
def get_class_members(klass):
ret = dir(klass)
if hasattr(klass, '__bases__'):
for base in klass.__bases__:
ret = ret + get_class_members(base)
return ret
class OutputStream(object):
"""
A Multiplexing output stream.
It can replace another stream, and tee output to the original stream and too
a GTK textview.
"""
def __init__(self, view, old_out, style):
self.view = view
self.buffer = view.get_buffer()
self.mark = self.buffer.create_mark("End", self.buffer.get_end_iter(), False)
self.out = old_out
self.style = style
self.tee = 1
def write(self, text):
if self.tee:
self.out.write(text)
end = self.buffer.get_end_iter()
if self.view is not None:
self.view.scroll_to_mark(self.mark, 0, True, 1, 1)
self.buffer.insert_with_tags(end, text, self.style)
class GTKInterpreterConsole(gtk.ScrolledWindow):
"""
An InteractiveConsole for GTK. It's an actual widget,
so it can be dropped in just about anywhere.
"""
def __init__(self):
gtk.ScrolledWindow.__init__(self)
self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.text = gtk.TextView()
self.text.set_wrap_mode(True)
self.interpreter = code.InteractiveInterpreter()
self.completer = Completer(self.interpreter.locals)
self.buffer = []
self.history = []
self.banner = banner
self.ps1 = ">>> "
self.ps2 = "... "
self.text.add_events(gtk.gdk.KEY_PRESS_MASK)
self.text.connect("key_press_event", self.key_pressed)
self.current_history = -1
self.mark = self.text.get_buffer().create_mark("End", self.text.get_buffer().get_end_iter(), False)
# setup colors
self.style_banner = gtk.TextTag("banner")
self.style_banner.set_property("foreground", "saddle brown")
self.style_ps1 = gtk.TextTag("ps1")
self.style_ps1.set_property("foreground", "DarkOrchid4")
self.style_ps1.set_property("editable", False)
self.style_ps1.set_property("font", "courier")
self.style_ps2 = gtk.TextTag("ps2")
self.style_ps2.set_property("foreground", "DarkOliveGreen")
self.style_ps2.set_property("editable", False)
self.style_ps2.set_property("font", "courier")
self.style_out = gtk.TextTag("stdout")
self.style_out.set_property("foreground", "midnight blue")
self.style_err = gtk.TextTag("stderr")
self.style_err.set_property("style", pango.STYLE_ITALIC)
self.style_err.set_property("foreground", "red")
self.text.get_buffer().get_tag_table().add(self.style_banner)
self.text.get_buffer().get_tag_table().add(self.style_ps1)
self.text.get_buffer().get_tag_table().add(self.style_ps2)
self.text.get_buffer().get_tag_table().add(self.style_out)
self.text.get_buffer().get_tag_table().add(self.style_err)
self.stdout = OutputStream(self.text, sys.stdout, self.style_out)
self.stderr = OutputStream(self.text, sys.stderr, self.style_err)
sys.stderr = self.stderr
sys.stdout = self.stdout
self.current_prompt = None
self.write_line(self.banner, self.style_banner)
self.prompt_ps1()
self.add(self.text)
self.text.show()
def reset_history(self):
self.history = []
def reset_buffer(self):
self.buffer = []
def prompt_ps1(self):
self.current_prompt = self.prompt_ps1
self.write_line(self.ps1, self.style_ps1)
def prompt_ps2(self):
self.current_prompt = self.prompt_ps2
self.write_line(self.ps2, self.style_ps2)
def write_line(self, text, style=None):
start, end = self.text.get_buffer().get_bounds()
if style is None:
self.text.get_buffer().insert(end, text)
else:
self.text.get_buffer().insert_with_tags(end, text, style)
self.text.scroll_to_mark(self.mark, 0, True, 1, 1)
def push(self, line):
self.buffer.append(line)
if len(line) > 0:
self.history.append(line)
source = "\n".join(self.buffer)
more = self.interpreter.runsource(source, "<>")
if not more:
self.reset_buffer()
return more
def key_pressed(self, widget, event):
if event.keyval == gtk.gdk.keyval_from_name('Return'):
return self.execute_line()
if event.keyval == gtk.gdk.keyval_from_name('Up'):
self.current_history = self.current_history - 1
if self.current_history < - len(self.history):
self.current_history = - len(self.history)
return self.show_history()
elif event.keyval == gtk.gdk.keyval_from_name('Down'):
self.current_history = self.current_history + 1
if self.current_history > 0:
self.current_history = 0
return self.show_history()
elif event.keyval == gtk.gdk.keyval_from_name('Home'):
l = self.text.get_buffer().get_line_count() - 1
start = self.text.get_buffer().get_iter_at_line_offset(l, 4)
self.text.get_buffer().place_cursor(start)
return True
elif event.keyval == gtk.gdk.keyval_from_name('space') and event.state & gtk.gdk.CONTROL_MASK:
return self.complete_line()
return False
def show_history(self):
if self.current_history == 0:
return True
else:
self.replace_line(self.history[self.current_history])
return True
def current_line(self):
start, end = self.current_line_bounds()
return self.text.get_buffer().get_text(start, end, True)
def current_line_bounds(self):
txt_buffer = self.text.get_buffer()
l = txt_buffer.get_line_count() - 1
start = txt_buffer.get_iter_at_line(l)
if start.get_chars_in_line() >= 4:
start.forward_chars(4)
end = txt_buffer.get_end_iter()
return start, end
def replace_line(self, txt):
start, end = self.current_line_bounds()
self.text.get_buffer().delete(start, end)
self.write_line(txt)
def execute_line(self, line=None):
if line is None:
line = self.current_line()
self.write_line("\n")
else:
self.write_line(line + "\n")
more = self.push(line)
self.text.get_buffer().place_cursor(self.text.get_buffer().get_end_iter())
if more:
self.prompt_ps2()
else:
self.prompt_ps1()
self.current_history = 0
self.window.raise_()
return True
def complete_line(self):
line = self.current_line()
tokens = line.split()
token = tokens[-1]
completions = []
p = self.completer.complete(token, len(completions))
while p is not None:
completions.append(p)
p = self.completer.complete(token, len(completions))
if len(completions) != 1:
self.write_line("\n")
self.write_line("\n".join(completions), self.style_ps1)
self.write_line("\n")
self.current_prompt()
self.write_line(line)
else:
i = line.rfind(token)
line = line[0:i] + completions[0]
self.replace_line(line)
return True
def main():
w = gtk.Window()
console = GTKInterpreterConsole()
console.set_size_request(640, 480)
w.add(console)
def destroy(arg=None):
gtk.main_quit()
def key_event(widget, event):
if gtk.gdk.keyval_name(event.keyval) == 'd' and \
event.state & gtk.gdk.CONTROL_MASK:
destroy()
return False
w.connect("destroy", destroy)
w.add_events(gtk.gdk.KEY_PRESS_MASK)
w.connect('key_press_event', key_event)
w.show_all()
console.execute_line('import matplotlib')
console.execute_line("matplotlib.use('GTKAgg')")
console.execute_line('matplotlib.interactive(1)')
console.execute_line('from pylab import *')
if len(sys.argv) > 1:
fname = sys.argv[1]
if not os.path.exists(fname):
print('%s does not exist' % fname)
for line in file(fname):
line = line.strip()
console.execute_line(line)
gtk.main()
if __name__ == '__main__':
main()
0707010001fb44000081a400001782000005de000000015689ead20000051e000002600000050a00000000000000000000004100000000reloc/matplotlib/examples/user_interfaces/rec_edit_gtk_custom.py """
generate an editable gtk treeview widget for record arrays with custom
formatting of the cells and show how to limit string entries to a list
of strings
"""
from __future__ import print_function
import gtk
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import mpl_toolkits.gtktools as gtktools
datafile = cbook.get_sample_data('demodata.csv', asfileobj=False)
r = mlab.csv2rec(datafile, converterd={'weekdays': str})
formatd = mlab.get_formatd(r)
formatd['date'] = mlab.FormatDate('%Y-%m-%d')
formatd['prices'] = mlab.FormatMillions(precision=1)
formatd['gain'] = mlab.FormatPercent(precision=2)
# use a drop down combo for weekdays
stringd = dict(weekdays=['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])
constant = ['clientid'] # block editing of this field
liststore = gtktools.RecListStore(r, formatd=formatd, stringd=stringd)
treeview = gtktools.RecTreeView(liststore, constant=constant)
def mycallback(liststore, rownum, colname, oldval, newval):
print('verify: old=%s, new=%s, rec=%s' % (oldval, newval, liststore.r[rownum][colname]))
liststore.callbacks.connect('cell_changed', mycallback)
win = gtk.Window()
win.set_title('click to edit')
win.add(treeview)
win.show_all()
win.connect('delete-event', lambda *args: gtk.main_quit())
gtk.main()
0707010001fb3a000081a400001782000005de000000015689ead200000570000002600000050a00000000000000000000004600000000reloc/matplotlib/examples/user_interfaces/histogram_demo_canvasagg.py #!/usr/bin/env python
"""
This is an example that shows you how to work directly with the agg
figure canvas to create a figure using the pythonic API.
In this example, the contents of the agg canvas are extracted to a
string, which can in turn be passed off to PIL or put in a numeric
array
"""
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
from matplotlib.mlab import normpdf
from numpy.random import randn
import numpy
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)
canvas = FigureCanvasAgg(fig)
mu, sigma = 100, 15
x = mu + sigma*randn(10000)
# the histogram of the data
n, bins, patches = ax.hist(x, 50, normed=1)
# add a 'best fit' line
y = normpdf(bins, mu, sigma)
line, = ax.plot(bins, y, 'r--')
line.set_linewidth(1)
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability')
ax.set_title(r'$\mathrm{Histogram of IQ: }\mu=100, \sigma=15$')
ax.set_xlim((40, 160))
ax.set_ylim((0, 0.03))
canvas.draw()
s = canvas.tostring_rgb() # save this and convert to bitmap as needed
# get the figure dimensions for creating bitmaps or numpy arrays,
# etc.
l, b, w, h = fig.bbox.bounds
w, h = int(w), int(h)
if 0:
# convert to a numpy array
X = numpy.fromstring(s, numpy.uint8)
X.shape = h, w, 3
if 0:
# pass off to PIL
from PIL import Image
im = Image.fromstring("RGB", (w, h), s)
im.show()
0707010001fb39000081a400001782000005de000000015689ead2000009a2000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/user_interfaces/gtk_spreadsheet.py #!/usr/bin/env python
"""
Example of embedding matplotlib in an application and interacting with
a treeview to store data. Double click on an entry to update plot
data
"""
import pygtk
pygtk.require('2.0')
import gtk
from gtk import gdk
import matplotlib
matplotlib.use('GTKAgg') # or 'GTK'
from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
from numpy.random import random
from matplotlib.figure import Figure
class DataManager(gtk.Window):
numRows, numCols = 20, 10
data = random((numRows, numCols))
def __init__(self):
gtk.Window.__init__(self)
self.set_default_size(600, 600)
self.connect('destroy', lambda win: gtk.main_quit())
self.set_title('GtkListStore demo')
self.set_border_width(8)
vbox = gtk.VBox(False, 8)
self.add(vbox)
label = gtk.Label('Double click a row to plot the data')
vbox.pack_start(label, False, False)
sw = gtk.ScrolledWindow()
sw.set_shadow_type(gtk.SHADOW_ETCHED_IN)
sw.set_policy(gtk.POLICY_NEVER,
gtk.POLICY_AUTOMATIC)
vbox.pack_start(sw, True, True)
model = self.create_model()
self.treeview = gtk.TreeView(model)
self.treeview.set_rules_hint(True)
# matplotlib stuff
fig = Figure(figsize=(6, 4))
self.canvas = FigureCanvas(fig) # a gtk.DrawingArea
vbox.pack_start(self.canvas, True, True)
ax = fig.add_subplot(111)
self.line, = ax.plot(self.data[0, :], 'go') # plot the first row
self.treeview.connect('row-activated', self.plot_row)
sw.add(self.treeview)
self.add_columns()
self.add_events(gdk.BUTTON_PRESS_MASK |
gdk.KEY_PRESS_MASK |
gdk.KEY_RELEASE_MASK)
def plot_row(self, treeview, path, view_column):
ind, = path # get the index into data
points = self.data[ind, :]
self.line.set_ydata(points)
self.canvas.draw()
def add_columns(self):
for i in range(self.numCols):
column = gtk.TreeViewColumn('%d' % i, gtk.CellRendererText(), text=i)
self.treeview.append_column(column)
def create_model(self):
types = [float]*self.numCols
store = gtk.ListStore(*types)
for row in self.data:
store.append(row)
return store
manager = DataManager()
manager.show_all()
gtk.main()
0707010001fb47000081a400001782000005de0000000156931c2000000d00000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/user_interfaces/svg_tooltip.py """
SVG tooltip example
===================
This example shows how to create a tooltip that will show up when
hovering over a matplotlib patch.
Although it is possible to create the tooltip from CSS or javascript,
here we create it in matplotlib and simply toggle its visibility on
when hovering over the patch. This approach provides total control over
the tooltip placement and appearance, at the expense of more code up
front.
The alternative approach would be to put the tooltip content in `title`
atttributes of SVG objects. Then, using an existing js/CSS library, it
would be relatively straightforward to create the tooltip in the
browser. The content would be dictated by the `title` attribute, and
the appearance by the CSS.
:author: David Huard
"""
import matplotlib.pyplot as plt
import xml.etree.ElementTree as ET
from io import StringIO
ET.register_namespace("", "http://www.w3.org/2000/svg")
fig, ax = plt.subplots()
# Create patches to which tooltips will be assigned.
circle = plt.Circle((0, 0), 5, fc='blue')
rect = plt.Rectangle((-5, 10), 10, 5, fc='green')
ax.add_patch(circle)
ax.add_patch(rect)
# Create the tooltips
circle_tip = ax.annotate(
'This is a blue circle.',
xy=(0, 0),
xytext=(30, -30),
textcoords='offset points',
color='w',
ha='left',
bbox=dict(boxstyle='round,pad=.5', fc=(.1, .1, .1, .92),
ec=(1., 1., 1.), lw=1, zorder=1))
rect_tip = ax.annotate(
'This is a green rectangle.',
xy=(-5, 10),
xytext=(30, 40),
textcoords='offset points',
color='w',
ha='left',
bbox=dict(boxstyle='round,pad=.5', fc=(.1, .1, .1, .92),
ec=(1., 1., 1.), lw=1, zorder=1))
# Set id for the patches
for i, t in enumerate(ax.patches):
t.set_gid('patch_%d' % i)
# Set id for the annotations
for i, t in enumerate(ax.texts):
t.set_gid('tooltip_%d' % i)
# Save the figure in a fake file object
ax.set_xlim(-30, 30)
ax.set_ylim(-30, 30)
ax.set_aspect('equal')
f = StringIO()
plt.savefig(f, format="svg")
# --- Add interactivity ---
# Create XML tree from the SVG file.
tree, xmlid = ET.XMLID(f.getvalue())
tree.set('onload', 'init(evt)')
# Hide the tooltips
for i, t in enumerate(ax.texts):
el = xmlid['tooltip_%d' % i]
el.set('visibility', 'hidden')
# Assign onmouseover and onmouseout callbacks to patches.
for i, t in enumerate(ax.patches):
el = xmlid['patch_%d' % i]
el.set('onmouseover', "ShowTooltip(this)")
el.set('onmouseout', "HideTooltip(this)")
# This is the script defining the ShowTooltip and HideTooltip functions.
script = """
"""
# Insert the script at the top of the file and save it.
tree.insert(0, ET.XML(script))
ET.ElementTree(tree).write('svg_tooltip.svg')
0707010001fb28000081a400001782000005de000000015574c1e000000335000002600000050a00000000000000000000003400000000reloc/matplotlib/examples/user_interfaces/README.wx You have a few different options available to you for embedding
matplotlib in a wxPython application
1. Embed one of the wxPython backend widgets (which subclass wx.Panel)
directly and draw plots on it using matplotlib's object-oriented
API. This approach is demonstrated by some of the examples
embedding_in_wx*.py
2. Embed the PlotPanel from Matt Newville's `MPlot' package and draw
plots on it using its plot() and oplot() methods.
http://cars9.uchicago.edu/~newville/Python/MPlot/
3. Embed the PlotPanel from Ken McIvor wxmpl module and draw plots on
it using the matplotlib's object-oriented API.
http://agni.phys.iit.edu/~kmcivor/wxmpl/
Each of these approachs has different benefits and drawbacks, so I
encourage you to evaluate each of them and select the one that best
meets your needs.
0707010001fb31000081a400001782000005de000000015689ead200000377000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/user_interfaces/embedding_in_tk2.py #!/usr/bin/env python
import matplotlib
matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import sys
if sys.version_info[0] < 3:
import Tkinter as Tk
else:
import tkinter as Tk
def destroy(e):
sys.exit()
root = Tk.Tk()
root.wm_title("Embedding in TK")
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
a.plot(t, s)
a.set_title('Tk embedding')
a.set_xlabel('X axis label')
a.set_ylabel('Y label')
# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
button = Tk.Button(master=root, text='Quit', command=sys.exit)
button.pack(side=Tk.BOTTOM)
Tk.mainloop()
0707010001fb32000081ed00001782000005de0000000156931c20000007fc000002600000050a00000000000000000000004400000000reloc/matplotlib/examples/user_interfaces/embedding_in_tk_canvas.py #!/usr/bin/env python
# -*- noplot -*-
import matplotlib as mpl
import numpy as np
import sys
if sys.version_info[0] < 3:
import Tkinter as tk
else:
import tkinter as tk
import matplotlib.backends.tkagg as tkagg
from matplotlib.backends.backend_agg import FigureCanvasAgg
def draw_figure(canvas, figure, loc=(0, 0)):
""" Draw a matplotlib figure onto a Tk canvas
loc: location of top-left corner of figure on canvas in pixels.
Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py
"""
figure_canvas_agg = FigureCanvasAgg(figure)
figure_canvas_agg.draw()
figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
figure_w, figure_h = int(figure_w), int(figure_h)
photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
# Position: convert from top-left anchor to center anchor
canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
# Unfortunatly, there's no accessor for the pointer to the native renderer
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
# Return a handle which contains a reference to the photo object
# which must be kept live or else the picture disappears
return photo
# Create a canvas
w, h = 300, 200
window = tk.Tk()
window.title("A figure in a canvas")
canvas = tk.Canvas(window, width=w, height=h)
canvas.pack()
# Generate some example data
X = np.linspace(0, 2.0*3.14, 50)
Y = np.sin(X)
# Create the figure we desire to add to an existing canvas
fig = mpl.figure.Figure(figsize=(2, 1))
ax = fig.add_axes([0, 0, 1, 1])
ax.plot(X, Y)
# Keep this handle alive, or else figure will disappear
fig_x, fig_y = 100, 100
fig_photo = draw_figure(canvas, fig, loc=(fig_x, fig_y))
fig_w, fig_h = fig_photo.width(), fig_photo.height()
# Add more elements to the canvas, potentially on top of the figure
canvas.create_line(200, 50, fig_x + fig_w / 2, fig_y + fig_h / 2)
canvas.create_text(200, 50, text="Zero-crossing", anchor="s")
# Let Tk take over
tk.mainloop()
0707010001fb3e000081a400001782000005de000000015689ead200000f2c000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/user_interfaces/mathtext_wx.py """
Demonstrates how to convert mathtext to a wx.Bitmap for display in various
controls on wxPython.
"""
import matplotlib
matplotlib.use("WxAgg")
from numpy import arange, sin, pi, cos, log
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx, wxc
from matplotlib.figure import Figure
import wx
IS_GTK = 'wxGTK' in wx.PlatformInfo
IS_WIN = 'wxMSW' in wx.PlatformInfo
############################################################
# This is where the "magic" happens.
from matplotlib.mathtext import MathTextParser
mathtext_parser = MathTextParser("Bitmap")
def mathtext_to_wxbitmap(s):
ftimage, depth = mathtext_parser.parse(s, 150)
return wxc.BitmapFromBuffer(
ftimage.get_width(), ftimage.get_height(),
ftimage.as_rgba_str())
############################################################
functions = [
(r'$\sin(2 \pi x)$', lambda x: sin(2*pi*x)),
(r'$\frac{4}{3}\pi x^3$', lambda x: (4.0/3.0)*pi*x**3),
(r'$\cos(2 \pi x)$', lambda x: cos(2*pi*x)),
(r'$\log(x)$', lambda x: log(x))
]
class CanvasFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title, size=(550, 350))
self.SetBackgroundColour(wxc.NamedColour("WHITE"))
self.figure = Figure()
self.axes = self.figure.add_subplot(111)
self.canvas = FigureCanvas(self, -1, self.figure)
self.change_plot(0)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.add_buttonbar()
self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
self.add_toolbar() # comment this out for no toolbar
menuBar = wx.MenuBar()
# File Menu
menu = wx.Menu()
menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")
menuBar.Append(menu, "&File")
if IS_GTK or IS_WIN:
# Equation Menu
menu = wx.Menu()
for i, (mt, func) in enumerate(functions):
bm = mathtext_to_wxbitmap(mt)
item = wx.MenuItem(menu, 1000 + i, " ")
item.SetBitmap(bm)
menu.AppendItem(item)
self.Bind(wx.EVT_MENU, self.OnChangePlot, item)
menuBar.Append(menu, "&Functions")
self.SetMenuBar(menuBar)
self.SetSizer(self.sizer)
self.Fit()
def add_buttonbar(self):
self.button_bar = wx.Panel(self)
self.button_bar_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.sizer.Add(self.button_bar, 0, wx.LEFT | wx.TOP | wx.GROW)
for i, (mt, func) in enumerate(functions):
bm = mathtext_to_wxbitmap(mt)
button = wx.BitmapButton(self.button_bar, 1000 + i, bm)
self.button_bar_sizer.Add(button, 1, wx.GROW)
self.Bind(wx.EVT_BUTTON, self.OnChangePlot, button)
self.button_bar.SetSizer(self.button_bar_sizer)
def add_toolbar(self):
"""Copied verbatim from embedding_wx2.py"""
self.toolbar = NavigationToolbar2Wx(self.canvas)
self.toolbar.Realize()
# By adding toolbar in sizer, we are able to put it at the bottom
# of the frame - so appearance is closer to GTK version.
self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
# update the axes menu on the toolbar
self.toolbar.update()
def OnChangePlot(self, event):
self.change_plot(event.GetId() - 1000)
def change_plot(self, plot_number):
t = arange(1.0, 3.0, 0.01)
s = functions[plot_number][1](t)
self.axes.clear()
self.axes.plot(t, s)
self.canvas.draw()
class MyApp(wx.App):
def OnInit(self):
frame = CanvasFrame(None, "wxPython mathtext demo app")
self.SetTopWindow(frame)
frame.Show(True)
return True
app = MyApp()
app.MainLoop()
0707010001fb1b000041ed00001782000005de00000002570a550000000000000002600000050a00000000000000000000002000000000reloc/matplotlib/examples/units 0707010001fb1f000081a400001782000005de000000015689ead200000351000002600000050a00000000000000000000003100000000reloc/matplotlib/examples/units/bar_unit_demo.py #!/usr/bin/env python
import numpy as np
from basic_units import cm, inch
import matplotlib.pyplot as plt
N = 5
menMeans = (150*cm, 160*cm, 146*cm, 172*cm, 155*cm)
menStd = (20*cm, 30*cm, 32*cm, 10*cm, 20*cm)
fig, ax = plt.subplots()
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
p1 = ax.bar(ind, menMeans, width, color='r', bottom=0*cm, yerr=menStd)
womenMeans = (145*cm, 149*cm, 172*cm, 165*cm, 200*cm)
womenStd = (30*cm, 25*cm, 20*cm, 31*cm, 22*cm)
p2 = ax.bar(ind + width, womenMeans, width, color='y', bottom=0*cm, yerr=womenStd)
ax.set_title('Scores by group and gender')
ax.set_xticks(ind + width)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend((p1[0], p2[0]), ('Men', 'Women'))
ax.yaxis.set_units(inch)
ax.autoscale_view()
#plt.savefig('barchart_demo')
plt.show()
0707010001fb20000081a400001782000005de000000015689ead200002b80000002600000050a00000000000000000000002f00000000reloc/matplotlib/examples/units/basic_units.py import math
import numpy as np
import matplotlib.units as units
import matplotlib.ticker as ticker
from matplotlib.axes import Axes
from matplotlib.cbook import iterable
class ProxyDelegate(object):
def __init__(self, fn_name, proxy_type):
self.proxy_type = proxy_type
self.fn_name = fn_name
def __get__(self, obj, objtype=None):
return self.proxy_type(self.fn_name, obj)
class TaggedValueMeta (type):
def __init__(cls, name, bases, dict):
for fn_name in cls._proxies.keys():
try:
dummy = getattr(cls, fn_name)
except AttributeError:
setattr(cls, fn_name,
ProxyDelegate(fn_name, cls._proxies[fn_name]))
class PassThroughProxy(object):
def __init__(self, fn_name, obj):
self.fn_name = fn_name
self.target = obj.proxy_target
def __call__(self, *args):
fn = getattr(self.target, self.fn_name)
ret = fn(*args)
return ret
class ConvertArgsProxy(PassThroughProxy):
def __init__(self, fn_name, obj):
PassThroughProxy.__init__(self, fn_name, obj)
self.unit = obj.unit
def __call__(self, *args):
converted_args = []
for a in args:
try:
converted_args.append(a.convert_to(self.unit))
except AttributeError:
converted_args.append(TaggedValue(a, self.unit))
converted_args = tuple([c.get_value() for c in converted_args])
return PassThroughProxy.__call__(self, *converted_args)
class ConvertReturnProxy(PassThroughProxy):
def __init__(self, fn_name, obj):
PassThroughProxy.__init__(self, fn_name, obj)
self.unit = obj.unit
def __call__(self, *args):
ret = PassThroughProxy.__call__(self, *args)
if (type(ret) == type(NotImplemented)):
return NotImplemented
return TaggedValue(ret, self.unit)
class ConvertAllProxy(PassThroughProxy):
def __init__(self, fn_name, obj):
PassThroughProxy.__init__(self, fn_name, obj)
self.unit = obj.unit
def __call__(self, *args):
converted_args = []
arg_units = [self.unit]
for a in args:
if hasattr(a, 'get_unit') and not hasattr(a, 'convert_to'):
# if this arg has a unit type but no conversion ability,
# this operation is prohibited
return NotImplemented
if hasattr(a, 'convert_to'):
try:
a = a.convert_to(self.unit)
except:
pass
arg_units.append(a.get_unit())
converted_args.append(a.get_value())
else:
converted_args.append(a)
if hasattr(a, 'get_unit'):
arg_units.append(a.get_unit())
else:
arg_units.append(None)
converted_args = tuple(converted_args)
ret = PassThroughProxy.__call__(self, *converted_args)
if (type(ret) == type(NotImplemented)):
return NotImplemented
ret_unit = unit_resolver(self.fn_name, arg_units)
if (ret_unit == NotImplemented):
return NotImplemented
return TaggedValue(ret, ret_unit)
class _TaggedValue(object):
_proxies = {'__add__': ConvertAllProxy,
'__sub__': ConvertAllProxy,
'__mul__': ConvertAllProxy,
'__rmul__': ConvertAllProxy,
'__cmp__': ConvertAllProxy,
'__lt__': ConvertAllProxy,
'__gt__': ConvertAllProxy,
'__len__': PassThroughProxy}
def __new__(cls, value, unit):
# generate a new subclass for value
value_class = type(value)
try:
subcls = type('TaggedValue_of_%s' % (value_class.__name__),
tuple([cls, value_class]),
{})
if subcls not in units.registry:
units.registry[subcls] = basicConverter
return object.__new__(subcls)
except TypeError:
if cls not in units.registry:
units.registry[cls] = basicConverter
return object.__new__(cls)
def __init__(self, value, unit):
self.value = value
self.unit = unit
self.proxy_target = self.value
def __getattribute__(self, name):
if (name.startswith('__')):
return object.__getattribute__(self, name)
variable = object.__getattribute__(self, 'value')
if (hasattr(variable, name) and name not in self.__class__.__dict__):
return getattr(variable, name)
return object.__getattribute__(self, name)
def __array__(self, t=None, context=None):
if t is not None:
return np.asarray(self.value).astype(t)
else:
return np.asarray(self.value, 'O')
def __array_wrap__(self, array, context):
return TaggedValue(array, self.unit)
def __repr__(self):
return 'TaggedValue(' + repr(self.value) + ', ' + repr(self.unit) + ')'
def __str__(self):
return str(self.value) + ' in ' + str(self.unit)
def __len__(self):
return len(self.value)
def __iter__(self):
class IteratorProxy(object):
def __init__(self, iter, unit):
self.iter = iter
self.unit = unit
def __next__(self):
value = next(self.iter)
return TaggedValue(value, self.unit)
next = __next__ # for Python 2
return IteratorProxy(iter(self.value), self.unit)
def get_compressed_copy(self, mask):
new_value = np.ma.masked_array(self.value, mask=mask).compressed()
return TaggedValue(new_value, self.unit)
def convert_to(self, unit):
if (unit == self.unit or not unit):
return self
new_value = self.unit.convert_value_to(self.value, unit)
return TaggedValue(new_value, unit)
def get_value(self):
return self.value
def get_unit(self):
return self.unit
TaggedValue = TaggedValueMeta('TaggedValue', (_TaggedValue, ), {})
class BasicUnit(object):
def __init__(self, name, fullname=None):
self.name = name
if fullname is None:
fullname = name
self.fullname = fullname
self.conversions = dict()
def __repr__(self):
return 'BasicUnit(%s)' % self.name
def __str__(self):
return self.fullname
def __call__(self, value):
return TaggedValue(value, self)
def __mul__(self, rhs):
value = rhs
unit = self
if hasattr(rhs, 'get_unit'):
value = rhs.get_value()
unit = rhs.get_unit()
unit = unit_resolver('__mul__', (self, unit))
if (unit == NotImplemented):
return NotImplemented
return TaggedValue(value, unit)
def __rmul__(self, lhs):
return self*lhs
def __array_wrap__(self, array, context):
return TaggedValue(array, self)
def __array__(self, t=None, context=None):
ret = np.array([1])
if t is not None:
return ret.astype(t)
else:
return ret
def add_conversion_factor(self, unit, factor):
def convert(x):
return x*factor
self.conversions[unit] = convert
def add_conversion_fn(self, unit, fn):
self.conversions[unit] = fn
def get_conversion_fn(self, unit):
return self.conversions[unit]
def convert_value_to(self, value, unit):
conversion_fn = self.conversions[unit]
ret = conversion_fn(value)
return ret
def get_unit(self):
return self
class UnitResolver(object):
def addition_rule(self, units):
for unit_1, unit_2 in zip(units[:-1], units[1:]):
if (unit_1 != unit_2):
return NotImplemented
return units[0]
def multiplication_rule(self, units):
non_null = [u for u in units if u]
if (len(non_null) > 1):
return NotImplemented
return non_null[0]
op_dict = {
'__mul__': multiplication_rule,
'__rmul__': multiplication_rule,
'__add__': addition_rule,
'__radd__': addition_rule,
'__sub__': addition_rule,
'__rsub__': addition_rule}
def __call__(self, operation, units):
if (operation not in self.op_dict):
return NotImplemented
return self.op_dict[operation](self, units)
unit_resolver = UnitResolver()
cm = BasicUnit('cm', 'centimeters')
inch = BasicUnit('inch', 'inches')
inch.add_conversion_factor(cm, 2.54)
cm.add_conversion_factor(inch, 1/2.54)
radians = BasicUnit('rad', 'radians')
degrees = BasicUnit('deg', 'degrees')
radians.add_conversion_factor(degrees, 180.0/np.pi)
degrees.add_conversion_factor(radians, np.pi/180.0)
secs = BasicUnit('s', 'seconds')
hertz = BasicUnit('Hz', 'Hertz')
minutes = BasicUnit('min', 'minutes')
secs.add_conversion_fn(hertz, lambda x: 1./x)
secs.add_conversion_factor(minutes, 1/60.0)
# radians formatting
def rad_fn(x, pos=None):
n = int((x / np.pi) * 2.0 + 0.25)
if n == 0:
return '0'
elif n == 1:
return r'$\pi/2$'
elif n == 2:
return r'$\pi$'
elif n % 2 == 0:
return r'$%s\pi$' % (n//2,)
else:
return r'$%s\pi/2$' % (n,)
class BasicUnitConverter(units.ConversionInterface):
@staticmethod
def axisinfo(unit, axis):
'return AxisInfo instance for x and unit'
if unit == radians:
return units.AxisInfo(
majloc=ticker.MultipleLocator(base=np.pi/2),
majfmt=ticker.FuncFormatter(rad_fn),
label=unit.fullname,
)
elif unit == degrees:
return units.AxisInfo(
majloc=ticker.AutoLocator(),
majfmt=ticker.FormatStrFormatter(r'$%i^\circ$'),
label=unit.fullname,
)
elif unit is not None:
if hasattr(unit, 'fullname'):
return units.AxisInfo(label=unit.fullname)
elif hasattr(unit, 'unit'):
return units.AxisInfo(label=unit.unit.fullname)
return None
@staticmethod
def convert(val, unit, axis):
if units.ConversionInterface.is_numlike(val):
return val
if iterable(val):
return [thisval.convert_to(unit).get_value() for thisval in val]
else:
return val.convert_to(unit).get_value()
@staticmethod
def default_units(x, axis):
'return the default unit for x or None'
if iterable(x):
for thisx in x:
return thisx.unit
return x.unit
def cos(x):
if iterable(x):
return [math.cos(val.convert_to(radians).get_value()) for val in x]
else:
return math.cos(x.convert_to(radians).get_value())
basicConverter = BasicUnitConverter()
units.registry[BasicUnit] = basicConverter
units.registry[TaggedValue] = basicConverter
0707010001fb21000081a400001782000005de000000015689ead20000072a000002600000050a00000000000000000000003600000000reloc/matplotlib/examples/units/ellipse_with_units.py """
Compare the ellipse generated with arcs versus a polygonal approximation
"""
from basic_units import cm
import numpy as np
from matplotlib import patches
import matplotlib.pyplot as plt
xcenter, ycenter = 0.38*cm, 0.52*cm
#xcenter, ycenter = 0., 0.
width, height = 1e-1*cm, 3e-1*cm
angle = -30
theta = np.arange(0.0, 360.0, 1.0)*np.pi/180.0
x = 0.5 * width * np.cos(theta)
y = 0.5 * height * np.sin(theta)
rtheta = np.radians(angle)
R = np.array([
[np.cos(rtheta), -np.sin(rtheta)],
[np.sin(rtheta), np.cos(rtheta)],
])
x, y = np.dot(R, np.array([x, y]))
x += xcenter
y += ycenter
fig = plt.figure()
ax = fig.add_subplot(211, aspect='auto')
ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow', linewidth=1, zorder=1)
e1 = patches.Ellipse((xcenter, ycenter), width, height,
angle=angle, linewidth=2, fill=False, zorder=2)
ax.add_patch(e1)
ax = fig.add_subplot(212, aspect='equal')
ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
e2 = patches.Ellipse((xcenter, ycenter), width, height,
angle=angle, linewidth=2, fill=False, zorder=2)
ax.add_patch(e2)
#fig.savefig('ellipse_compare.png')
fig.savefig('ellipse_compare')
fig = plt.figure()
ax = fig.add_subplot(211, aspect='auto')
ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow', linewidth=1, zorder=1)
e1 = patches.Arc((xcenter, ycenter), width, height,
angle=angle, linewidth=2, fill=False, zorder=2)
ax.add_patch(e1)
ax = fig.add_subplot(212, aspect='equal')
ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
e2 = patches.Arc((xcenter, ycenter), width, height,
angle=angle, linewidth=2, fill=False, zorder=2)
ax.add_patch(e2)
#fig.savefig('arc_compare.png')
fig.savefig('arc_compare')
plt.show()
0707010001fb1e000081a400001782000005de000000015689ead200000434000002600000050a00000000000000000000002d00000000reloc/matplotlib/examples/units/bar_demo2.py """
plot using a variety of cm vs inches conversions. The example shows
how default unit instrospection works (ax1), how various keywords can
be used to set the x and y units to override the defaults (ax2, ax3,
ax4) and how one can set the xlimits using scalars (ax3, current units
assumed) or units (conversions applied to get the numbers to current
units)
"""
import numpy as np
from basic_units import cm, inch
import matplotlib.pyplot as plt
cms = cm * np.arange(0, 10, 2)
bottom = 0*cm
width = 0.8*cm
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax1.bar(cms, cms, bottom=bottom)
ax2 = fig.add_subplot(2, 2, 2)
ax2.bar(cms, cms, bottom=bottom, width=width, xunits=cm, yunits=inch)
ax3 = fig.add_subplot(2, 2, 3)
ax3.bar(cms, cms, bottom=bottom, width=width, xunits=inch, yunits=cm)
ax3.set_xlim(2, 6) # scalars are interpreted in current units
ax4 = fig.add_subplot(2, 2, 4)
ax4.bar(cms, cms, bottom=bottom, width=width, xunits=inch, yunits=inch)
#fig.savefig('simple_conversion_plot.png')
ax4.set_xlim(2*cm, 6*cm) # cm are converted to inches
plt.show()
0707010001fb1d000081a400001782000005de000000015689ead2000005c2000002600000050a00000000000000000000003000000000reloc/matplotlib/examples/units/artist_tests.py """
Test unit support with each of the matplotlib primitive artist types
The axes handles unit conversions and the artists keep a pointer to
their axes parent, so you must init the artists with the axes instance
if you want to initialize them with unit data, or else they will not
know how to convert the units to scalars
"""
import random
import matplotlib.lines as lines
import matplotlib.patches as patches
import matplotlib.text as text
import matplotlib.collections as collections
from basic_units import cm, inch
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.xaxis.set_units(cm)
ax.yaxis.set_units(cm)
if 0:
# test a line collection
# Not supported at present.
verts = []
for i in range(10):
# a random line segment in inches
verts.append(zip(*inch*10*np.random.rand(2, random.randint(2, 15))))
lc = collections.LineCollection(verts, axes=ax)
ax.add_collection(lc)
# test a plain-ol-line
line = lines.Line2D([0*cm, 1.5*cm], [0*cm, 2.5*cm], lw=2, color='black', axes=ax)
ax.add_line(line)
if 0:
# test a patch
# Not supported at present.
rect = patches.Rectangle((1*cm, 1*cm), width=5*cm, height=2*cm, alpha=0.2, axes=ax)
ax.add_patch(rect)
t = text.Text(3*cm, 2.5*cm, 'text label', ha='left', va='bottom', axes=ax)
ax.add_artist(t)
ax.set_xlim(-1*cm, 10*cm)
ax.set_ylim(-1*cm, 10*cm)
#ax.xaxis.set_units(inch)
ax.grid(True)
ax.set_title("Artists with units")
plt.show()
0707010001fb24000081a400001782000005de000000015689ead2000003b4000002600000050a00000000000000000000003000000000reloc/matplotlib/examples/units/units_sample.py """
plot using a variety of cm vs inches conversions. The example shows
how default unit instrospection works (ax1), how various keywords can
be used to set the x and y units to override the defaults (ax2, ax3,
ax4) and how one can set the xlimits using scalars (ax3, current units
assumed) or units (conversions applied to get the numbers to current
units)
"""
from basic_units import cm, inch
import matplotlib.pyplot as plt
import numpy
cms = cm * numpy.arange(0, 10, 2)
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax1.plot(cms, cms)
ax2 = fig.add_subplot(2, 2, 2)
ax2.plot(cms, cms, xunits=cm, yunits=inch)
ax3 = fig.add_subplot(2, 2, 3)
ax3.plot(cms, cms, xunits=inch, yunits=cm)
ax3.set_xlim(3, 6) # scalars are interpreted in current units
ax4 = fig.add_subplot(2, 2, 4)
ax4.plot(cms, cms, xunits=inch, yunits=inch)
#fig.savefig('simple_conversion_plot.png')
ax4.set_xlim(3*cm, 6*cm) # cm are converted to inches
plt.show()
0707010001fb25000081a400001782000005de000000015689ead200000388000002600000050a00000000000000000000003100000000reloc/matplotlib/examples/units/units_scatter.py """
Demonstrate unit handling
basic_units is a mockup of a true units package used for testing
purposed, which illustrates the basic interface that a units package
must provide to matplotlib.
The example below shows support for unit conversions over masked
arrays.
"""
import numpy as np
from basic_units import secs, hertz, minutes
from matplotlib.pylab import figure, show
# create masked array
xsecs = secs*np.ma.MaskedArray((1, 2, 3, 4, 5, 6, 7, 8), (1, 0, 1, 0, 0, 0, 1, 0), np.float)
#xsecs = secs*np.arange(1,10.)
fig = figure()
ax1 = fig.add_subplot(3, 1, 1)
ax1.scatter(xsecs, xsecs)
#ax1.set_ylabel('seconds')
ax1.axis([0, 10, 0, 10])
ax2 = fig.add_subplot(3, 1, 2, sharex=ax1)
ax2.scatter(xsecs, xsecs, yunits=hertz)
ax2.axis([0, 10, 0, 1])
ax3 = fig.add_subplot(3, 1, 3, sharex=ax1)
ax3.scatter(xsecs, xsecs, yunits=hertz)
ax3.yaxis.set_units(minutes)
ax3.axis([0, 10, 0, 1])
show()
0707010001fb1c000081a400001782000005de000000015689ead2000002de000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/units/annotate_with_units.py import matplotlib.pyplot as plt
from basic_units import cm
fig, ax = plt.subplots()
ax.annotate("Note 01", [0.5*cm, 0.5*cm])
# xy and text both unitized
ax.annotate('local max', xy=(3*cm, 1*cm), xycoords='data',
xytext=(0.8*cm, 0.95*cm), textcoords='data',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='right', verticalalignment='top')
# mixing units w/ nonunits
ax.annotate('local max', xy=(3*cm, 1*cm), xycoords='data',
xytext=(0.8, 0.95), textcoords='axes fraction',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='right', verticalalignment='top')
ax.set_xlim(0*cm, 4*cm)
ax.set_ylim(0*cm, 4*cm)
plt.show()
0707010001fb23000081a400001782000005de0000000155f2504c00000212000002600000050a00000000000000000000002f00000000reloc/matplotlib/examples/units/radian_demo.py """
Plot with radians from the basic_units mockup example package
This example shows how the unit class can determine the tick locating,
formatting and axis labeling.
"""
import numpy as np
from basic_units import radians, degrees, cos
from matplotlib.pyplot import figure, show
x = [val*radians for val in np.arange(0, 15, 0.01)]
fig = figure()
fig.subplots_adjust(hspace=0.3)
ax = fig.add_subplot(211)
line1, = ax.plot(x, cos(x), xunits=radians)
ax = fig.add_subplot(212)
line2, = ax.plot(x, cos(x), xunits=degrees)
show()
0707010001fb22000081a400001782000005de000000015689ead200000923000002600000050a00000000000000000000002e00000000reloc/matplotlib/examples/units/evans_test.py """
A mockup "Foo" units class which supports
conversion and different tick formatting depending on the "unit".
Here the "unit" is just a scalar conversion factor, but this example shows mpl is
entirely agnostic to what kind of units client packages use
"""
from matplotlib.cbook import iterable
import matplotlib.units as units
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
class Foo(object):
def __init__(self, val, unit=1.0):
self.unit = unit
self._val = val * unit
def value(self, unit):
if unit is None:
unit = self.unit
return self._val / unit
class FooConverter(object):
@staticmethod
def axisinfo(unit, axis):
'return the Foo AxisInfo'
if unit == 1.0 or unit == 2.0:
return units.AxisInfo(
majloc=ticker.IndexLocator(8, 0),
majfmt=ticker.FormatStrFormatter("VAL: %s"),
label='foo',
)
else:
return None
@staticmethod
def convert(obj, unit, axis):
"""
convert obj using unit. If obj is a sequence, return the
converted sequence
"""
if units.ConversionInterface.is_numlike(obj):
return obj
if iterable(obj):
return [o.value(unit) for o in obj]
else:
return obj.value(unit)
@staticmethod
def default_units(x, axis):
'return the default unit for x or None'
if iterable(x):
for thisx in x:
return thisx.unit
else:
return x.unit
units.registry[Foo] = FooConverter()
# create some Foos
x = []
for val in range(0, 50, 2):
x.append(Foo(val, 1.0))
# and some arbitrary y data
y = [i for i in range(len(x))]
# plot specifying units
fig = plt.figure()
fig.suptitle("Custom units")
fig.subplots_adjust(bottom=0.2)
ax = fig.add_subplot(1, 2, 2)
ax.plot(x, y, 'o', xunits=2.0)
for label in ax.get_xticklabels():
label.set_rotation(30)
label.set_ha('right')
ax.set_title("xunits = 2.0")
# plot without specifying units; will use the None branch for axisinfo
ax = fig.add_subplot(1, 2, 1)
ax.plot(x, y) # uses default units
ax.set_title('default units')
for label in ax.get_xticklabels():
label.set_rotation(30)
label.set_ha('right')
plt.show()
0707010001faef000041ed00001782000005de00000002570a54ff00000000000002600000050a00000000000000000000002300000000reloc/matplotlib/examples/showcase 0707010001faf2000081a400001782000005de000000015689ead2000005b1000002600000050a00000000000000000000002b00000000reloc/matplotlib/examples/showcase/xkcd.py import matplotlib.pyplot as plt
import numpy as np
with plt.xkcd():
# Based on "Stove Ownership" from XKCD by Randall Monroe
# http://xkcd.com/418/
fig = plt.figure()
ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.xticks([])
plt.yticks([])
ax.set_ylim([-30, 10])
data = np.ones(100)
data[70:] -= np.arange(30)
plt.annotate(
'THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED',
xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))
plt.plot(data)
plt.xlabel('time')
plt.ylabel('my overall health')
fig.text(
0.5, 0.05,
'"Stove Ownership" from xkcd by Randall Monroe',
ha='center')
# Based on "The Data So Far" from XKCD by Randall Monroe
# http://xkcd.com/373/
fig = plt.figure()
ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
ax.bar([-0.125, 1.0 - 0.125], [0, 100], 0.25)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks([0, 1])
ax.set_xlim([-0.5, 1.5])
ax.set_ylim([0, 110])
ax.set_xticklabels(['CONFIRMED BY\nEXPERIMENT', 'REFUTED BY\nEXPERIMENT'])
plt.yticks([])
plt.title("CLAIMS OF SUPERNATURAL POWERS")
fig.text(
0.5, 0.05,
'"The Data So Far" from xkcd by Randall Monroe',
ha='center')
plt.show()
0707010001faf1000081a400001782000005de000000015689ead200000512000002600000050a00000000000000000000003400000000reloc/matplotlib/examples/showcase/integral_demo.py """
Plot demonstrating the integral as the area under a curve.
Although this is a simple example, it demonstrates some important tweaks:
* A simple line plot with custom color and line width.
* A shaded region created using a Polygon patch.
* A text label with mathtext rendering.
* figtext calls to label the x- and y-axes.
* Use of axis spines to hide the top and right spines.
* Custom tick placement and labels.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def func(x):
return (x - 3) * (x - 5) * (x - 7) + 85
a, b = 2, 9 # integral limits
x = np.linspace(0, 10)
y = func(x)
fig, ax = plt.subplots()
plt.plot(x, y, 'r', linewidth=2)
plt.ylim(ymin=0)
# Make the shaded region
ix = np.linspace(a, b)
iy = func(ix)
verts = [(a, 0)] + list(zip(ix, iy)) + [(b, 0)]
poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')
ax.add_patch(poly)
plt.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$",
horizontalalignment='center', fontsize=20)
plt.figtext(0.9, 0.05, '$x$')
plt.figtext(0.1, 0.9, '$y$')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.set_xticks((a, b))
ax.set_xticklabels(('$a$', '$b$'))
ax.set_yticks([])
plt.show()
0707010001faf0000081a400001782000005de000000015689ead200001189000002600000050a00000000000000000000004200000000reloc/matplotlib/examples/showcase/bachelors_degrees_by_gender.py import matplotlib.pyplot as plt
from matplotlib.mlab import csv2rec
from matplotlib.cbook import get_sample_data
fname = get_sample_data('percent_bachelors_degrees_women_usa.csv')
gender_degree_data = csv2rec(fname)
# These are the colors that will be used in the plot
color_sequence = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c',
'#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5',
'#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f',
'#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']
# You typically want your plot to be ~1.33x wider than tall. This plot
# is a rare exception because of the number of lines being plotted on it.
# Common sizes: (10, 7.5) and (12, 9)
fig, ax = plt.subplots(1, 1, figsize=(12, 14))
# Remove the plot frame lines. They are unnecessary here.
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
# Ensure that the axis ticks only show up on the bottom and left of the plot.
# Ticks on the right and top of the plot are generally unnecessary.
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
# Limit the range of the plot to only where the data is.
# Avoid unnecessary whitespace.
plt.xlim(1968.5, 2011.1)
plt.ylim(-0.25, 90)
# Make sure your axis ticks are large enough to be easily read.
# You don't want your viewers squinting to read your plot.
plt.xticks(range(1970, 2011, 10), fontsize=14)
plt.yticks(range(0, 91, 10), ['{0}%'.format(x)
for x in range(0, 91, 10)], fontsize=14)
# Provide tick lines across the plot to help your viewers trace along
# the axis ticks. Make sure that the lines are light and small so they
# don't obscure the primary data lines.
for y in range(10, 91, 10):
plt.plot(range(1969, 2012), [y] * len(range(1969, 2012)), '--',
lw=0.5, color='black', alpha=0.3)
# Remove the tick marks; they are unnecessary with the tick lines we just
# plotted.
plt.tick_params(axis='both', which='both', bottom='off', top='off',
labelbottom='on', left='off', right='off', labelleft='on')
# Now that the plot is prepared, it's time to actually plot the data!
# Note that I plotted the majors in order of the highest % in the final year.
majors = ['Health Professions', 'Public Administration', 'Education',
'Psychology', 'Foreign Languages', 'English',
'Communications\nand Journalism', 'Art and Performance', 'Biology',
'Agriculture', 'Social Sciences and History', 'Business',
'Math and Statistics', 'Architecture', 'Physical Sciences',
'Computer Science', 'Engineering']
y_offsets = {'Foreign Languages': 0.5, 'English': -0.5,
'Communications\nand Journalism': 0.75,
'Art and Performance': -0.25, 'Agriculture': 1.25,
'Social Sciences and History': 0.25, 'Business': -0.75,
'Math and Statistics': 0.75, 'Architecture': -0.75,
'Computer Science': 0.75, 'Engineering': -0.25}
for rank, column in enumerate(majors):
# Plot each line separately with its own color.
column_rec_name = column.replace('\n', '_').replace(' ', '_').lower()
line = plt.plot(gender_degree_data.year,
gender_degree_data[column_rec_name],
lw=2.5,
color=color_sequence[rank])
# Add a text label to the right end of every line. Most of the code below
# is adding specific offsets y position because some labels overlapped.
y_pos = gender_degree_data[column_rec_name][-1] - 0.5
if column in y_offsets:
y_pos += y_offsets[column]
# Again, make sure that all labels are large enough to be easily read
# by the viewer.
plt.text(2011.5, y_pos, column, fontsize=14, color=color_sequence[rank])
# Make the title big enough so it spans the entire plot, but don't make it
# so big that it requires two lines to show.
# Note that if the title is descriptive enough, it is unnecessary to include
# axis labels; they are self-evident, in this plot's case.
plt.title('Percentage of Bachelor\'s degrees conferred to women in '
'the U.S.A. by major (1970-2011)\n', fontsize=18, ha='center')
# Finally, save the figure as a PNG.
# You can also save it as a PDF, JPEG, etc.
# Just change the file extension in this call.
plt.savefig('percent-bachelors-degrees-women-usa.png', bbox_inches='tight')
0707010001f9b2000041ed00001782000005de00000002570a54fe00000000000002600000050a00000000000000000000002900000000reloc/matplotlib/examples/event_handling 0707010001f9c7000081a400001782000005de000000015689ead200000484000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/event_handling/zoom_window.py """
This example shows how to connect events in one window, for example, a mouse
press, to another figure window.
If you click on a point in the first window, the z and y limits of the
second will be adjusted so that the center of the zoom in the second
window will be the x,y coordinates of the clicked point.
Note the diameter of the circles in the scatter are defined in
points**2, so their size is independent of the zoom
"""
from matplotlib.pyplot import figure, show
import numpy
figsrc = figure()
figzoom = figure()
axsrc = figsrc.add_subplot(111, xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
axzoom = figzoom.add_subplot(111, xlim=(0.45, 0.55), ylim=(0.4, .6),
autoscale_on=False)
axsrc.set_title('Click to zoom')
axzoom.set_title('zoom window')
x, y, s, c = numpy.random.rand(4, 200)
s *= 200
axsrc.scatter(x, y, s, c)
axzoom.scatter(x, y, s, c)
def onpress(event):
if event.button != 1:
return
x, y = event.xdata, event.ydata
axzoom.set_xlim(x - 0.1, x + 0.1)
axzoom.set_ylim(y - 0.1, y + 0.1)
figzoom.canvas.draw()
figsrc.canvas.mpl_connect('button_press_event', onpress)
show()
0707010001f9ba000081a400001782000005de0000000155f2504c0000050c000002600000050a00000000000000000000003b00000000reloc/matplotlib/examples/event_handling/legend_picking.py """
Enable picking on the legend to toggle the legended line on and off
"""
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 0.2, 0.1)
y1 = 2*np.sin(2*np.pi*t)
y2 = 4*np.sin(2*np.pi*2*t)
fig, ax = plt.subplots()
ax.set_title('Click on legend line to toggle line on/off')
line1, = ax.plot(t, y1, lw=2, color='red', label='1 HZ')
line2, = ax.plot(t, y2, lw=2, color='blue', label='2 HZ')
leg = ax.legend(loc='upper left', fancybox=True, shadow=True)
leg.get_frame().set_alpha(0.4)
# we will set up a dict mapping legend line to orig line, and enable
# picking on the legend line
lines = [line1, line2]
lined = dict()
for legline, origline in zip(leg.get_lines(), lines):
legline.set_picker(5) # 5 pts tolerance
lined[legline] = origline
def onpick(event):
# on the pick event, find the orig line corresponding to the
# legend proxy line, and toggle the visibility
legline = event.artist
origline = lined[legline]
vis = not origline.get_visible()
origline.set_visible(vis)
# Change the alpha on the line in the legend so we can see what lines
# have been toggled
if vis:
legline.set_alpha(1.0)
else:
legline.set_alpha(0.2)
fig.canvas.draw()
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
0707010001f9c2000081a400001782000005de000000015689ead20000061d000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/event_handling/resample.py import numpy as np
import matplotlib.pyplot as plt
from scikits.audiolab import wavread
# A class that will downsample the data and recompute when zoomed.
class DataDisplayDownsampler(object):
def __init__(self, xdata, ydata):
self.origYData = ydata
self.origXData = xdata
self.numpts = 3000
self.delta = xdata[-1] - xdata[0]
def resample(self, xstart, xend):
# Very simple downsampling that takes the points within the range
# and picks every Nth point
mask = (self.origXData > xstart) & (self.origXData < xend)
xdata = self.origXData[mask]
ratio = int(xdata.size / self.numpts) + 1
xdata = xdata[::ratio]
ydata = self.origYData[mask]
ydata = ydata[::ratio]
return xdata, ydata
def update(self, ax):
# Update the line
lims = ax.viewLim
if np.abs(lims.width - self.delta) > 1e-8:
self.delta = lims.width
xstart, xend = lims.intervalx
self.line.set_data(*self.downsample(xstart, xend))
ax.figure.canvas.draw_idle()
# Read data
data = wavread('/usr/share/sounds/purple/receive.wav')[0]
ydata = np.tile(data[:, 0], 100)
xdata = np.arange(ydata.size)
d = DataDisplayDownsampler(xdata, ydata)
fig, ax = plt.subplots()
# Hook up the line
xdata, ydata = d.downsample(xdata[0], xdata[-1])
d.line, = ax.plot(xdata, ydata)
ax.set_autoscale_on(False) # Otherwise, infinite loop
# Connect for changing the view limits
ax.callbacks.connect('xlim_changed', d.update)
plt.show()
0707010001f9bc000081a400001782000005de000000015689ead200001115000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/event_handling/path_editor.py import numpy as np
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
Path = mpath.Path
fig, ax = plt.subplots()
pathdata = [
(Path.MOVETO, (1.58, -2.57)),
(Path.CURVE4, (0.35, -1.1)),
(Path.CURVE4, (-1.75, 2.0)),
(Path.CURVE4, (0.375, 2.0)),
(Path.LINETO, (0.85, 1.15)),
(Path.CURVE4, (2.2, 3.2)),
(Path.CURVE4, (3, 0.05)),
(Path.CURVE4, (2.0, -0.5)),
(Path.CLOSEPOLY, (1.58, -2.57)),
]
codes, verts = zip(*pathdata)
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)
class PathInteractor(object):
"""
An path editor.
Key-bindings
't' toggle vertex markers on and off. When vertex markers are on,
you can move them, delete them
"""
showverts = True
epsilon = 5 # max pixel distance to count as a vertex hit
def __init__(self, pathpatch):
self.ax = pathpatch.axes
canvas = self.ax.figure.canvas
self.pathpatch = pathpatch
self.pathpatch.set_animated(True)
x, y = zip(*self.pathpatch.get_path().vertices)
self.line, = ax.plot(x, y, marker='o', markerfacecolor='r', animated=True)
self._ind = None # the active vert
canvas.mpl_connect('draw_event', self.draw_callback)
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('key_press_event', self.key_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
self.canvas = canvas
def draw_callback(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.pathpatch)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
def pathpatch_changed(self, pathpatch):
'this method is called whenever the pathpatchgon object is called'
# only copy the artist props to the line (except visibility)
vis = self.line.get_visible()
plt.Artist.update_from(self.line, pathpatch)
self.line.set_visible(vis) # don't use the pathpatch visibility state
def get_ind_under_point(self, event):
'get the index of the vertex under point if within epsilon tolerance'
# display coords
xy = np.asarray(self.pathpatch.get_path().vertices)
xyt = self.pathpatch.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2)
ind = d.argmin()
if d[ind] >= self.epsilon:
ind = None
return ind
def button_press_callback(self, event):
'whenever a mouse button is pressed'
if not self.showverts:
return
if event.inaxes is None:
return
if event.button != 1:
return
self._ind = self.get_ind_under_point(event)
def button_release_callback(self, event):
'whenever a mouse button is released'
if not self.showverts:
return
if event.button != 1:
return
self._ind = None
def key_press_callback(self, event):
'whenever a key is pressed'
if not event.inaxes:
return
if event.key == 't':
self.showverts = not self.showverts
self.line.set_visible(self.showverts)
if not self.showverts:
self._ind = None
self.canvas.draw()
def motion_notify_callback(self, event):
'on mouse movement'
if not self.showverts:
return
if self._ind is None:
return
if event.inaxes is None:
return
if event.button != 1:
return
x, y = event.xdata, event.ydata
vertices = self.pathpatch.get_path().vertices
vertices[self._ind] = x, y
self.line.set_data(zip(*vertices))
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.pathpatch)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
interactor = PathInteractor(patch)
ax.set_title('drag vertices to update path')
ax.set_xlim(-3, 4)
ax.set_ylim(-3, 4)
plt.show()
0707010001f9bb000081a400001782000005de000000015689ead200000500000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/event_handling/looking_glass.py import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
x, y = np.random.rand(2, 200)
fig, ax = plt.subplots()
circ = patches.Circle((0.5, 0.5), 0.25, alpha=0.8, fc='yellow')
ax.add_patch(circ)
ax.plot(x, y, alpha=0.2)
line, = ax.plot(x, y, alpha=1.0, clip_path=circ)
class EventHandler(object):
def __init__(self):
fig.canvas.mpl_connect('button_press_event', self.onpress)
fig.canvas.mpl_connect('button_release_event', self.onrelease)
fig.canvas.mpl_connect('motion_notify_event', self.onmove)
self.x0, self.y0 = circ.center
self.pressevent = None
def onpress(self, event):
if event.inaxes != ax:
return
if not circ.contains(event)[0]:
return
self.pressevent = event
def onrelease(self, event):
self.pressevent = None
self.x0, self.y0 = circ.center
def onmove(self, event):
if self.pressevent is None or event.inaxes != self.pressevent.inaxes:
return
dx = event.xdata - self.pressevent.xdata
dy = event.ydata - self.pressevent.ydata
circ.center = self.x0 + dx, self.y0 + dy
line.set_clip_path(circ)
fig.canvas.draw()
handler = EventHandler()
plt.show()
0707010001f9c0000081a400001782000005de000000015689ead2000015aa000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/event_handling/poly_editor.py """
This is an example to show how to build cross-GUI applications using
matplotlib event handling to interact with objects on the canvas
"""
import numpy as np
from matplotlib.lines import Line2D
from matplotlib.artist import Artist
from matplotlib.mlab import dist_point_to_segment
class PolygonInteractor(object):
"""
An polygon editor.
Key-bindings
't' toggle vertex markers on and off. When vertex markers are on,
you can move them, delete them
'd' delete the vertex under point
'i' insert a vertex at point. You must be within epsilon of the
line connecting two existing vertices
"""
showverts = True
epsilon = 5 # max pixel distance to count as a vertex hit
def __init__(self, ax, poly):
if poly.figure is None:
raise RuntimeError('You must first add the polygon to a figure or canvas before defining the interactor')
self.ax = ax
canvas = poly.figure.canvas
self.poly = poly
x, y = zip(*self.poly.xy)
self.line = Line2D(x, y, marker='o', markerfacecolor='r', animated=True)
self.ax.add_line(self.line)
#self._update_line(poly)
cid = self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
canvas.mpl_connect('draw_event', self.draw_callback)
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('key_press_event', self.key_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
self.canvas = canvas
def draw_callback(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
def poly_changed(self, poly):
'this method is called whenever the polygon object is called'
# only copy the artist props to the line (except visibility)
vis = self.line.get_visible()
Artist.update_from(self.line, poly)
self.line.set_visible(vis) # don't use the poly visibility state
def get_ind_under_point(self, event):
'get the index of the vertex under point if within epsilon tolerance'
# display coords
xy = np.asarray(self.poly.xy)
xyt = self.poly.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2)
indseq = np.nonzero(np.equal(d, np.amin(d)))[0]
ind = indseq[0]
if d[ind] >= self.epsilon:
ind = None
return ind
def button_press_callback(self, event):
'whenever a mouse button is pressed'
if not self.showverts:
return
if event.inaxes is None:
return
if event.button != 1:
return
self._ind = self.get_ind_under_point(event)
def button_release_callback(self, event):
'whenever a mouse button is released'
if not self.showverts:
return
if event.button != 1:
return
self._ind = None
def key_press_callback(self, event):
'whenever a key is pressed'
if not event.inaxes:
return
if event.key == 't':
self.showverts = not self.showverts
self.line.set_visible(self.showverts)
if not self.showverts:
self._ind = None
elif event.key == 'd':
ind = self.get_ind_under_point(event)
if ind is not None:
self.poly.xy = [tup for i, tup in enumerate(self.poly.xy) if i != ind]
self.line.set_data(zip(*self.poly.xy))
elif event.key == 'i':
xys = self.poly.get_transform().transform(self.poly.xy)
p = event.x, event.y # display coords
for i in range(len(xys) - 1):
s0 = xys[i]
s1 = xys[i + 1]
d = dist_point_to_segment(p, s0, s1)
if d <= self.epsilon:
self.poly.xy = np.array(
list(self.poly.xy[:i]) +
[(event.xdata, event.ydata)] +
list(self.poly.xy[i:]))
self.line.set_data(zip(*self.poly.xy))
break
self.canvas.draw()
def motion_notify_callback(self, event):
'on mouse movement'
if not self.showverts:
return
if self._ind is None:
return
if event.inaxes is None:
return
if event.button != 1:
return
x, y = event.xdata, event.ydata
self.poly.xy[self._ind] = x, y
self.line.set_data(zip(*self.poly.xy))
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
if __name__ == '__main__':
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
theta = np.arange(0, 2*np.pi, 0.1)
r = 1.5
xs = r*np.cos(theta)
ys = r*np.sin(theta)
poly = Polygon(list(zip(xs, ys)), animated=True)
fig, ax = plt.subplots()
ax.add_patch(poly)
p = PolygonInteractor(ax, poly)
#ax.add_line(p.line)
ax.set_title('Click and drag a point to move it')
ax.set_xlim((-2, 2))
ax.set_ylim((-2, 2))
plt.show()
0707010001f9be000081a400001782000005de000000015689ead200000404000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/event_handling/pick_event_demo2.py """
compute the mean and standard deviation (stddev) of 100 data sets and plot
mean vs stddev. When you click on one of the mu, sigma points, plot the raw
data from the dataset that generated the mean and stddev.
"""
import numpy
import matplotlib.pyplot as plt
X = numpy.random.rand(100, 1000)
xs = numpy.mean(X, axis=1)
ys = numpy.std(X, axis=1)
fig, ax = plt.subplots()
ax.set_title('click on point to plot time series')
line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance
def onpick(event):
if event.artist != line:
return True
N = len(event.ind)
if not N:
return True
figi = plt.figure()
for subplotnum, dataind in enumerate(event.ind):
ax = figi.add_subplot(N, 1, subplotnum + 1)
ax.plot(X[dataind])
ax.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f' % (xs[dataind], ys[dataind]),
transform=ax.transAxes, va='top')
ax.set_ylim(-0.5, 1.5)
figi.show()
return True
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
0707010001f9b7000081a400001782000005de000000015689ead20000031d000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/event_handling/idle_and_timeout.py from __future__ import print_function
"""
Demonstrate/test the idle and timeout API
WARNING: idle_event is deprecated. Use the animations module instead.
This is only tested on gtk so far and is a prototype implementation
"""
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
t = np.arange(0.0, 2.0, 0.01)
y1 = np.sin(2*np.pi*t)
y2 = np.cos(2*np.pi*t)
line1, = ax.plot(y1)
line2, = ax.plot(y2)
N = 100
def on_idle(event):
on_idle.count += 1
print('idle', on_idle.count)
line1.set_ydata(np.sin(2*np.pi*t*(N - on_idle.count)/float(N)))
event.canvas.draw()
# test boolean return removal
if on_idle.count == N:
return False
return True
on_idle.cid = None
on_idle.count = 0
fig.canvas.mpl_connect('idle_event', on_idle)
plt.show()
0707010001f9b5000081a400001782000005de000000015689ead200000929000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/event_handling/data_browser.py import numpy as np
class PointBrowser(object):
"""
Click on a point to select and highlight it -- the data that
generated the point will be shown in the lower axes. Use the 'n'
and 'p' keys to browse through the next and previous points
"""
def __init__(self):
self.lastind = 0
self.text = ax.text(0.05, 0.95, 'selected: none',
transform=ax.transAxes, va='top')
self.selected, = ax.plot([xs[0]], [ys[0]], 'o', ms=12, alpha=0.4,
color='yellow', visible=False)
def onpress(self, event):
if self.lastind is None:
return
if event.key not in ('n', 'p'):
return
if event.key == 'n':
inc = 1
else:
inc = -1
self.lastind += inc
self.lastind = np.clip(self.lastind, 0, len(xs) - 1)
self.update()
def onpick(self, event):
if event.artist != line:
return True
N = len(event.ind)
if not N:
return True
# the click locations
x = event.mouseevent.xdata
y = event.mouseevent.ydata
distances = np.hypot(x - xs[event.ind], y - ys[event.ind])
indmin = distances.argmin()
dataind = event.ind[indmin]
self.lastind = dataind
self.update()
def update(self):
if self.lastind is None:
return
dataind = self.lastind
ax2.cla()
ax2.plot(X[dataind])
ax2.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f' % (xs[dataind], ys[dataind]),
transform=ax2.transAxes, va='top')
ax2.set_ylim(-0.5, 1.5)
self.selected.set_visible(True)
self.selected.set_data(xs[dataind], ys[dataind])
self.text.set_text('selected: %d' % dataind)
fig.canvas.draw()
if __name__ == '__main__':
import matplotlib.pyplot as plt
X = np.random.rand(100, 200)
xs = np.mean(X, axis=1)
ys = np.std(X, axis=1)
fig, (ax, ax2) = plt.subplots(2, 1)
ax.set_title('click on point to plot time series')
line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance
browser = PointBrowser()
fig.canvas.mpl_connect('pick_event', browser.onpick)
fig.canvas.mpl_connect('key_press_event', browser.onpress)
plt.show()
0707010001f9c6000081a400001782000005de000000015689ead200000b49000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/event_handling/viewlims.py # Creates two identical panels. Zooming in on the right panel will show
# a rectangle in the first panel, denoting the zoomed region.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
# We just subclass Rectangle so that it can be called with an Axes
# instance, causing the rectangle to update its shape to match the
# bounds of the Axes
class UpdatingRect(Rectangle):
def __call__(self, ax):
self.set_bounds(*ax.viewLim.bounds)
ax.figure.canvas.draw_idle()
# A class that will regenerate a fractal set as we zoom in, so that you
# can actually see the increasing detail. A box in the left panel will show
# the area to which we are zoomed.
class MandlebrotDisplay(object):
def __init__(self, h=500, w=500, niter=50, radius=2., power=2):
self.height = h
self.width = w
self.niter = niter
self.radius = radius
self.power = power
def __call__(self, xstart, xend, ystart, yend):
self.x = np.linspace(xstart, xend, self.width)
self.y = np.linspace(ystart, yend, self.height).reshape(-1, 1)
c = self.x + 1.0j * self.y
threshold_time = np.zeros((self.height, self.width))
z = np.zeros(threshold_time.shape, dtype=np.complex)
mask = np.ones(threshold_time.shape, dtype=np.bool)
for i in range(self.niter):
z[mask] = z[mask]**self.power + c[mask]
mask = (np.abs(z) < self.radius)
threshold_time += mask
return threshold_time
def ax_update(self, ax):
ax.set_autoscale_on(False) # Otherwise, infinite loop
# Get the number of points from the number of pixels in the window
dims = ax.axesPatch.get_window_extent().bounds
self.width = int(dims[2] + 0.5)
self.height = int(dims[2] + 0.5)
# Get the range for the new area
xstart, ystart, xdelta, ydelta = ax.viewLim.bounds
xend = xstart + xdelta
yend = ystart + ydelta
# Update the image object with our new data and extent
im = ax.images[-1]
im.set_data(self.__call__(xstart, xend, ystart, yend))
im.set_extent((xstart, xend, ystart, yend))
ax.figure.canvas.draw_idle()
md = MandlebrotDisplay()
Z = md(-2., 0.5, -1.25, 1.25)
fig1, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(Z, origin='lower', extent=(md.x.min(), md.x.max(), md.y.min(), md.y.max()))
ax2.imshow(Z, origin='lower', extent=(md.x.min(), md.x.max(), md.y.min(), md.y.max()))
rect = UpdatingRect([0, 0], 0, 0, facecolor='None', edgecolor='black')
rect.set_bounds(*ax2.viewLim.bounds)
ax1.add_patch(rect)
# Connect for changing the view limits
ax2.callbacks.connect('xlim_changed', rect)
ax2.callbacks.connect('ylim_changed', rect)
ax2.callbacks.connect('xlim_changed', md.ax_update)
ax2.callbacks.connect('ylim_changed', md.ax_update)
plt.show()
0707010001f9c5000081a400001782000005de0000000155f2504c000006eb000002600000050a00000000000000000000004100000000reloc/matplotlib/examples/event_handling/trifinder_event_demo.py """
Example showing the use of a TriFinder object. As the mouse is moved over the
triangulation, the triangle under the cursor is highlighted and the index of
the triangle is displayed in the plot title.
"""
import matplotlib.pyplot as plt
from matplotlib.tri import Triangulation
from matplotlib.patches import Polygon
import numpy as np
import math
def update_polygon(tri):
if tri == -1:
points = [0, 0, 0]
else:
points = triangulation.triangles[tri]
xs = triangulation.x[points]
ys = triangulation.y[points]
polygon.set_xy(zip(xs, ys))
def motion_notify(event):
if event.inaxes is None:
tri = -1
else:
tri = trifinder(event.xdata, event.ydata)
update_polygon(tri)
plt.title('In triangle %i' % tri)
event.canvas.draw()
# Create a Triangulation.
n_angles = 16
n_radii = 5
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2*math.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += math.pi / n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
triangulation = Triangulation(x, y)
xmid = x[triangulation.triangles].mean(axis=1)
ymid = y[triangulation.triangles].mean(axis=1)
mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0)
triangulation.set_mask(mask)
# Use the triangulation's default TriFinder object.
trifinder = triangulation.get_trifinder()
# Setup plot and callbacks.
plt.subplot(111, aspect='equal')
plt.triplot(triangulation, 'bo-')
polygon = Polygon([[0, 0], [0, 0]], facecolor='y') # dummy data for xs,ys
update_polygon(-1)
plt.gca().add_patch(polygon)
plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify)
plt.show()
0707010001f9b4000081a400001782000005de000000015689ead2000000ff000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/event_handling/close_event.py from __future__ import print_function
import matplotlib.pyplot as plt
def handle_close(evt):
print('Closed Figure!')
fig = plt.figure()
fig.canvas.mpl_connect('close_event', handle_close)
plt.text(0.35, 0.5, 'Close Me!', dict(size=30))
plt.show()
0707010001f9c4000081a400001782000005de000000015689ead200000316000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/event_handling/timers.py # Simple example of using general timer objects. This is used to update
# the time placed in the title of the figure.
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
def update_title(axes):
axes.set_title(datetime.now())
axes.figure.canvas.draw()
fig, ax = plt.subplots()
x = np.linspace(-3, 3)
ax.plot(x, x*x)
# Create a new timer object. Set the interval to 100 milliseconds
# (1000 is default) and tell the timer what function should be called.
timer = fig.canvas.new_timer(interval=100)
timer.add_callback(update_title, ax)
timer.start()
# Or could start the timer on first figure draw
#def start_timer(evt):
# timer.start()
# fig.canvas.mpl_disconnect(drawid)
#drawid = fig.canvas.mpl_connect('draw_event', start_timer)
plt.show()
0707010001f9c1000081ed00001782000005de000000015689ead200000316000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/event_handling/pong_gtk.py #!/usr/bin/env python
from __future__ import print_function
# For detailed comments on animation and the techniques used here, see
# the wiki entry
# http://www.scipy.org/wikis/topical_software/MatplotlibAnimation
import time
import gobject
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
import pipong
fig, ax = plt.subplots()
canvas = ax.figure.canvas
def start_anim(event):
# gobject.idle_add(animation.draw,animation)
gobject.timeout_add(10, animation.draw, animation)
canvas.mpl_disconnect(start_anim.cid)
animation = pipong.Game(ax)
start_anim.cid = canvas.mpl_connect('draw_event', start_anim)
tstart = time.time()
plt.grid() # to ensure proper background restore
plt.show()
print('FPS: %f' % animation.cnt/(time.time() - tstart))
0707010001f9bf000081ed00001782000005de000000015689ead200002309000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/event_handling/pipong.py #!/usr/bin/env python
# A matplotlib based game of Pong illustrating one way to write interactive
# animation which are easily ported to multiple backends
# pipong.py was written by Paul Ivanov
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randn, randint
instructions = """
Player A: Player B:
'e' up 'i'
'd' down 'k'
press 't' -- close these instructions
(animation will be much faster)
press 'a' -- add a puck
press 'A' -- remove a puck
press '1' -- slow down all pucks
press '2' -- speed up all pucks
press '3' -- slow down distractors
press '4' -- speed up distractors
press ' ' -- reset the first puck
press 'n' -- toggle distractors on/off
press 'g' -- toggle the game on/off
"""
class Pad(object):
def __init__(self, disp, x, y, type='l'):
self.disp = disp
self.x = x
self.y = y
self.w = .3
self.score = 0
self.xoffset = 0.3
self.yoffset = 0.1
if type == 'r':
self.xoffset *= -1.0
if type == 'l' or type == 'r':
self.signx = -1.0
self.signy = 1.0
else:
self.signx = 1.0
self.signy = -1.0
def contains(self, loc):
return self.disp.get_bbox().contains(loc.x, loc.y)
class Puck(object):
def __init__(self, disp, pad, field):
self.vmax = .2
self.disp = disp
self.field = field
self._reset(pad)
def _reset(self, pad):
self.x = pad.x + pad.xoffset
if pad.y < 0:
self.y = pad.y + pad.yoffset
else:
self.y = pad.y - pad.yoffset
self.vx = pad.x - self.x
self.vy = pad.y + pad.w/2 - self.y
self._speedlimit()
self._slower()
self._slower()
def update(self, pads):
self.x += self.vx
self.y += self.vy
for pad in pads:
if pad.contains(self):
self.vx *= 1.2 * pad.signx
self.vy *= 1.2 * pad.signy
fudge = .001
# probably cleaner with something like...
#if not self.field.contains(self.x, self.y):
if self.x < fudge:
#print("player A loses")
pads[1].score += 1
self._reset(pads[0])
return True
if self.x > 7 - fudge:
#print("player B loses")
pads[0].score += 1
self._reset(pads[1])
return True
if self.y < -1 + fudge or self.y > 1 - fudge:
self.vy *= -1.0
# add some randomness, just to make it interesting
self.vy -= (randn()/300.0 + 1/300.0) * np.sign(self.vy)
self._speedlimit()
return False
def _slower(self):
self.vx /= 5.0
self.vy /= 5.0
def _faster(self):
self.vx *= 5.0
self.vy *= 5.0
def _speedlimit(self):
if self.vx > self.vmax:
self.vx = self.vmax
if self.vx < -self.vmax:
self.vx = -self.vmax
if self.vy > self.vmax:
self.vy = self.vmax
if self.vy < -self.vmax:
self.vy = -self.vmax
class Game(object):
def __init__(self, ax):
# create the initial line
self.ax = ax
padAx = padBx = .50
padAy = padBy = .30
padBx += 6.3
pA, = self.ax.barh(padAy, .2, height=.3, color='k', alpha=.5, edgecolor='b', lw=2, label="Player B", animated=True)
pB, = self.ax.barh(padBy, .2, height=.3, left=padBx, color='k', alpha=.5, edgecolor='r', lw=2, label="Player A", animated=True)
# distractors
self.x = np.arange(0, 2.22*np.pi, 0.01)
self.line, = self.ax.plot(self.x, np.sin(self.x), "r", animated=True, lw=4)
self.line2, = self.ax.plot(self.x, np.cos(self.x), "g", animated=True, lw=4)
self.line3, = self.ax.plot(self.x, np.cos(self.x), "g", animated=True, lw=4)
self.line4, = self.ax.plot(self.x, np.cos(self.x), "r", animated=True, lw=4)
self.centerline, = self.ax.plot([3.5, 3.5], [1, -1], 'k', alpha=.5, animated=True, lw=8)
self.puckdisp = self.ax.scatter([1], [1], label='_nolegend_', s=200, c='g', alpha=.9, animated=True)
self.canvas = self.ax.figure.canvas
self.background = None
self.cnt = 0
self.distract = True
self.res = 100.0
self.on = False
self.inst = True # show instructions from the beginning
self.background = None
self.pads = []
self.pads.append(Pad(pA, 0, padAy))
self.pads.append(Pad(pB, padBx, padBy, 'r'))
self.pucks = []
self.i = self.ax.annotate(instructions, (.5, 0.5),
name='monospace',
verticalalignment='center',
horizontalalignment='center',
multialignment='left',
textcoords='axes fraction', animated=True)
self.canvas.mpl_connect('key_press_event', self.key_press)
def draw(self, evt):
draw_artist = self.ax.draw_artist
if self.background is None:
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
# restore the clean slate background
self.canvas.restore_region(self.background)
# show the distractors
if self.distract:
self.line.set_ydata(np.sin(self.x + self.cnt/self.res))
self.line2.set_ydata(np.cos(self.x - self.cnt/self.res))
self.line3.set_ydata(np.tan(self.x + self.cnt/self.res))
self.line4.set_ydata(np.tan(self.x - self.cnt/self.res))
draw_artist(self.line)
draw_artist(self.line2)
draw_artist(self.line3)
draw_artist(self.line4)
# show the instructions - this is very slow
if self.inst:
self.ax.draw_artist(self.i)
# pucks and pads
if self.on:
self.ax.draw_artist(self.centerline)
for pad in self.pads:
pad.disp.set_y(pad.y)
pad.disp.set_x(pad.x)
self.ax.draw_artist(pad.disp)
for puck in self.pucks:
if puck.update(self.pads):
# we only get here if someone scored
self.pads[0].disp.set_label(" " + str(self.pads[0].score))
self.pads[1].disp.set_label(" " + str(self.pads[1].score))
self.ax.legend(loc='center')
self.leg = self.ax.get_legend()
#self.leg.draw_frame(False) #don't draw the legend border
self.leg.get_frame().set_alpha(.2)
plt.setp(self.leg.get_texts(), fontweight='bold', fontsize='xx-large')
self.leg.get_frame().set_facecolor('0.2')
self.background = None
self.ax.figure.canvas.draw()
return True
puck.disp.set_offsets([puck.x, puck.y])
self.ax.draw_artist(puck.disp)
# just redraw the axes rectangle
self.canvas.blit(self.ax.bbox)
if self.cnt == 50000:
# just so we don't get carried away
print("...and you've been playing for too long!!!")
plt.close()
self.cnt += 1
return True
def key_press(self, event):
if event.key == '3':
self.res *= 5.0
if event.key == '4':
self.res /= 5.0
if event.key == 'e':
self.pads[0].y += .1
if self.pads[0].y > 1 - .3:
self.pads[0].y = 1 - .3
if event.key == 'd':
self.pads[0].y -= .1
if self.pads[0].y < -1:
self.pads[0].y = -1
if event.key == 'i':
self.pads[1].y += .1
if self.pads[1].y > 1 - .3:
self.pads[1].y = 1 - .3
if event.key == 'k':
self.pads[1].y -= .1
if self.pads[1].y < -1:
self.pads[1].y = -1
if event.key == 'a':
self.pucks.append(Puck(self.puckdisp, self.pads[randint(2)], self.ax.bbox))
if event.key == 'A' and len(self.pucks):
self.pucks.pop()
if event.key == ' ' and len(self.pucks):
self.pucks[0]._reset(self.pads[randint(2)])
if event.key == '1':
for p in self.pucks:
p._slower()
if event.key == '2':
for p in self.pucks:
p._faster()
if event.key == 'n':
self.distract = not self.distract
if event.key == 'g':
#self.ax.clear()
self.on = not self.on
if event.key == 't':
self.inst = not self.inst
self.i.set_visible(self.i.get_visible())
if event.key == 'q':
plt.close()
0707010001f9bd000081ed00001782000005de000000015689ead2000018d1000002600000050a00000000000000000000003c00000000reloc/matplotlib/examples/event_handling/pick_event_demo.py #!/usr/bin/env python
"""
You can enable picking by setting the "picker" property of an artist
(for example, a matplotlib Line2D, Text, Patch, Polygon, AxesImage,
etc...)
There are a variety of meanings of the picker property
None - picking is disabled for this artist (default)
boolean - if True then picking will be enabled and the
artist will fire a pick event if the mouse event is over
the artist
float - if picker is a number it is interpreted as an
epsilon tolerance in points and the artist will fire
off an event if it's data is within epsilon of the mouse
event. For some artists like lines and patch collections,
the artist may provide additional data to the pick event
that is generated, for example, the indices of the data within
epsilon of the pick event
function - if picker is callable, it is a user supplied
function which determines whether the artist is hit by the
mouse event.
hit, props = picker(artist, mouseevent)
to determine the hit test. If the mouse event is over the
artist, return hit=True and props is a dictionary of properties
you want added to the PickEvent attributes
After you have enabled an artist for picking by setting the "picker"
property, you need to connect to the figure canvas pick_event to get
pick callbacks on mouse press events. For example,
def pick_handler(event):
mouseevent = event.mouseevent
artist = event.artist
# now do something with this...
The pick event (matplotlib.backend_bases.PickEvent) which is passed to
your callback is always fired with two attributes:
mouseevent - the mouse event that generate the pick event. The
mouse event in turn has attributes like x and y (the coordinates in
display space, such as pixels from left, bottom) and xdata, ydata (the
coords in data space). Additionally, you can get information about
which buttons were pressed, which keys were pressed, which Axes
the mouse is over, etc. See matplotlib.backend_bases.MouseEvent
for details.
artist - the matplotlib.artist that generated the pick event.
Additionally, certain artists like Line2D and PatchCollection may
attach additional meta data like the indices into the data that meet
the picker criteria (for example, all the points in the line that are within
the specified epsilon tolerance)
The examples below illustrate each of these methods.
"""
from __future__ import print_function
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from matplotlib.text import Text
from matplotlib.image import AxesImage
import numpy as np
from numpy.random import rand
if 1: # simple picking, lines, rectangles and text
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.set_title('click on points, rectangles or text', picker=True)
ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red'))
line, = ax1.plot(rand(100), 'o', picker=5) # 5 points tolerance
# pick the rectangle
bars = ax2.bar(range(10), rand(10), picker=True)
for label in ax2.get_xticklabels(): # make the xtick labels pickable
label.set_picker(True)
def onpick1(event):
if isinstance(event.artist, Line2D):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
print('onpick1 line:', zip(np.take(xdata, ind), np.take(ydata, ind)))
elif isinstance(event.artist, Rectangle):
patch = event.artist
print('onpick1 patch:', patch.get_path())
elif isinstance(event.artist, Text):
text = event.artist
print('onpick1 text:', text.get_text())
fig.canvas.mpl_connect('pick_event', onpick1)
if 1: # picking with a custom hit test function
# you can define custom pickers by setting picker to a callable
# function. The function has the signature
#
# hit, props = func(artist, mouseevent)
#
# to determine the hit test. if the mouse event is over the artist,
# return hit=True and props is a dictionary of
# properties you want added to the PickEvent attributes
def line_picker(line, mouseevent):
"""
find the points within a certain distance from the mouseclick in
data coords and attach some extra attributes, pickx and picky
which are the data points that were picked
"""
if mouseevent.xdata is None:
return False, dict()
xdata = line.get_xdata()
ydata = line.get_ydata()
maxd = 0.05
d = np.sqrt((xdata - mouseevent.xdata)**2. + (ydata - mouseevent.ydata)**2.)
ind = np.nonzero(np.less_equal(d, maxd))
if len(ind):
pickx = np.take(xdata, ind)
picky = np.take(ydata, ind)
props = dict(ind=ind, pickx=pickx, picky=picky)
return True, props
else:
return False, dict()
def onpick2(event):
print('onpick2 line:', event.pickx, event.picky)
fig, ax = plt.subplots()
ax.set_title('custom picker for line data')
line, = ax.plot(rand(100), rand(100), 'o', picker=line_picker)
fig.canvas.mpl_connect('pick_event', onpick2)
if 1: # picking on a scatter plot (matplotlib.collections.RegularPolyCollection)
x, y, c, s = rand(4, 100)
def onpick3(event):
ind = event.ind
print('onpick3 scatter:', ind, np.take(x, ind), np.take(y, ind))
fig, ax = plt.subplots()
col = ax.scatter(x, y, 100*s, c, picker=True)
#fig.savefig('pscoll.eps')
fig.canvas.mpl_connect('pick_event', onpick3)
if 1: # picking images (matplotlib.image.AxesImage)
fig, ax = plt.subplots()
im1 = ax.imshow(rand(10, 5), extent=(1, 2, 1, 2), picker=True)
im2 = ax.imshow(rand(5, 10), extent=(3, 4, 1, 2), picker=True)
im3 = ax.imshow(rand(20, 25), extent=(1, 2, 3, 4), picker=True)
im4 = ax.imshow(rand(30, 12), extent=(3, 4, 3, 4), picker=True)
ax.axis([0, 5, 0, 5])
def onpick4(event):
artist = event.artist
if isinstance(artist, AxesImage):
im = artist
A = im.get_array()
print('onpick4 image', A.shape)
fig.canvas.mpl_connect('pick_event', onpick4)
plt.show()
0707010001f9c3000081ed00001782000005de0000000155f2504c00000319000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/event_handling/test_mouseclicks.py #!/usr/bin/env python
from __future__ import print_function
import matplotlib
#matplotlib.use("WxAgg")
#matplotlib.use("TkAgg")
#matplotlib.use("GTKAgg")
#matplotlib.use("Qt4Agg")
#matplotlib.use("CocoaAgg")
#matplotlib.use("MacOSX")
import matplotlib.pyplot as plt
#print("***** TESTING WITH BACKEND: %s"%matplotlib.get_backend() + " *****")
def OnClick(event):
if event.dblclick:
print("DBLCLICK", event)
else:
print("DOWN ", event)
def OnRelease(event):
print("UP ", event)
fig = plt.gcf()
cid_up = fig.canvas.mpl_connect('button_press_event', OnClick)
cid_down = fig.canvas.mpl_connect('button_release_event', OnRelease)
plt.gca().text(0.5, 0.5, "Click on the canvas to test mouse events.",
ha="center", va="center")
plt.show()
0707010001f9b6000081a400001782000005de000000015689ead20000059a000002600000050a00000000000000000000004400000000reloc/matplotlib/examples/event_handling/figure_axes_enter_leave.py """
Illustrate the figure and axes enter and leave events by changing the
frame colors on enter and leave
"""
from __future__ import print_function
import matplotlib.pyplot as plt
def enter_axes(event):
print('enter_axes', event.inaxes)
event.inaxes.patch.set_facecolor('yellow')
event.canvas.draw()
def leave_axes(event):
print('leave_axes', event.inaxes)
event.inaxes.patch.set_facecolor('white')
event.canvas.draw()
def enter_figure(event):
print('enter_figure', event.canvas.figure)
event.canvas.figure.patch.set_facecolor('red')
event.canvas.draw()
def leave_figure(event):
print('leave_figure', event.canvas.figure)
event.canvas.figure.patch.set_facecolor('grey')
event.canvas.draw()
fig1, (ax, ax2) = plt.subplots(2, 1)
fig1.suptitle('mouse hover over figure or axes to trigger events')
fig1.canvas.mpl_connect('figure_enter_event', enter_figure)
fig1.canvas.mpl_connect('figure_leave_event', leave_figure)
fig1.canvas.mpl_connect('axes_enter_event', enter_axes)
fig1.canvas.mpl_connect('axes_leave_event', leave_axes)
fig2, (ax, ax2) = plt.subplots(2, 1)
fig2.suptitle('mouse hover over figure or axes to trigger events')
fig2.canvas.mpl_connect('figure_enter_event', enter_figure)
fig2.canvas.mpl_connect('figure_leave_event', leave_figure)
fig2.canvas.mpl_connect('axes_enter_event', enter_axes)
fig2.canvas.mpl_connect('axes_leave_event', leave_axes)
plt.show()
0707010001f9b8000081ed00001782000005de000000015689ead200000225000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/event_handling/keypress_demo.py #!/usr/bin/env python
"""
Show how to connect to keypress events
"""
from __future__ import print_function
import sys
import numpy as np
import matplotlib.pyplot as plt
def press(event):
print('press', event.key)
sys.stdout.flush()
if event.key == 'x':
visible = xl.get_visible()
xl.set_visible(not visible)
fig.canvas.draw()
fig, ax = plt.subplots()
fig.canvas.mpl_connect('key_press_event', press)
ax.plot(np.random.rand(12), np.random.rand(12), 'go')
xl = ax.set_xlabel('easy come, easy go')
plt.show()
0707010001f9b3000081a400001782000005de000000015689ead200000231000002600000050a00000000000000000000003400000000reloc/matplotlib/examples/event_handling/README.txt matplotlib event handling
=========================
matplotlib supports event handling with a GUI neutral event model. So
you can connect to matplotlib events w/o knowledge of what user
interface matplotlib will ultimately be plugged in to. This has two
advantages: the code you write will be more portable, and matplotlib
events are aware of things like data coordinate space and whih axes
the event occurs in so you don't have to mess with low level
transformation details to go from canvas space to data space. Object
picking examples are also included.
0707010001f9b9000081a400001782000005de000000015689ead2000009a3000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/event_handling/lasso_demo.py """
Show how to use a lasso to select a set of points and get the indices
of the selected points. A callback is used to change the color of the
selected points
This is currently a proof-of-concept implementation (though it is
usable as is). There will be some refinement of the API.
"""
from matplotlib.widgets import Lasso
from matplotlib.colors import colorConverter
from matplotlib.collections import RegularPolyCollection
from matplotlib import path
import matplotlib.pyplot as plt
from numpy import nonzero
from numpy.random import rand
class Datum(object):
colorin = colorConverter.to_rgba('red')
colorout = colorConverter.to_rgba('blue')
def __init__(self, x, y, include=False):
self.x = x
self.y = y
if include:
self.color = self.colorin
else:
self.color = self.colorout
class LassoManager(object):
def __init__(self, ax, data):
self.axes = ax
self.canvas = ax.figure.canvas
self.data = data
self.Nxy = len(data)
facecolors = [d.color for d in data]
self.xys = [(d.x, d.y) for d in data]
fig = ax.figure
self.collection = RegularPolyCollection(
fig.dpi, 6, sizes=(100,),
facecolors=facecolors,
offsets=self.xys,
transOffset=ax.transData)
ax.add_collection(self.collection)
self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
def callback(self, verts):
facecolors = self.collection.get_facecolors()
p = path.Path(verts)
ind = p.contains_points(self.xys)
for i in range(len(self.xys)):
if ind[i]:
facecolors[i] = Datum.colorin
else:
facecolors[i] = Datum.colorout
self.canvas.draw_idle()
self.canvas.widgetlock.release(self.lasso)
del self.lasso
def onpress(self, event):
if self.canvas.widgetlock.locked():
return
if event.inaxes is None:
return
self.lasso = Lasso(event.inaxes,
(event.xdata, event.ydata),
self.callback)
# acquire a lock on the widget drawing
self.canvas.widgetlock(self.lasso)
if __name__ == '__main__':
data = [Datum(*xy) for xy in rand(100, 2)]
ax = plt.axes(xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
lman = LassoManager(ax, data)
plt.show()
0707010001fa0a000041ed00001782000005de00000002570a54fe00000000000002600000050a00000000000000000000002f00000000reloc/matplotlib/examples/pie_and_polar_charts 0707010001fa0c000081a400001782000005de000000015689ead2000001d1000002600000050a00000000000000000000004100000000reloc/matplotlib/examples/pie_and_polar_charts/polar_bar_demo.py """
Demo of bar plot on a polar axis.
"""
import numpy as np
import matplotlib.pyplot as plt
N = 20
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
ax = plt.subplot(111, projection='polar')
bars = ax.bar(theta, radii, width=width, bottom=0.0)
# Use custom colors and opacity
for r, bar in zip(radii, bars):
bar.set_facecolor(plt.cm.jet(r / 10.))
bar.set_alpha(0.5)
plt.show()
0707010001fa0d000081a400001782000005de000000015689ead2000001ea000002600000050a00000000000000000000004500000000reloc/matplotlib/examples/pie_and_polar_charts/polar_scatter_demo.py """
Demo of scatter plot on a polar axis.
Size increases radially in this example and color increases with angle (just to
verify the symbols are being scattered correctly).
"""
import numpy as np
import matplotlib.pyplot as plt
N = 150
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2 * np.random.rand(N)
colors = theta
ax = plt.subplot(111, projection='polar')
c = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.hsv)
c.set_alpha(0.75)
plt.show()
0707010001fa0b000081a400001782000005de000000015689ead20000082b000002600000050a00000000000000000000004400000000reloc/matplotlib/examples/pie_and_polar_charts/pie_demo_features.py """
Demo of a basic pie chart plus a few additional features.
In addition to the basic pie chart, this demo shows a few optional features:
* slice labels
* auto-labeling the percentage
* offsetting a slice with "explode"
* drop-shadow
* custom start angle
Note about the custom start angle:
The default ``startangle`` is 0, which would start the "Frogs" slice on the
positive x-axis. This example sets ``startangle = 90`` such that everything is
rotated counter-clockwise by 90 degrees, and the frog slice starts on the
positive y-axis.
"""
import matplotlib.pyplot as plt
# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
fig = plt.figure()
ax = fig.gca()
import numpy as np
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
radius=0.25, center=(0, 0), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
radius=0.25, center=(1, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
radius=0.25, center=(0, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90,
radius=0.25, center=(1, 0), frame=True)
ax.set_xticks([0, 1])
ax.set_yticks([0, 1])
ax.set_xticklabels(["Sunny", "Cloudy"])
ax.set_yticklabels(["Dry", "Rainy"])
ax.set_xlim((-0.5, 1.5))
ax.set_ylim((-0.5, 1.5))
# Set aspect ratio to be equal so that pie is drawn as a circle.
ax.set_aspect('equal')
plt.show()
0707010001f95d000041ed00001782000005de00000002570a54fd00000000000002600000050a00000000000000000000002400000000reloc/matplotlib/examples/animation 0707010001f966000081a400001782000005de000000015689ead20000038b000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/animation/moviewriter.py # This example uses a MovieWriter directly to grab individual frames and
# write them to a file. This avoids any event loop integration, but has
# the advantage of working with even the Agg backend. This is not recommended
# for use in an interactive setting.
# -*- noplot -*-
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as manimation
FFMpegWriter = manimation.writers['ffmpeg']
metadata = dict(title='Movie Test', artist='Matplotlib',
comment='Movie support!')
writer = FFMpegWriter(fps=15, metadata=metadata)
fig = plt.figure()
l, = plt.plot([], [], 'k-o')
plt.xlim(-5, 5)
plt.ylim(-5, 5)
x0, y0 = 0, 0
with writer.saving(fig, "writer_test.mp4", 100):
for i in range(100):
x0 += 0.1 * np.random.randn()
y0 += 0.1 * np.random.randn()
l.set_data(x0, y0)
writer.grab_frame()
0707010001f962000081a400001782000005de00000001569316c10000091b000002600000050a00000000000000000000004000000000reloc/matplotlib/examples/animation/double_pendulum_animated.py # Double pendulum formula translated from the C code at
# http://www.physics.usyd.edu.au/~wheat/dpend_html/solve_dpend.c
from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation
G = 9.8 # acceleration due to gravity, in m/s^2
L1 = 1.0 # length of pendulum 1 in m
L2 = 1.0 # length of pendulum 2 in m
M1 = 1.0 # mass of pendulum 1 in kg
M2 = 1.0 # mass of pendulum 2 in kg
def derivs(state, t):
dydx = np.zeros_like(state)
dydx[0] = state[1]
del_ = state[2] - state[0]
den1 = (M1 + M2)*L1 - M2*L1*cos(del_)*cos(del_)
dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_) +
M2*G*sin(state[2])*cos(del_) +
M2*L2*state[3]*state[3]*sin(del_) -
(M1 + M2)*G*sin(state[0]))/den1
dydx[2] = state[3]
den2 = (L2/L1)*den1
dydx[3] = (-M2*L2*state[3]*state[3]*sin(del_)*cos(del_) +
(M1 + M2)*G*sin(state[0])*cos(del_) -
(M1 + M2)*L1*state[1]*state[1]*sin(del_) -
(M1 + M2)*G*sin(state[2]))/den2
return dydx
# create a time array from 0..100 sampled at 0.05 second steps
dt = 0.05
t = np.arange(0.0, 20, dt)
# th1 and th2 are the initial angles (degrees)
# w10 and w20 are the initial angular velocities (degrees per second)
th1 = 120.0
w1 = 0.0
th2 = -10.0
w2 = 0.0
# initial state
state = np.radians([th1, w1, th2, w2])
# integrate your ODE using scipy.integrate.
y = integrate.odeint(derivs, state, t)
x1 = L1*sin(y[:, 0])
y1 = -L1*cos(y[:, 0])
x2 = L2*sin(y[:, 2]) + x1
y2 = -L2*cos(y[:, 2]) + y1
fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2))
ax.grid()
line, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
def init():
line.set_data([], [])
time_text.set_text('')
return line, time_text
def animate(i):
thisx = [0, x1[i], x2[i]]
thisy = [0, y1[i], y2[i]]
line.set_data(thisx, thisy)
time_text.set_text(time_template % (i*dt))
return line, time_text
ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)),
interval=25, blit=True, init_func=init)
#ani.save('double_pendulum.mp4', fps=15)
plt.show()
0707010001f96a000081a400001782000005de000000015689ead200000256000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/animation/simple_anim.py """
A simple example of an animated plot
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10.0)) # update the data
return line,
# Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
interval=25, blit=True)
plt.show()
0707010001f964000081a400001782000005de000000015689ead2000002fc000002600000050a00000000000000000000003600000000reloc/matplotlib/examples/animation/dynamic_image2.py #!/usr/bin/env python
"""
An animated image
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
# ims is a list of lists, each row is a list of artists to draw in the
# current frame; here we are just animating one artist, the image, in
# each frame
ims = []
for i in range(60):
x += np.pi / 15.
y += np.pi / 20.
im = plt.imshow(f(x, y), cmap='viridis', animated=True)
ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
repeat_delay=1000)
#ani.save('dynamic_images.mp4')
plt.show()
0707010001f960000081a400001782000005de000000015689ead20000049e000002600000050a00000000000000000000003c00000000reloc/matplotlib/examples/animation/basic_example_writer.py # Same as basic_example, but writes files using a single MovieWriter instance
# without putting on screen
# -*- noplot -*-
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_line(num, data, line):
line.set_data(data[..., :num])
return line,
# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
fig1 = plt.figure()
data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
interval=50, blit=True)
line_ani.save('lines.mp4', writer=writer)
fig2 = plt.figure()
x = np.arange(-9, 10)
y = np.arange(-9, 10).reshape(-1, 1)
base = np.hypot(x, y)
ims = []
for add in np.arange(15):
ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))
im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,
blit=True)
im_ani.save('im.mp4', writer=writer)
0707010001f965000081a400001782000005de000000015689ead2000006c6000002600000050a00000000000000000000003100000000reloc/matplotlib/examples/animation/histogram.py """
This example shows how to use a path patch to draw a bunch of
rectangles for an animated histogram
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.animation as animation
fig, ax = plt.subplots()
# histogram our data with numpy
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
nrects = len(left)
# here comes the tricky part -- we have to set up the vertex and path
# codes arrays using moveto, lineto and closepoly
# for each rect: 1 for the MOVETO, 3 for the LINETO, 1 for the
# CLOSEPOLY; the vert for the closepoly is ignored but we still need
# it to keep the codes aligned with the vertices
nverts = nrects*(1 + 3 + 1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom
barpath = path.Path(verts, codes)
patch = patches.PathPatch(
barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)
ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())
def animate(i):
# simulate new data coming in
data = np.random.randn(1000)
n, bins = np.histogram(data, 100)
top = bottom + n
verts[1::5, 1] = top
verts[2::5, 1] = top
return [patch, ]
ani = animation.FuncAnimation(fig, animate, 100, repeat=False, blit=True)
plt.show()
0707010001f96c000081a400001782000005de000000015689ead200000de1000002600000050a00000000000000000000003000000000reloc/matplotlib/examples/animation/subplots.py import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.animation as animation
# This example uses subclassing, but there is no reason that the proper
# function couldn't be set up and then use FuncAnimation. The code is long, but
# not really complex. The length is due solely to the fact that there are a
# total of 9 lines that need to be changed for the animation as well as 3
# subplots that need initial set up.
class SubplotAnimation(animation.TimedAnimation):
def __init__(self):
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 4)
self.t = np.linspace(0, 80, 400)
self.x = np.cos(2 * np.pi * self.t / 10.)
self.y = np.sin(2 * np.pi * self.t / 10.)
self.z = 10 * self.t
ax1.set_xlabel('x')
ax1.set_ylabel('y')
self.line1 = Line2D([], [], color='black')
self.line1a = Line2D([], [], color='red', linewidth=2)
self.line1e = Line2D(
[], [], color='red', marker='o', markeredgecolor='r')
ax1.add_line(self.line1)
ax1.add_line(self.line1a)
ax1.add_line(self.line1e)
ax1.set_xlim(-1, 1)
ax1.set_ylim(-2, 2)
ax1.set_aspect('equal', 'datalim')
ax2.set_xlabel('y')
ax2.set_ylabel('z')
self.line2 = Line2D([], [], color='black')
self.line2a = Line2D([], [], color='red', linewidth=2)
self.line2e = Line2D(
[], [], color='red', marker='o', markeredgecolor='r')
ax2.add_line(self.line2)
ax2.add_line(self.line2a)
ax2.add_line(self.line2e)
ax2.set_xlim(-1, 1)
ax2.set_ylim(0, 800)
ax3.set_xlabel('x')
ax3.set_ylabel('z')
self.line3 = Line2D([], [], color='black')
self.line3a = Line2D([], [], color='red', linewidth=2)
self.line3e = Line2D(
[], [], color='red', marker='o', markeredgecolor='r')
ax3.add_line(self.line3)
ax3.add_line(self.line3a)
ax3.add_line(self.line3e)
ax3.set_xlim(-1, 1)
ax3.set_ylim(0, 800)
animation.TimedAnimation.__init__(self, fig, interval=50, blit=True)
def _draw_frame(self, framedata):
i = framedata
head = i - 1
head_len = 10
head_slice = (self.t > self.t[i] - 1.0) & (self.t < self.t[i])
self.line1.set_data(self.x[:i], self.y[:i])
self.line1a.set_data(self.x[head_slice], self.y[head_slice])
self.line1e.set_data(self.x[head], self.y[head])
self.line2.set_data(self.y[:i], self.z[:i])
self.line2a.set_data(self.y[head_slice], self.z[head_slice])
self.line2e.set_data(self.y[head], self.z[head])
self.line3.set_data(self.x[:i], self.z[:i])
self.line3a.set_data(self.x[head_slice], self.z[head_slice])
self.line3e.set_data(self.x[head], self.z[head])
self._drawn_artists = [self.line1, self.line1a, self.line1e,
self.line2, self.line2a, self.line2e,
self.line3, self.line3a, self.line3e]
def new_frame_seq(self):
return iter(range(self.t.size))
def _init_draw(self):
lines = [self.line1, self.line1a, self.line1e,
self.line2, self.line2a, self.line2e,
self.line3, self.line3a, self.line3e]
for l in lines:
l.set_data([], [])
ani = SubplotAnimation()
#ani.save('test_sub.mp4')
plt.show()
0707010001f963000081a400001782000005de000000015689ead20000023a000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/animation/dynamic_image.py #!/usr/bin/env python
"""
An animated image
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
im = plt.imshow(f(x, y), cmap=plt.get_cmap('viridis'), animated=True)
def updatefig(*args):
global x, y
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
0707010001f95f000081a400001782000005de000000015689ead200000377000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/animation/basic_example.py import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_line(num, data, line):
line.set_data(data[..., :num])
return line,
fig1 = plt.figure()
data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
interval=50, blit=True)
#line_ani.save('lines.mp4')
fig2 = plt.figure()
x = np.arange(-9, 10)
y = np.arange(-9, 10).reshape(-1, 1)
base = np.hypot(x, y)
ims = []
for add in np.arange(15):
ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))
im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,
blit=True)
#im_ani.save('im.mp4', metadata={'artist':'Guido'})
plt.show()
0707010001f95e000081a400001782000005de000000015689ead20000036c000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/animation/animate_decay.py import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def data_gen(t=0):
cnt = 0
while cnt < 1000:
cnt += 1
t += 0.1
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
def init():
ax.set_ylim(-1.1, 1.1)
ax.set_xlim(0, 10)
del xdata[:]
del ydata[:]
line.set_data(xdata, ydata)
return line,
fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
ax.grid()
xdata, ydata = [], []
def run(data):
# update the data
t, y = data
xdata.append(t)
ydata.append(y)
xmin, xmax = ax.get_xlim()
if t >= xmax:
ax.set_xlim(xmin, 2*xmax)
ax.figure.canvas.draw()
line.set_data(xdata, ydata)
return line,
ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
repeat=False, init_func=init)
plt.show()
0707010001f968000081a400001782000005de000000015689ead20000017c000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/animation/random_data.py import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1)
def update(data):
line.set_ydata(data)
return line,
def data_gen():
while True:
yield np.random.rand(10)
ani = animation.FuncAnimation(fig, update, data_gen, interval=100)
plt.show()
0707010001f961000081a400001782000005de000000015689ead2000005bc000002600000050a00000000000000000000003400000000reloc/matplotlib/examples/animation/bayes_update.py # update a distribution based on new data.
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as ss
from matplotlib.animation import FuncAnimation
class UpdateDist(object):
def __init__(self, ax, prob=0.5):
self.success = 0
self.prob = prob
self.line, = ax.plot([], [], 'k-')
self.x = np.linspace(0, 1, 200)
self.ax = ax
# Set up plot parameters
self.ax.set_xlim(0, 1)
self.ax.set_ylim(0, 15)
self.ax.grid(True)
# This vertical line represents the theoretical value, to
# which the plotted distribution should converge.
self.ax.axvline(prob, linestyle='--', color='black')
def init(self):
self.success = 0
self.line.set_data([], [])
return self.line,
def __call__(self, i):
# This way the plot can continuously run and we just keep
# watching new realizations of the process
if i == 0:
return self.init()
# Choose success based on exceed a threshold with a uniform pick
if np.random.rand(1,) < self.prob:
self.success += 1
y = ss.beta.pdf(self.x, self.success + 1, (i - self.success) + 1)
self.line.set_data(self.x, y)
return self.line,
fig, ax = plt.subplots()
ud = UpdateDist(ax, prob=0.7)
anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init,
interval=100, blit=True)
plt.show()
0707010001f969000081a400001782000005de000000015689ead200000707000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/animation/simple_3danim.py """
A simple example of an animated plot... In 3D!
"""
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
def Gen_RandLine(length, dims=2):
"""
Create a line using a random walk algorithm
length is the number of points for the line.
dims is the number of dimensions the line has.
"""
lineData = np.empty((dims, length))
lineData[:, 0] = np.random.rand(dims)
for index in range(1, length):
# scaling the random numbers by 0.1 so
# movement is small compared to position.
# subtraction by 0.5 is to change the range to [-0.5, 0.5]
# to allow a line to move backwards.
step = ((np.random.rand(dims) - 0.5) * 0.1)
lineData[:, index] = lineData[:, index - 1] + step
return lineData
def update_lines(num, dataLines, lines):
for line, data in zip(lines, dataLines):
# NOTE: there is no .set_data() for 3 dim data...
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2, :num])
return lines
# Attaching 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)
# Fifty lines of random 3-D lines
data = [Gen_RandLine(25, 3) for index in range(50)]
# Creating fifty line objects.
# NOTE: Can't pass empty arrays into 3d version of plot()
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]
# Setting the axes properties
ax.set_xlim3d([0.0, 1.0])
ax.set_xlabel('X')
ax.set_ylim3d([0.0, 1.0])
ax.set_ylabel('Y')
ax.set_zlim3d([0.0, 1.0])
ax.set_zlabel('Z')
ax.set_title('3D Test')
# Creating the Animation object
line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines),
interval=50, blit=False)
plt.show()
0707010001f96d000081a400001782000005de000000015689ead200000742000002600000050a00000000000000000000003100000000reloc/matplotlib/examples/animation/unchained.py """
Comparative path demonstration of frequency from a fake signal of a pulsar.
(mostly known because of the cover for Joy Division's Unknown Pleasures)
Author: Nicolas P. Rougier
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Create new Figure with black background
fig = plt.figure(figsize=(8, 8), facecolor='black')
# Add a subplot with no frame
ax = plt.subplot(111, frameon=False)
# Generate random data
data = np.random.uniform(0, 1, (64, 75))
X = np.linspace(-1, 1, data.shape[-1])
G = 1.5 * np.exp(-4 * X * X)
# Generate line plots
lines = []
for i in range(len(data)):
# Small reduction of the X extents to get a cheap perspective effect
xscale = 1 - i / 200.
# Same for linewidth (thicker strokes on bottom)
lw = 1.5 - i / 100.0
line, = ax.plot(xscale * X, i + G * data[i], color="w", lw=lw)
lines.append(line)
# Set y limit (or first line is cropped because of thickness)
ax.set_ylim(-1, 70)
# No ticks
ax.set_xticks([])
ax.set_yticks([])
# 2 part titles to get different font weights
ax.text(0.5, 1.0, "MATPLOTLIB ", transform=ax.transAxes,
ha="right", va="bottom", color="w",
family="sans-serif", fontweight="light", fontsize=16)
ax.text(0.5, 1.0, "UNCHAINED", transform=ax.transAxes,
ha="left", va="bottom", color="w",
family="sans-serif", fontweight="bold", fontsize=16)
def update(*args):
# Shift all data to the right
data[:, 1:] = data[:, :-1]
# Fill-in new values
data[:, 0] = np.random.uniform(0, 1, len(data))
# Update data
for i in range(len(data)):
lines[i].set_ydata(i + G * data[i])
# Return modified artists
return lines
# Construct the animation, using the update function as the animation
# director.
anim = animation.FuncAnimation(fig, update, interval=10)
plt.show()
0707010001f96b000081a400001782000005de000000015689ead2000005e8000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/animation/strip_chart_demo.py """
Emulate an oscilloscope. Requires the animation API introduced in
matplotlib 1.0 SVN.
"""
import numpy as np
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class Scope(object):
def __init__(self, ax, maxt=2, dt=0.02):
self.ax = ax
self.dt = dt
self.maxt = maxt
self.tdata = [0]
self.ydata = [0]
self.line = Line2D(self.tdata, self.ydata)
self.ax.add_line(self.line)
self.ax.set_ylim(-.1, 1.1)
self.ax.set_xlim(0, self.maxt)
def update(self, y):
lastt = self.tdata[-1]
if lastt > self.tdata[0] + self.maxt: # reset the arrays
self.tdata = [self.tdata[-1]]
self.ydata = [self.ydata[-1]]
self.ax.set_xlim(self.tdata[0], self.tdata[0] + self.maxt)
self.ax.figure.canvas.draw()
t = self.tdata[-1] + self.dt
self.tdata.append(t)
self.ydata.append(y)
self.line.set_data(self.tdata, self.ydata)
return self.line,
def emitter(p=0.03):
'return a random value with probability p, else 0'
while True:
v = np.random.rand(1)
if v > p:
yield 0.
else:
yield np.random.rand(1)
fig, ax = plt.subplots()
scope = Scope(ax)
# pass a generator in "emitter" to produce data for the update func
ani = animation.FuncAnimation(fig, scope.update, emitter, interval=10,
blit=True)
plt.show()
0707010001f967000081a400001782000005de000000015689ead200000909000002600000050a00000000000000000000002c00000000reloc/matplotlib/examples/animation/rain.py """
Rain simulation
Simulates rain drops on a surface by animating the scale and opacity
of 50 scatter points.
Author: Nicolas P. Rougier
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(0, 1), ax.set_xticks([])
ax.set_ylim(0, 1), ax.set_yticks([])
# Create rain data
n_drops = 50
rain_drops = np.zeros(n_drops, dtype=[('position', float, 2),
('size', float, 1),
('growth', float, 1),
('color', float, 4)])
# Initialize the raindrops in random positions and with
# random growth rates.
rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))
rain_drops['growth'] = np.random.uniform(50, 200, n_drops)
# Construct the scatter which we will update during animation
# as the raindrops develop.
scat = ax.scatter(rain_drops['position'][:, 0], rain_drops['position'][:, 1],
s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],
facecolors='none')
def update(frame_number):
# Get an index which we can use to re-spawn the oldest raindrop.
current_index = frame_number % n_drops
# Make all colors more transparent as time progresses.
rain_drops['color'][:, 3] -= 1.0/len(rain_drops)
rain_drops['color'][:, 3] = np.clip(rain_drops['color'][:, 3], 0, 1)
# Make all circles bigger.
rain_drops['size'] += rain_drops['growth']
# Pick a new position for oldest rain drop, resetting its size,
# color and growth factor.
rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)
rain_drops['size'][current_index] = 5
rain_drops['color'][current_index] = (0, 0, 0, 1)
rain_drops['growth'][current_index] = np.random.uniform(50, 200)
# Update the scatter collection, with the new colors, sizes and positions.
scat.set_edgecolors(rain_drops['color'])
scat.set_sizes(rain_drops['size'])
scat.set_offsets(rain_drops['position'])
# Construct the animation, using the update function as the animation
# director.
animation = FuncAnimation(fig, update, interval=10)
plt.show()
0707010001faeb000041ed00001782000005de00000002570a54ff00000000000002600000050a00000000000000000000003100000000reloc/matplotlib/examples/shapes_and_collections 0707010001faec000081a400001782000005de000000015689ead200000b08000002600000050a00000000000000000000004500000000reloc/matplotlib/examples/shapes_and_collections/artist_reference.py """
Reference for matplotlib artists
This example displays several of matplotlib's graphics primitives (artists)
drawn using matplotlib API. A full list of artists and the documentation is
available at http://matplotlib.org/api/artist_api.html.
Copyright (c) 2010, Bartosz Telenczuk
BSD License
"""
import matplotlib.pyplot as plt
plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
def label(xy, text):
y = xy[1] - 0.15 # shift y-value for label so that it's below the artist
plt.text(xy[0], y, text, ha="center", family='sans-serif', size=14)
fig, ax = plt.subplots()
# create 3x3 grid to plot the artists
grid = np.mgrid[0.2:0.8:3j, 0.2:0.8:3j].reshape(2, -1).T
patches = []
# add a circle
circle = mpatches.Circle(grid[0], 0.1, ec="none")
patches.append(circle)
label(grid[0], "Circle")
# add a rectangle
rect = mpatches.Rectangle(grid[1] - [0.025, 0.05], 0.05, 0.1, ec="none")
patches.append(rect)
label(grid[1], "Rectangle")
# add a wedge
wedge = mpatches.Wedge(grid[2], 0.1, 30, 270, ec="none")
patches.append(wedge)
label(grid[2], "Wedge")
# add a Polygon
polygon = mpatches.RegularPolygon(grid[3], 5, 0.1)
patches.append(polygon)
label(grid[3], "Polygon")
# add an ellipse
ellipse = mpatches.Ellipse(grid[4], 0.2, 0.1)
patches.append(ellipse)
label(grid[4], "Ellipse")
# add an arrow
arrow = mpatches.Arrow(grid[5, 0] - 0.05, grid[5, 1] - 0.05, 0.1, 0.1, width=0.1)
patches.append(arrow)
label(grid[5], "Arrow")
# add a path patch
Path = mpath.Path
path_data = [
(Path.MOVETO, [0.018, -0.11]),
(Path.CURVE4, [-0.031, -0.051]),
(Path.CURVE4, [-0.115, 0.073]),
(Path.CURVE4, [-0.03 , 0.073]),
(Path.LINETO, [-0.011, 0.039]),
(Path.CURVE4, [0.043, 0.121]),
(Path.CURVE4, [0.075, -0.005]),
(Path.CURVE4, [0.035, -0.027]),
(Path.CLOSEPOLY, [0.018, -0.11])
]
codes, verts = zip(*path_data)
path = mpath.Path(verts + grid[6], codes)
patch = mpatches.PathPatch(path)
patches.append(patch)
label(grid[6], "PathPatch")
# add a fancy box
fancybox = mpatches.FancyBboxPatch(
grid[7] - [0.025, 0.05], 0.05, 0.1,
boxstyle=mpatches.BoxStyle("Round", pad=0.02))
patches.append(fancybox)
label(grid[7], "FancyBoxPatch")
# add a line
x, y = np.array([[-0.06, 0.0, 0.1], [0.05, -0.05, 0.05]])
line = mlines.Line2D(x + grid[8, 0], y + grid[8, 1], lw=5., alpha=0.3)
label(grid[8], "Line2D")
colors = np.linspace(0, 1, len(patches))
collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
collection.set_array(np.array(colors))
ax.add_collection(collection)
ax.add_line(line)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
plt.axis('equal')
plt.axis('off')
plt.show()
0707010001faee000081a400001782000005de000000015689ead20000012a000002600000050a00000000000000000000004100000000reloc/matplotlib/examples/shapes_and_collections/scatter_demo.py """
Simple demo of a scatter plot.
"""
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()
0707010001faed000081a400001782000005de0000000155f2504c0000030d000002600000050a00000000000000000000004400000000reloc/matplotlib/examples/shapes_and_collections/path_patch_demo.py """
Demo of a PathPatch object.
"""
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
Path = mpath.Path
path_data = [
(Path.MOVETO, (1.58, -2.57)),
(Path.CURVE4, (0.35, -1.1)),
(Path.CURVE4, (-1.75, 2.0)),
(Path.CURVE4, (0.375, 2.0)),
(Path.LINETO, (0.85, 1.15)),
(Path.CURVE4, (2.2, 3.2)),
(Path.CURVE4, (3, 0.05)),
(Path.CURVE4, (2.0, -0.5)),
(Path.CLOSEPOLY, (1.58, -2.57)),
]
codes, verts = zip(*path_data)
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5)
ax.add_patch(patch)
# plot control points and connecting lines
x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'go-')
ax.grid()
ax.axis('equal')
plt.show()
0707010001f95c000081a400001782000005de00000001569316c10000069f000002600000050a00000000000000000000002500000000reloc/matplotlib/examples/README.txt matplotlib examples
===================
There are a variety of ways to use matplotlib, and most of them are
illustrated in the examples in this directory.
Probably the most common way people use matplotlib is with the
procedural interface, which follows the matlab/IDL/mathematica
approach of using simple procedures like "plot" or "title" to modify
the current figure. These examples are included in the "pylab_examples"
directory. If you want to write more robust scripts, e.g., for
production use or in a web application server, you will probably want
to use the matplotlib API for full control. These examples are found
in the "api" directory. Below is a brief description of the different
directories found here:
* animation - dynamic plots, see the tutorial at
http://www.scipy.org/Cookbook/Matplotlib/Animations
* api - working with the matplotlib API directory.
* axes_grid - Examples related to the AxesGrid toolkit
* event_handling - how to interact with your figure, mouse presses,
key presses, object picking, etc.
* misc - some miscellaneous examples. some demos for loading and
working with record arrays
* mplot3d - 3D examples
* pylab_examples - the interface to matplotlib similar to matlab
* tests - tests used by matplotlib developers to check functionality
(These tests are still sometimes useful, but mostly developers should
use the nosetests which perform automatic image comparison.)
* units - working with unit data an custom types in matplotlib
* user_interfaces - using matplotlib in a GUI application, e.g.,
TkInter, WXPython, pygtk, pyqt or FLTK widgets
* widgets - Examples using interactive widgets
0707010001fae9000041ed00001782000005de00000002570a54ff00000000000002600000050a00000000000000000000002100000000reloc/matplotlib/examples/scales 0707010001faea000081a400001782000005de000000015689ead200000317000002600000050a00000000000000000000002b00000000reloc/matplotlib/examples/scales/scales.py """
Illustrate the scale transformations applied to axes, e.g. log, symlog, logit.
"""
import numpy as np
import matplotlib.pyplot as plt
# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
# plot with various axes scales
fig, axs = plt.subplots(2, 2)
# linear
ax = axs[0, 0]
ax.plot(x, y)
ax.set_yscale('linear')
ax.set_title('linear')
ax.grid(True)
# log
ax = axs[0, 1]
ax.plot(x, y)
ax.set_yscale('log')
ax.set_title('log')
ax.grid(True)
# symmetric log
ax = axs[1, 0]
ax.plot(x, y - y.mean())
ax.set_yscale('symlog', linthreshy=0.05)
ax.set_title('symlog')
ax.grid(True)
# logit
ax = axs[1, 1]
ax.plot(x, y)
ax.set_yscale('logit')
ax.set_title('logit')
ax.grid(True)
plt.show()
0707010001f9d2000041ed00001782000005de00000002570a54fe00000000000002600000050a00000000000000000000003100000000reloc/matplotlib/examples/lines_bars_and_markers 0707010001f9d8000081a400001782000005de000000015689e23900000378000002600000050a00000000000000000000004f00000000reloc/matplotlib/examples/lines_bars_and_markers/marker_fillstyle_reference.py """
Reference for marker fill-styles included with Matplotlib.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
points = np.ones(5) # Draw 3 points for each line
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontdict={'family': 'monospace'})
marker_style = dict(color='cornflowerblue', linestyle=':', marker='o',
markersize=15, markerfacecoloralt='gray')
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
def nice_repr(text):
return repr(text).lstrip('u')
fig, ax = plt.subplots()
# Plot all fill styles.
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, nice_repr(fill_style), **text_style)
ax.plot(y * points, fillstyle=fill_style, **marker_style)
format_axes(ax)
ax.set_title('fill style')
plt.show()
0707010001f9da000081a400001782000005de000000015689e23900000131000002600000050a00000000000000000000004800000000reloc/matplotlib/examples/lines_bars_and_markers/scatter_with_legend.py import matplotlib.pyplot as plt
from numpy.random import rand
for color in ['red', 'green', 'blue']:
n = 750
x, y = rand(2, n)
scale = 200.0 * rand(n)
plt.scatter(x, y, c=color, s=scale, label=color,
alpha=0.3, edgecolors='none')
plt.legend()
plt.grid(True)
plt.show()
0707010001f9d3000081a400001782000005de000000015689ead2000001ff000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/lines_bars_and_markers/barh_demo.py """
Simple demo of a horizontal bar chart.
"""
import matplotlib.pyplot as plt
plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))
plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)
plt.yticks(y_pos, people)
plt.xlabel('Performance')
plt.title('How fast do you want to go today?')
plt.show()
0707010001f9d9000081a400001782000005de000000015689ead2000007d3000002600000050a00000000000000000000004500000000reloc/matplotlib/examples/lines_bars_and_markers/marker_reference.py """
Reference for filled- and unfilled-marker types included with Matplotlib.
"""
from six import iteritems
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
points = np.ones(3) # Draw 3 points for each line
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontdict={'family': 'monospace'})
marker_style = dict(linestyle=':', color='cornflowerblue', markersize=10)
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
def nice_repr(text):
return repr(text).lstrip('u')
def split_list(a_list):
i_half = len(a_list) // 2
return (a_list[:i_half], a_list[i_half:])
# Plot all un-filled markers
# --------------------------
fig, axes = plt.subplots(ncols=2)
# Filter out filled markers and marker settings that do nothing.
# We use iteritems from six to make sure that we get an iterator
# in both python 2 and 3
unfilled_markers = [m for m, func in iteritems(Line2D.markers)
if func != 'nothing' and m not in Line2D.filled_markers]
# Reverse-sort for pretty. We use our own sort key which is essentially
# a python3 compatible reimplementation of python2 sort.
unfilled_markers = sorted(unfilled_markers,
key=lambda x: (str(type(x)), str(x)))[::-1]
for ax, markers in zip(axes, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, nice_repr(marker), **text_style)
ax.plot(y * points, marker=marker, **marker_style)
format_axes(ax)
fig.suptitle('un-filled markers', fontsize=14)
# Plot all filled markers.
# ------------------------
fig, axes = plt.subplots(ncols=2)
for ax, markers in zip(axes, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, nice_repr(marker), **text_style)
ax.plot(y * points, marker=marker, **marker_style)
format_axes(ax)
fig.suptitle('filled markers', fontsize=14)
plt.show()
0707010001f9d5000081a400001782000005de0000000155f2504c000001aa000002600000050a00000000000000000000004700000000reloc/matplotlib/examples/lines_bars_and_markers/fill_demo_features.py """
Demo of the fill function with a few features.
In addition to the basic fill plot, this demo shows a few optional features:
* Multiple curves with a single command.
* Setting the fill color.
* Setting the opacity (alpha value).
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x)
y2 = np.sin(3 * x)
plt.fill(x, y1, 'b', x, y2, 'r', alpha=0.3)
plt.show()
0707010001f9d6000081a400001782000005de000000015689ead20000018c000002600000050a00000000000000000000004b00000000reloc/matplotlib/examples/lines_bars_and_markers/line_demo_dash_control.py """
Demo of a simple plot with a custom dashed line.
A Line object's ``set_dashes`` method allows you to specify dashes with
a series of on/off lengths (in points).
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10)
line, = plt.plot(x, np.sin(x), '--', linewidth=2)
dashes = [10, 5, 100, 5] # 10 points on, 5 off, 100 on, 5 off
line.set_dashes(dashes)
plt.show()
0707010001f9d4000081a400001782000005de0000000155f2504c000000cf000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/lines_bars_and_markers/fill_demo.py """
Simple demo of the fill function.
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x)
plt.fill(x, y, 'r')
plt.grid(True)
plt.show()
0707010001f9d7000081a400001782000005de000000015689e23900000304000002600000050a00000000000000000000004a00000000reloc/matplotlib/examples/lines_bars_and_markers/line_styles_reference.py """
Reference for line-styles included with Matplotlib.
"""
import numpy as np
import matplotlib.pyplot as plt
color = 'cornflowerblue'
points = np.ones(5) # Draw 5 points for each line
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontdict={'family': 'monospace'})
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
def nice_repr(text):
return repr(text).lstrip('u')
# Plot all line styles.
f, ax = plt.subplots()
linestyles = ['-', '--', '-.', ':']
for y, linestyle in enumerate(linestyles):
ax.text(-0.5, y, nice_repr(linestyle), **text_style)
ax.plot(y * points, linestyle=linestyle, color=color, linewidth=3)
format_axes(ax)
ax.set_title('line styles')
plt.show()
0707010001fb15000041ed00001782000005de00000002570a550000000000000002600000050a00000000000000000000002b00000000reloc/matplotlib/examples/ticks_and_spines 0707010001fb19000081a400001782000005de000000015689ead2000003bb000002600000050a00000000000000000000004600000000reloc/matplotlib/examples/ticks_and_spines/tick_labels_from_values.py """
Basic demo showing how to set tick labels to values of a series.
Using ax.set_xticks causes the tick labels to be set on the currently
chosen ticks. However, you may want to allow matplotlib to dynamically
choose the number of ticks and their spacing.
In this case it may be better to determine the tick label from the
value at the tick. The following example shows how to do this.
NB: The MaxNLocator is used here to ensure that the tick values
take integer values.
"""
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, MaxNLocator
fig = plt.figure()
ax = fig.add_subplot(111)
xs = range(26)
ys = range(26)
labels = list('abcdefghijklmnopqrstuvwxyz')
def format_fn(tick_val, tick_pos):
if int(tick_val) in xs:
return labels[int(tick_val)]
else:
return ''
ax.xaxis.set_major_formatter(FuncFormatter(format_fn))
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.plot(xs, ys)
plt.show()
0707010001fb16000081a400001782000005de000000015689e239000002ea000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/ticks_and_spines/spines_demo.py """
Basic demo of axis spines.
This demo compares a normal axes, with spines on all four sides, and an axes
with spines only on the left and bottom.
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
y = 2 * np.sin(x)
fig, (ax0, ax1) = plt.subplots(nrows=2)
ax0.plot(x, y)
ax0.set_title('normal spines')
ax1.plot(x, y)
ax1.set_title('bottom-left spines')
# Hide the right and top spines
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax1.yaxis.set_ticks_position('left')
ax1.xaxis.set_ticks_position('bottom')
# Tweak spacing between subplots to prevent labels from overlapping
plt.subplots_adjust(hspace=0.5)
plt.show()
0707010001fb1a000081a400001782000005de0000000155f2504c000001ea000002600000050a00000000000000000000004700000000reloc/matplotlib/examples/ticks_and_spines/ticklabels_demo_rotation.py """
Demo of custom tick-labels with user-defined rotation.
"""
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']
plt.plot(x, y, 'ro')
# You can specify a rotation for the tick labels in degrees or with keywords.
plt.xticks(x, labels, rotation='vertical')
# Pad margins so that markers don't get clipped by the axes
plt.margins(0.2)
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)
plt.show()
0707010001fb17000081a400001782000005de000000015689ead200000317000002600000050a00000000000000000000004100000000reloc/matplotlib/examples/ticks_and_spines/spines_demo_bounds.py """
Demo of spines using custom bounds to limit the extent of the spine.
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 50)
y = np.sin(x)
y2 = y + 0.1 * np.random.normal(size=x.shape)
fig, ax = plt.subplots()
ax.plot(x, y, 'k--')
ax.plot(x, y2, 'ro')
# set ticks and tick labels
ax.set_xlim((0, 2*np.pi))
ax.set_xticks([0, np.pi, 2*np.pi])
ax.set_xticklabels(['0', '$\pi$', '2$\pi$'])
ax.set_ylim((-1.5, 1.5))
ax.set_yticks([-1, 0, 1])
# Only draw spine between the y-ticks
ax.spines['left'].set_bounds(-1, 1)
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plt.show()
0707010001fb18000081a400001782000005de0000000155f2504c000002a0000002600000050a00000000000000000000004200000000reloc/matplotlib/examples/ticks_and_spines/spines_demo_dropped.py """
Demo of spines offset from the axes (a.k.a. "dropped spines").
"""
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
image = np.random.uniform(size=(10, 10))
ax.imshow(image, cmap=plt.cm.gray, interpolation='nearest')
ax.set_title('dropped spines')
# Move left and bottom spines outward by 10 points
ax.spines['left'].set_position(('outward', 10))
ax.spines['bottom'].set_position(('outward', 10))
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plt.show()
0707010001f996000041ed00001782000005de00000002570a54fe00000000000002600000050a00000000000000000000002400000000reloc/matplotlib/examples/axes_grid 0707010001f9a2000081a400001782000005de00000001569316c100000844000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/axes_grid/demo_floating_axis.py """
An experimental support for curvilinear grid.
"""
def curvelinear_test2(fig):
"""
polar projection, but in a rectangular box.
"""
global ax1
import numpy as np
import mpl_toolkits.axisartist.angle_helper as angle_helper
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import SubplotHost
from mpl_toolkits.axisartist import GridHelperCurveLinear
# see demo_curvelinear_grid.py for details
tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
lon_cycle=360,
lat_cycle=None,
lon_minmax=None,
lat_minmax=(0, np.inf),
)
grid_locator1 = angle_helper.LocatorDMS(12)
tick_formatter1 = angle_helper.FormatterDMS()
grid_helper = GridHelperCurveLinear(tr,
extreme_finder=extreme_finder,
grid_locator1=grid_locator1,
tick_formatter1=tick_formatter1
)
ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
fig.add_subplot(ax1)
# Now creates floating axis
#grid_helper = ax1.get_grid_helper()
# floating axis whose first coordinate (theta) is fixed at 60
ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60)
axis.label.set_text(r"$\theta = 60^{\circ}$")
axis.label.set_visible(True)
# floating axis whose second coordinate (r) is fixed at 6
ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6)
axis.label.set_text(r"$r = 6$")
ax1.set_aspect(1.)
ax1.set_xlim(-5, 12)
ax1.set_ylim(-5, 10)
ax1.grid(True)
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(5, 5))
fig.clf()
curvelinear_test2(fig)
plt.show()
0707010001f99f000081a400001782000005de00000001569316c10000073b000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/axes_grid/demo_curvelinear_grid2.py import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.grid_helper_curvelinear import \
GridHelperCurveLinear
from mpl_toolkits.axes_grid.axislines import Subplot
import mpl_toolkits.axes_grid.angle_helper as angle_helper
def curvelinear_test1(fig):
"""
grid for custom transform.
"""
def tr(x, y):
sgn = np.sign(x)
x, y = np.abs(np.asarray(x)), np.asarray(y)
return sgn*x**.5, y
def inv_tr(x, y):
sgn = np.sign(x)
x, y = np.asarray(x), np.asarray(y)
return sgn*x**2, y
extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
lon_cycle=None,
lat_cycle=None,
# (0, np.inf),
lon_minmax=None,
lat_minmax=None,
)
grid_helper = GridHelperCurveLinear((tr, inv_tr),
extreme_finder=extreme_finder)
ax1 = Subplot(fig, 111, grid_helper=grid_helper)
# ax1 will have a ticks and gridlines defined by the given
# transform (+ transData of the Axes). Note that the transform of
# the Axes itself (i.e., transData) is not affected by the given
# transform.
fig.add_subplot(ax1)
ax1.imshow(np.arange(25).reshape(5, 5),
vmax=50, cmap=plt.cm.gray_r,
interpolation="nearest",
origin="lower")
# tick density
grid_helper.grid_finder.grid_locator1._nbins = 6
grid_helper.grid_finder.grid_locator2._nbins = 6
if 1:
fig = plt.figure(1, figsize=(7, 4))
fig.clf()
curvelinear_test1(fig)
plt.show()
0707010001f9ad000081a400001782000005de00000001569316c10000022e000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/axes_grid/simple_axisline4.py import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import numpy as np
ax = host_subplot(111, axes_class=AA.Axes)
xx = np.arange(0, 2*np.pi, 0.01)
ax.plot(xx, np.sin(xx))
ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis
ax2.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi])
ax2.set_xticklabels(["$0$", r"$\frac{1}{2}\pi$",
r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"])
ax2.axis["right"].major_ticklabels.set_visible(False)
plt.draw()
plt.show()
0707010001f9a7000081a400001782000005de00000001569316c1000006a4000002600000050a00000000000000000000004b00000000reloc/matplotlib/examples/axes_grid/make_room_for_ylabel_using_axesgrid.py from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable
if __name__ == "__main__":
import matplotlib.pyplot as plt
def ex1():
plt.figure(1)
ax = plt.axes([0, 0, 1, 1])
#ax = plt.subplot(111)
ax.set_yticks([0.5])
ax.set_yticklabels(["very long label"])
make_axes_area_auto_adjustable(ax)
def ex2():
plt.figure(2)
ax1 = plt.axes([0, 0, 1, 0.5])
ax2 = plt.axes([0, 0.5, 1, 0.5])
ax1.set_yticks([0.5])
ax1.set_yticklabels(["very long label"])
ax1.set_ylabel("Y label")
ax2.set_title("Title")
make_axes_area_auto_adjustable(ax1, pad=0.1, use_axes=[ax1, ax2])
make_axes_area_auto_adjustable(ax2, pad=0.1, use_axes=[ax1, ax2])
def ex3():
fig = plt.figure(3)
ax1 = plt.axes([0, 0, 1, 1])
divider = make_axes_locatable(ax1)
ax2 = divider.new_horizontal("100%", pad=0.3, sharey=ax1)
ax2.tick_params(labelleft="off")
fig.add_axes(ax2)
divider.add_auto_adjustable_area(use_axes=[ax1], pad=0.1,
adjust_dirs=["left"])
divider.add_auto_adjustable_area(use_axes=[ax2], pad=0.1,
adjust_dirs=["right"])
divider.add_auto_adjustable_area(use_axes=[ax1, ax2], pad=0.1,
adjust_dirs=["top", "bottom"])
ax1.set_yticks([0.5])
ax1.set_yticklabels(["very long label"])
ax2.set_title("Title")
ax2.set_xlabel("X - Label")
ex1()
ex2()
ex3()
plt.show()
0707010001f99b000081a400001782000005de00000001569316c100000737000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/axes_grid/demo_axes_rgb.py import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_rgb import make_rgb_axes, RGBAxes
def get_demo_image():
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
def get_rgb():
Z, extent = get_demo_image()
Z[Z < 0] = 0.
Z = Z/Z.max()
R = Z[:13, :13]
G = Z[2:, 2:]
B = Z[:13, 2:]
return R, G, B
def make_cube(r, g, b):
ny, nx = r.shape
R = np.zeros([ny, nx, 3], dtype="d")
R[:, :, 0] = r
G = np.zeros_like(R)
G[:, :, 1] = g
B = np.zeros_like(R)
B[:, :, 2] = b
RGB = R + G + B
return R, G, B, RGB
def demo_rgb():
fig, ax = plt.subplots()
ax_r, ax_g, ax_b = make_rgb_axes(ax, pad=0.02)
#fig.add_axes(ax_r)
#fig.add_axes(ax_g)
#fig.add_axes(ax_b)
r, g, b = get_rgb()
im_r, im_g, im_b, im_rgb = make_cube(r, g, b)
kwargs = dict(origin="lower", interpolation="nearest")
ax.imshow(im_rgb, **kwargs)
ax_r.imshow(im_r, **kwargs)
ax_g.imshow(im_g, **kwargs)
ax_b.imshow(im_b, **kwargs)
def demo_rgb2():
fig = plt.figure(2)
ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8], pad=0.0)
#fig.add_axes(ax)
#ax.add_RGB_to_figure()
r, g, b = get_rgb()
kwargs = dict(origin="lower", interpolation="nearest")
ax.imshow_rgb(r, g, b, **kwargs)
ax.RGB.set_xlim(0., 9.5)
ax.RGB.set_ylim(0.9, 10.6)
for ax1 in [ax.RGB, ax.R, ax.G, ax.B]:
for sp1 in ax1.spines.values():
sp1.set_color("w")
for tick in ax1.xaxis.get_major_ticks() + ax1.yaxis.get_major_ticks():
tick.tick1line.set_mec("w")
tick.tick2line.set_mec("w")
return ax
demo_rgb()
ax = demo_rgb2()
plt.show()
0707010001f9a5000081a400001782000005de00000001569316c1000003e6000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/axes_grid/inset_locator_demo.py import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
def add_sizebar(ax, size):
asb = AnchoredSizeBar(ax.transData,
size,
str(size),
loc=8,
pad=0.1, borderpad=0.5, sep=5,
frameon=False)
ax.add_artist(asb)
fig, (ax, ax2) = plt.subplots(1, 2, figsize=[5.5, 3])
# first subplot
ax.set_aspect(1.)
axins = inset_axes(ax,
width="30%", # width = 30% of parent_bbox
height=1., # height : 1 inch
loc=3)
plt.xticks(visible=False)
plt.yticks(visible=False)
# second subplot
ax2.set_aspect(1.)
axins = zoomed_inset_axes(ax2, 0.5, loc=1) # zoom = 0.5
plt.xticks(visible=False)
plt.yticks(visible=False)
add_sizebar(ax2, 0.5)
add_sizebar(axins, 0.5)
plt.draw()
plt.show()
0707010001f99d000081a400001782000005de00000001569316c10000042c000002600000050a00000000000000000000004800000000reloc/matplotlib/examples/axes_grid/demo_colorbar_with_inset_locator.py import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=[6, 3])
axins1 = inset_axes(ax1,
width="50%", # width = 10% of parent_bbox width
height="5%", # height : 50%
loc=1)
im1 = ax1.imshow([[1, 2], [2, 3]])
plt.colorbar(im1, cax=axins1, orientation="horizontal", ticks=[1, 2, 3])
axins1.xaxis.set_ticks_position("bottom")
axins = inset_axes(ax2,
width="5%", # width = 10% of parent_bbox width
height="50%", # height : 50%
loc=3,
bbox_to_anchor=(1.05, 0., 1, 1),
bbox_transform=ax2.transAxes,
borderpad=0,
)
# Controlling the placement of the inset axes is basically same as that
# of the legend. you may want to play with the borderpad value and
# the bbox_to_anchor coordinate.
im = ax2.imshow([[1, 2], [2, 3]])
plt.colorbar(im, cax=axins, ticks=[1, 2, 3])
plt.draw()
plt.show()
0707010001f9ab000081a400001782000005de00000001569316c1000001d3000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/axes_grid/simple_axesgrid.py import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
im = np.arange(100)
im.shape = 10, 10
fig = plt.figure(1, (4., 4.))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(2, 2), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
for i in range(4):
grid[i].imshow(im) # The AxesGrid object work as a list of axes.
plt.show()
0707010001f9a4000081a400001782000005de00000001569316c1000004ae000002600000050a00000000000000000000003b00000000reloc/matplotlib/examples/axes_grid/demo_parasite_axes2.py from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt
if 1:
host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
axes=par2,
offset=(offset, 0))
par2.axis["right"].toggle(all=True)
host.set_xlim(0, 2)
host.set_ylim(0, 2)
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
host.legend()
host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())
plt.draw()
plt.show()
#plt.savefig("Test")
0707010001f9a9000081a400001782000005de00000001569316c100000616000002600000050a00000000000000000000003400000000reloc/matplotlib/examples/axes_grid/scatter_hist.py import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)
fig, axScatter = plt.subplots(figsize=(5.5, 5.5))
# the scatter plot:
axScatter.scatter(x, y)
axScatter.set_aspect(1.)
# create new axes on the right and on the top of the current axes
# The first argument of the new_vertical(new_horizontal) method is
# the height (width) of the axes to be created in inches.
divider = make_axes_locatable(axScatter)
axHistx = divider.append_axes("top", 1.2, pad=0.1, sharex=axScatter)
axHisty = divider.append_axes("right", 1.2, pad=0.1, sharey=axScatter)
# make some labels invisible
plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(),
visible=False)
# now determine nice limits by hand:
binwidth = 0.25
xymax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))])
lim = (int(xymax/binwidth) + 1)*binwidth
bins = np.arange(-lim, lim + binwidth, binwidth)
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')
# the xaxis of axHistx and yaxis of axHisty are shared with axScatter,
# thus there is no need to manually adjust the xlim and ylim of these
# axis.
#axHistx.axis["bottom"].major_ticklabels.set_visible(False)
for tl in axHistx.get_xticklabels():
tl.set_visible(False)
axHistx.set_yticks([0, 50, 100])
#axHisty.axis["left"].major_ticklabels.set_visible(False)
for tl in axHisty.get_yticklabels():
tl.set_visible(False)
axHisty.set_xticks([0, 50, 100])
plt.draw()
plt.show()
0707010001f9ac000081a400001782000005de00000001569316c100000358000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/axes_grid/simple_axesgrid2.py import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
def get_demo_image():
import numpy as np
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
F = plt.figure(1, (5.5, 3.5))
grid = ImageGrid(F, 111, # similar to subplot(111)
nrows_ncols=(1, 3),
axes_pad=0.1,
add_all=True,
label_mode="L",
)
Z, extent = get_demo_image() # demo image
im1 = Z
im2 = Z[:, :10]
im3 = Z[:, 10:]
vmin, vmax = Z.min(), Z.max()
for i, im in enumerate([im1, im2, im3]):
ax = grid[i]
ax.imshow(im, origin="lower", vmin=vmin,
vmax=vmax, interpolation="nearest")
plt.draw()
plt.show()
0707010001f999000081a400001782000005de00000001569316c100000da0000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/axes_grid/demo_axes_grid2.py import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
def get_demo_image():
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
def add_inner_title(ax, title, loc, size=None, **kwargs):
from matplotlib.offsetbox import AnchoredText
from matplotlib.patheffects import withStroke
if size is None:
size = dict(size=plt.rcParams['legend.fontsize'])
at = AnchoredText(title, loc=loc, prop=size,
pad=0., borderpad=0.5,
frameon=False, **kwargs)
ax.add_artist(at)
at.txt._text.set_path_effects([withStroke(foreground="w", linewidth=3)])
return at
if 1:
F = plt.figure(1, (6, 6))
F.clf()
# prepare images
Z, extent = get_demo_image()
ZS = [Z[i::3, :] for i in range(3)]
extent = extent[0], extent[1]/3., extent[2], extent[3]
# demo 1 : colorbar at each axes
grid = ImageGrid(F, 211, # similar to subplot(111)
nrows_ncols=(1, 3),
direction="row",
axes_pad=0.05,
add_all=True,
label_mode="1",
share_all=True,
cbar_location="top",
cbar_mode="each",
cbar_size="7%",
cbar_pad="1%",
)
for ax, z in zip(grid, ZS):
im = ax.imshow(
z, origin="lower", extent=extent, interpolation="nearest")
ax.cax.colorbar(im)
for ax, im_title in zip(grid, ["Image 1", "Image 2", "Image 3"]):
t = add_inner_title(ax, im_title, loc=3)
t.patch.set_alpha(0.5)
for ax, z in zip(grid, ZS):
ax.cax.toggle_label(True)
#axis = ax.cax.axis[ax.cax.orientation]
#axis.label.set_text("counts s$^{-1}$")
#axis.label.set_size(10)
#axis.major_ticklabels.set_size(6)
# changing the colorbar ticks
grid[1].cax.set_xticks([-1, 0, 1])
grid[2].cax.set_xticks([-1, 0, 1])
grid[0].set_xticks([-2, 0])
grid[0].set_yticks([-2, 0, 2])
# demo 2 : shared colorbar
grid2 = ImageGrid(F, 212,
nrows_ncols=(1, 3),
direction="row",
axes_pad=0.05,
add_all=True,
label_mode="1",
share_all=True,
cbar_location="right",
cbar_mode="single",
cbar_size="10%",
cbar_pad=0.05,
)
grid2[0].set_xlabel("X")
grid2[0].set_ylabel("Y")
vmax, vmin = np.max(ZS), np.min(ZS)
import matplotlib.colors
norm = matplotlib.colors.Normalize(vmax=vmax, vmin=vmin)
for ax, z in zip(grid2, ZS):
im = ax.imshow(z, norm=norm,
origin="lower", extent=extent,
interpolation="nearest")
# With cbar_mode="single", cax attribute of all axes are identical.
ax.cax.colorbar(im)
ax.cax.toggle_label(True)
for ax, im_title in zip(grid2, ["(a)", "(b)", "(c)"]):
t = add_inner_title(ax, im_title, loc=2)
t.patch.set_ec("none")
t.patch.set_alpha(0.5)
grid2[0].set_xticks([-2, 0])
grid2[0].set_yticks([-2, 0, 2])
plt.draw()
plt.show()
0707010001f9a8000081a400001782000005de00000001569316c1000004e3000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/axes_grid/parasite_simple2.py import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
obs = [["01_S1", 3.88, 0.14, 1970, 63],
["01_S4", 5.6, 0.82, 1622, 150],
["02_S1", 2.4, 0.54, 1570, 40],
["03_S1", 4.1, 0.62, 2380, 170]]
fig = plt.figure()
ax_kms = SubplotHost(fig, 1, 1, 1, aspect=1.)
# angular proper motion("/yr) to linear velocity(km/s) at distance=2.3kpc
pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5
aux_trans = mtransforms.Affine2D().scale(pm_to_kms, 1.)
ax_pm = ax_kms.twin(aux_trans)
ax_pm.set_viewlim_mode("transform")
fig.add_subplot(ax_kms)
for n, ds, dse, w, we in obs:
time = ((2007 + (10. + 4/30.)/12) - 1988.5)
v = ds / time * pm_to_kms
ve = dse / time * pm_to_kms
ax_kms.errorbar([v], [w], xerr=[ve], yerr=[we], color="k")
ax_kms.axis["bottom"].set_label("Linear velocity at 2.3 kpc [km/s]")
ax_kms.axis["left"].set_label("FWHM [km/s]")
ax_pm.axis["top"].set_label("Proper Motion [$^{''}$/yr]")
ax_pm.axis["top"].label.set_visible(True)
ax_pm.axis["right"].major_ticklabels.set_visible(False)
ax_kms.set_xlim(950, 3700)
ax_kms.set_ylim(950, 3100)
# xlim and ylim of ax_pms will be automatically adjusted.
plt.draw()
plt.show()
0707010001f9aa000081a400001782000005de00000001569316c10000079f000002600000050a00000000000000000000003f00000000reloc/matplotlib/examples/axes_grid/simple_anchored_artists.py import matplotlib.pyplot as plt
def draw_text(ax):
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredText
at = AnchoredText("Figure 1a",
loc=2, prop=dict(size=8), frameon=True,
)
at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at)
at2 = AnchoredText("Figure 1(b)",
loc=3, prop=dict(size=8), frameon=True,
bbox_to_anchor=(0., 1.),
bbox_transform=ax.transAxes
)
at2.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at2)
def draw_circle(ax): # circle in the canvas coordinate
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea
from matplotlib.patches import Circle
ada = AnchoredDrawingArea(20, 20, 0, 0,
loc=1, pad=0., frameon=False)
p = Circle((10, 10), 10)
ada.da.add_artist(p)
ax.add_artist(ada)
def draw_ellipse(ax):
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredEllipse
# draw an ellipse of width=0.1, height=0.15 in the data coordinate
ae = AnchoredEllipse(ax.transData, width=0.1, height=0.15, angle=0.,
loc=3, pad=0.5, borderpad=0.4, frameon=True)
ax.add_artist(ae)
def draw_sizebar(ax):
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
# draw a horizontal bar with length of 0.1 in Data coordinate
# (ax.transData) with a label underneath.
asb = AnchoredSizeBar(ax.transData,
0.1,
r"1$^{\prime}$",
loc=8,
pad=0.1, borderpad=0.5, sep=5,
frameon=False)
ax.add_artist(asb)
if 1:
ax = plt.gca()
ax.set_aspect(1.)
draw_text(ax)
draw_circle(ax)
draw_ellipse(ax)
draw_sizebar(ax)
plt.show()
0707010001f998000081a400001782000005de00000001569316c100000f90000002600000050a00000000000000000000003600000000reloc/matplotlib/examples/axes_grid/demo_axes_grid.py import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid
def get_demo_image():
import numpy as np
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
def demo_simple_grid(fig):
"""
A grid of 2x2 images with 0.05 inch pad between images and only
the lower-left axes is labeled.
"""
grid = AxesGrid(fig, 141, # similar to subplot(141)
nrows_ncols=(2, 2),
axes_pad=0.05,
label_mode="1",
)
Z, extent = get_demo_image()
for i in range(4):
im = grid[i].imshow(Z, extent=extent, interpolation="nearest")
# This only affects axes in first column and second row as share_all =
# False.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
def demo_grid_with_single_cbar(fig):
"""
A grid of 2x2 images with a single colorbar
"""
grid = AxesGrid(fig, 142, # similar to subplot(142)
nrows_ncols=(2, 2),
axes_pad=0.0,
share_all=True,
label_mode="L",
cbar_location="top",
cbar_mode="single",
)
Z, extent = get_demo_image()
for i in range(4):
im = grid[i].imshow(Z, extent=extent, interpolation="nearest")
#plt.colorbar(im, cax = grid.cbar_axes[0])
grid.cbar_axes[0].colorbar(im)
for cax in grid.cbar_axes:
cax.toggle_label(False)
# This affects all axes as share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
def demo_grid_with_each_cbar(fig):
"""
A grid of 2x2 images. Each image has its own colorbar.
"""
grid = AxesGrid(fig, 143, # similar to subplot(143)
nrows_ncols=(2, 2),
axes_pad=0.1,
label_mode="1",
share_all=True,
cbar_location="top",
cbar_mode="each",
cbar_size="7%",
cbar_pad="2%",
)
Z, extent = get_demo_image()
for i in range(4):
im = grid[i].imshow(Z, extent=extent, interpolation="nearest")
grid.cbar_axes[i].colorbar(im)
for cax in grid.cbar_axes:
cax.toggle_label(False)
# This affects all axes because we set share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
def demo_grid_with_each_cbar_labelled(fig):
"""
A grid of 2x2 images. Each image has its own colorbar.
"""
grid = AxesGrid(fig, 144, # similar to subplot(144)
nrows_ncols=(2, 2),
axes_pad=(0.45, 0.15),
label_mode="1",
share_all=True,
cbar_location="right",
cbar_mode="each",
cbar_size="7%",
cbar_pad="2%",
)
Z, extent = get_demo_image()
# Use a different colorbar range every time
limits = ((0, 1), (-2, 2), (-1.7, 1.4), (-1.5, 1))
for i in range(4):
im = grid[i].imshow(Z, extent=extent, interpolation="nearest",
vmin=limits[i][0], vmax=limits[i][1])
grid.cbar_axes[i].colorbar(im)
for i, cax in enumerate(grid.cbar_axes):
cax.set_yticks((limits[i][0], limits[i][1]))
# This affects all axes because we set share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
if 1:
F = plt.figure(1, (10.5, 2.5))
F.subplots_adjust(left=0.05, right=0.95)
demo_simple_grid(F)
demo_grid_with_single_cbar(F)
demo_grid_with_each_cbar(F)
demo_grid_with_each_cbar_labelled(F)
plt.draw()
plt.show()
0707010001f99e000081a400001782000005de00000001569316c100000ff3000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/axes_grid/demo_curvelinear_grid.py import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from mpl_toolkits.axisartist import Subplot
from mpl_toolkits.axisartist import SubplotHost, \
ParasiteAxesAuxTrans
from mpl_toolkits.axisartist.grid_helper_curvelinear import \
GridHelperCurveLinear
def curvelinear_test1(fig):
"""
grid for custom transform.
"""
def tr(x, y):
x, y = np.asarray(x), np.asarray(y)
return x, y - x
def inv_tr(x, y):
x, y = np.asarray(x), np.asarray(y)
return x, y + x
grid_helper = GridHelperCurveLinear((tr, inv_tr))
ax1 = Subplot(fig, 1, 2, 1, grid_helper=grid_helper)
# ax1 will have a ticks and gridlines defined by the given
# transform (+ transData of the Axes). Note that the transform of
# the Axes itself (i.e., transData) is not affected by the given
# transform.
fig.add_subplot(ax1)
xx, yy = tr([3, 6], [5.0, 10.])
ax1.plot(xx, yy)
ax1.set_aspect(1.)
ax1.set_xlim(0, 10.)
ax1.set_ylim(0, 10.)
ax1.axis["t"] = ax1.new_floating_axis(0, 3.)
ax1.axis["t2"] = ax1.new_floating_axis(1, 7.)
ax1.grid(True)
import mpl_toolkits.axisartist.angle_helper as angle_helper
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
def curvelinear_test2(fig):
"""
polar projection, but in a rectangular box.
"""
# PolarAxes.PolarTransform takes radian. However, we want our coordinate
# system in degree
tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
# polar projection, which involves cycle, and also has limits in
# its coordinates, needs a special method to find the extremes
# (min, max of the coordinate within the view).
# 20, 20 : number of sampling points along x, y direction
extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
lon_cycle=360,
lat_cycle=None,
lon_minmax=None,
lat_minmax=(0, np.inf),
)
grid_locator1 = angle_helper.LocatorDMS(12)
# Find a grid values appropriate for the coordinate (degree,
# minute, second).
tick_formatter1 = angle_helper.FormatterDMS()
# And also uses an appropriate formatter. Note that,the
# acceptable Locator and Formatter class is a bit different than
# that of mpl's, and you cannot directly use mpl's Locator and
# Formatter here (but may be possible in the future).
grid_helper = GridHelperCurveLinear(tr,
extreme_finder=extreme_finder,
grid_locator1=grid_locator1,
tick_formatter1=tick_formatter1
)
ax1 = SubplotHost(fig, 1, 2, 2, grid_helper=grid_helper)
# make ticklabels of right and top axis visible.
ax1.axis["right"].major_ticklabels.set_visible(True)
ax1.axis["top"].major_ticklabels.set_visible(True)
# let right axis shows ticklabels for 1st coordinate (angle)
ax1.axis["right"].get_helper().nth_coord_ticks = 0
# let bottom axis shows ticklabels for 2nd coordinate (radius)
ax1.axis["bottom"].get_helper().nth_coord_ticks = 1
fig.add_subplot(ax1)
# A parasite axes with given transform
ax2 = ParasiteAxesAuxTrans(ax1, tr, "equal")
# note that ax2.transData == tr + ax1.transData
# Anthing you draw in ax2 will match the ticks and grids of ax1.
ax1.parasites.append(ax2)
intp = cbook.simple_linear_interpolation
ax2.plot(intp(np.array([0, 30]), 50),
intp(np.array([10., 10.]), 50))
ax1.set_aspect(1.)
ax1.set_xlim(-5, 12)
ax1.set_ylim(-5, 10)
ax1.grid(True)
if 1:
fig = plt.figure(1, figsize=(7, 4))
fig.clf()
curvelinear_test1(fig)
curvelinear_test2(fig)
plt.draw()
plt.show()
0707010001f99a000081a400001782000005de00000001569316c1000005ff000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/axes_grid/demo_axes_hbox_divider.py import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_divider import HBoxDivider
import mpl_toolkits.axes_grid1.axes_size as Size
def make_heights_equal(fig, rect, ax1, ax2, pad):
# pad in inches
h1, v1 = Size.AxesX(ax1), Size.AxesY(ax1)
h2, v2 = Size.AxesX(ax2), Size.AxesY(ax2)
pad_v = Size.Scaled(1)
pad_h = Size.Fixed(pad)
my_divider = HBoxDivider(fig, rect,
horizontal=[h1, pad_h, h2],
vertical=[v1, pad_v, v2])
ax1.set_axes_locator(my_divider.new_locator(0))
ax2.set_axes_locator(my_divider.new_locator(2))
if __name__ == "__main__":
arr1 = np.arange(20).reshape((4, 5))
arr2 = np.arange(20).reshape((5, 4))
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(arr1, interpolation="nearest")
ax2.imshow(arr2, interpolation="nearest")
rect = 111 # subplot param for combined axes
make_heights_equal(fig, rect, ax1, ax2, pad=0.5) # pad in inches
for ax in [ax1, ax2]:
ax.locator_params(nbins=4)
# annotate
ax3 = plt.axes([0.5, 0.5, 0.001, 0.001], frameon=False)
ax3.xaxis.set_visible(False)
ax3.yaxis.set_visible(False)
ax3.annotate("Location of two axes are adjusted\n"
"so that they have equal heights\n"
"while maintaining their aspect ratios", (0.5, 0.5),
xycoords="axes fraction", va="center", ha="center",
bbox=dict(boxstyle="round, pad=1", fc="w"))
plt.show()
0707010001f99c000081a400001782000005de00000001569316c10000020b000002600000050a00000000000000000000003b00000000reloc/matplotlib/examples/axes_grid/demo_axisline_style.py
from mpl_toolkits.axes_grid.axislines import SubplotZero
import matplotlib.pyplot as plt
import numpy as np
if 1:
fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
for direction in ["xzero", "yzero"]:
ax.axis[direction].set_axisline_style("-|>")
ax.axis[direction].set_visible(True)
for direction in ["left", "right", "bottom", "top"]:
ax.axis[direction].set_visible(False)
x = np.linspace(-0.5, 1., 100)
ax.plot(x, np.sin(x*np.pi))
plt.show()
0707010001f9a6000081a400001782000005de00000001569316c1000004e0000002600000050a00000000000000000000003b00000000reloc/matplotlib/examples/axes_grid/inset_locator_demo2.py import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
import numpy as np
def get_demo_image():
from matplotlib.cbook import get_sample_data
import numpy as np
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
fig, ax = plt.subplots(figsize=[5, 4])
# prepare the demo image
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30 + ny, 30:30 + nx] = Z
# extent = [-3, 4, -4, 3]
ax.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
axins.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)
# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.show()
0707010001f9a1000081a400001782000005de00000001569316c1000010fb000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/axes_grid/demo_floating_axes.py from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist.floating_axes as floating_axes
import numpy as np
import mpl_toolkits.axisartist.angle_helper as angle_helper
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist.grid_finder import (FixedLocator, MaxNLocator,
DictFormatter)
import matplotlib.pyplot as plt
def setup_axes1(fig, rect):
"""
A simple one.
"""
tr = Affine2D().scale(2, 1).rotate_deg(30)
grid_helper = floating_axes.GridHelperCurveLinear(
tr, extremes=(0, 4, 0, 4))
ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
fig.add_subplot(ax1)
aux_ax = ax1.get_aux_axes(tr)
grid_helper.grid_finder.grid_locator1._nbins = 4
grid_helper.grid_finder.grid_locator2._nbins = 4
return ax1, aux_ax
def setup_axes2(fig, rect):
"""
With custom locator and formatter.
Note that the extreme values are swapped.
"""
tr = PolarAxes.PolarTransform()
pi = np.pi
angle_ticks = [(0, r"$0$"),
(.25*pi, r"$\frac{1}{4}\pi$"),
(.5*pi, r"$\frac{1}{2}\pi$")]
grid_locator1 = FixedLocator([v for v, s in angle_ticks])
tick_formatter1 = DictFormatter(dict(angle_ticks))
grid_locator2 = MaxNLocator(2)
grid_helper = floating_axes.GridHelperCurveLinear(
tr, extremes=(.5*pi, 0, 2, 1),
grid_locator1=grid_locator1,
grid_locator2=grid_locator2,
tick_formatter1=tick_formatter1,
tick_formatter2=None)
ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
fig.add_subplot(ax1)
# create a parasite axes whose transData in RA, cz
aux_ax = ax1.get_aux_axes(tr)
aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax
ax1.patch.zorder = 0.9 # but this has a side effect that the patch is
# drawn twice, and possibly over some other
# artists. So, we decrease the zorder a bit to
# prevent this.
return ax1, aux_ax
def setup_axes3(fig, rect):
"""
Sometimes, things like axis_direction need to be adjusted.
"""
# rotate a bit for better orientation
tr_rotate = Affine2D().translate(-95, 0)
# scale degree to radians
tr_scale = Affine2D().scale(np.pi/180., 1.)
tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()
grid_locator1 = angle_helper.LocatorHMS(4)
tick_formatter1 = angle_helper.FormatterHMS()
grid_locator2 = MaxNLocator(3)
ra0, ra1 = 8.*15, 14.*15
cz0, cz1 = 0, 14000
grid_helper = floating_axes.GridHelperCurveLinear(
tr, extremes=(ra0, ra1, cz0, cz1),
grid_locator1=grid_locator1,
grid_locator2=grid_locator2,
tick_formatter1=tick_formatter1,
tick_formatter2=None)
ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
fig.add_subplot(ax1)
# adjust axis
ax1.axis["left"].set_axis_direction("bottom")
ax1.axis["right"].set_axis_direction("top")
ax1.axis["bottom"].set_visible(False)
ax1.axis["top"].set_axis_direction("bottom")
ax1.axis["top"].toggle(ticklabels=True, label=True)
ax1.axis["top"].major_ticklabels.set_axis_direction("top")
ax1.axis["top"].label.set_axis_direction("top")
ax1.axis["left"].label.set_text(r"cz [km$^{-1}$]")
ax1.axis["top"].label.set_text(r"$\alpha_{1950}$")
# create a parasite axes whose transData in RA, cz
aux_ax = ax1.get_aux_axes(tr)
aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax
ax1.patch.zorder = 0.9 # but this has a side effect that the patch is
# drawn twice, and possibly over some other
# artists. So, we decrease the zorder a bit to
# prevent this.
return ax1, aux_ax
##########################################################
fig = plt.figure(1, figsize=(8, 4))
fig.subplots_adjust(wspace=0.3, left=0.05, right=0.95)
ax1, aux_ax1 = setup_axes1(fig, 131)
aux_ax1.bar([0, 1, 2, 3], [3, 2, 1, 3])
ax2, aux_ax2 = setup_axes2(fig, 132)
theta = np.random.rand(10)*.5*np.pi
radius = np.random.rand(10) + 1.
aux_ax2.scatter(theta, radius)
ax3, aux_ax3 = setup_axes3(fig, 133)
theta = (8 + np.random.rand(10)*(14 - 8))*15. # in degrees
radius = np.random.rand(10)*14000.
aux_ax3.scatter(theta, radius)
plt.show()
0707010001f9a0000081a400001782000005de00000001569316c100000a2d000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/axes_grid/demo_edge_colorbar.py import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid
def get_demo_image():
import numpy as np
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
def demo_bottom_cbar(fig):
"""
A grid of 2x2 images with a colorbar for each column.
"""
grid = AxesGrid(fig, 121, # similar to subplot(132)
nrows_ncols=(2, 2),
axes_pad=0.10,
share_all=True,
label_mode="1",
cbar_location="bottom",
cbar_mode="edge",
cbar_pad=0.25,
cbar_size="15%",
direction="column"
)
Z, extent = get_demo_image()
cmaps = [plt.get_cmap("autumn"), plt.get_cmap("summer")]
for i in range(4):
im = grid[i].imshow(Z, extent=extent, interpolation="nearest",
cmap=cmaps[i//2])
if i % 2:
cbar = grid.cbar_axes[i//2].colorbar(im)
for cax in grid.cbar_axes:
cax.toggle_label(True)
cax.axis[cax.orientation].set_label("Bar")
# This affects all axes as share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
def demo_right_cbar(fig):
"""
A grid of 2x2 images. Each row has its own colorbar.
"""
grid = AxesGrid(F, 122, # similar to subplot(122)
nrows_ncols=(2, 2),
axes_pad=0.10,
label_mode="1",
share_all=True,
cbar_location="right",
cbar_mode="edge",
cbar_size="7%",
cbar_pad="2%",
)
Z, extent = get_demo_image()
cmaps = [plt.get_cmap("spring"), plt.get_cmap("winter")]
for i in range(4):
im = grid[i].imshow(Z, extent=extent, interpolation="nearest",
cmap=cmaps[i//2])
if i % 2:
grid.cbar_axes[i//2].colorbar(im)
for cax in grid.cbar_axes:
cax.toggle_label(True)
cax.axis[cax.orientation].set_label('Foo')
# This affects all axes because we set share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
if 1:
F = plt.figure(1, (5.5, 2.5))
F.subplots_adjust(left=0.05, right=0.93)
demo_bottom_cbar(F)
demo_right_cbar(F)
plt.draw()
plt.show()
0707010001f9a3000081a400001782000005de00000001569316c10000018f000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/axes_grid/demo_imagegrid_aspect.py import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
fig = plt.figure(1)
grid1 = ImageGrid(fig, 121, (2, 2), axes_pad=0.1,
aspect=True, share_all=True)
for i in [0, 1]:
grid1[i].set_aspect(2)
grid2 = ImageGrid(fig, 122, (2, 2), axes_pad=0.1,
aspect=True, share_all=True)
for i in [1, 3]:
grid2[i].set_aspect(2)
plt.show()
0707010001f997000081a400001782000005de00000001569316c100000c20000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/axes_grid/demo_axes_divider.py import matplotlib.pyplot as plt
def get_demo_image():
import numpy as np
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
def demo_simple_image(ax):
Z, extent = get_demo_image()
im = ax.imshow(Z, extent=extent, interpolation="nearest")
cb = plt.colorbar(im)
plt.setp(cb.ax.get_yticklabels(), visible=False)
def demo_locatable_axes_hard(fig1):
from mpl_toolkits.axes_grid1 \
import SubplotDivider, LocatableAxes, Size
divider = SubplotDivider(fig1, 2, 2, 2, aspect=True)
# axes for image
ax = LocatableAxes(fig1, divider.get_position())
# axes for colorbar
ax_cb = LocatableAxes(fig1, divider.get_position())
h = [Size.AxesX(ax), # main axes
Size.Fixed(0.05), # padding, 0.1 inch
Size.Fixed(0.2), # colorbar, 0.3 inch
]
v = [Size.AxesY(ax)]
divider.set_horizontal(h)
divider.set_vertical(v)
ax.set_axes_locator(divider.new_locator(nx=0, ny=0))
ax_cb.set_axes_locator(divider.new_locator(nx=2, ny=0))
fig1.add_axes(ax)
fig1.add_axes(ax_cb)
ax_cb.axis["left"].toggle(all=False)
ax_cb.axis["right"].toggle(ticks=True)
Z, extent = get_demo_image()
im = ax.imshow(Z, extent=extent, interpolation="nearest")
plt.colorbar(im, cax=ax_cb)
plt.setp(ax_cb.get_yticklabels(), visible=False)
def demo_locatable_axes_easy(ax):
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
ax_cb = divider.new_horizontal(size="5%", pad=0.05)
fig1 = ax.get_figure()
fig1.add_axes(ax_cb)
Z, extent = get_demo_image()
im = ax.imshow(Z, extent=extent, interpolation="nearest")
plt.colorbar(im, cax=ax_cb)
ax_cb.yaxis.tick_right()
for tl in ax_cb.get_yticklabels():
tl.set_visible(False)
ax_cb.yaxis.tick_right()
def demo_images_side_by_side(ax):
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
Z, extent = get_demo_image()
ax2 = divider.new_horizontal(size="100%", pad=0.05)
fig1 = ax.get_figure()
fig1.add_axes(ax2)
ax.imshow(Z, extent=extent, interpolation="nearest")
ax2.imshow(Z, extent=extent, interpolation="nearest")
for tl in ax2.get_yticklabels():
tl.set_visible(False)
def demo():
fig1 = plt.figure(1, (6, 6))
fig1.clf()
# PLOT 1
# simple image & colorbar
ax = fig1.add_subplot(2, 2, 1)
demo_simple_image(ax)
# PLOT 2
# image and colorbar whose location is adjusted in the drawing time.
# a hard way
demo_locatable_axes_hard(fig1)
# PLOT 3
# image and colorbar whose location is adjusted in the drawing time.
# a easy way
ax = fig1.add_subplot(2, 2, 3)
demo_locatable_axes_easy(ax)
# PLOT 4
# two images side by side with fixed padding.
ax = fig1.add_subplot(2, 2, 4)
demo_images_side_by_side(ax)
plt.draw()
plt.show()
demo()
0707010001fb05000041ed00001782000005de00000002570a550000000000000002600000050a00000000000000000000002700000000reloc/matplotlib/examples/style_sheets 0707010001fb0a000081a400001782000005de000000015689ead200000337000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/style_sheets/plot_grayscale.py """
This example demonstrates the "grayscale" style sheet, which changes all colors
that are defined as rc parameters to grayscale. Note, however, that not all
plot elements default to colors defined by an rc parameter.
"""
import numpy as np
import matplotlib.pyplot as plt
def color_cycle_example(ax):
L = 6
x = np.linspace(0, L)
ncolors = len(plt.rcParams['axes.color_cycle'])
shift = np.linspace(0, L, ncolors, endpoint=False)
for s in shift:
ax.plot(x, np.sin(x + s), 'o-')
def image_and_patch_example(ax):
ax.imshow(np.random.random(size=(20, 20)), interpolation='none')
c = plt.Circle((5, 5), radius=5, label='patch')
ax.add_patch(c)
plt.style.use('grayscale')
fig, (ax1, ax2) = plt.subplots(ncols=2)
color_cycle_example(ax1)
image_and_patch_example(ax2)
plt.show()
0707010001fb06000081a400001782000005de000000015689ead2000001c9000002600000050a00000000000000000000003300000000reloc/matplotlib/examples/style_sheets/plot_bmh.py """
This example demonstrates the "bmh" style, which is the design used in the
Bayesian Methods for Hackers online book.
"""
from numpy.random import beta
import matplotlib.pyplot as plt
plt.style.use('bmh')
def plot_beta_hist(a, b):
plt.hist(beta(a, b, size=10000), histtype="stepfilled",
bins=25, alpha=0.8, normed=True)
return
plot_beta_hist(10, 10)
plot_beta_hist(4, 12)
plot_beta_hist(50, 12)
plot_beta_hist(6, 55)
plt.show()
0707010001fb07000081a400001782000005de000000015689e23900000239000002600000050a00000000000000000000003f00000000reloc/matplotlib/examples/style_sheets/plot_dark_background.py """
This example demonstrates the "dark_background" style, which uses white for
elements that are typically black (text, borders, etc). Note, however, that not
all plot elements default to colors defined by an rc parameter.
"""
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('dark_background')
L = 6
x = np.linspace(0, L)
ncolors = len(plt.rcParams['axes.color_cycle'])
shift = np.linspace(0, L, ncolors, endpoint=False)
for s in shift:
plt.plot(x, np.sin(x + s), 'o-')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('title')
plt.show()
0707010001fb09000081a400001782000005de000000015689ead200000569000002600000050a00000000000000000000003600000000reloc/matplotlib/examples/style_sheets/plot_ggplot.py """
This example demonstrates the "ggplot" style, which adjusts the style to
emulate ggplot_ (a popular plotting package for R_).
These settings were shamelessly stolen from [1]_ (with permission).
.. [1] http://www.huyng.com/posts/sane-color-scheme-for-matplotlib/
.. _ggplot: http://had.co.nz/ggplot/
.. _R: http://www.r-project.org/
"""
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
fig, axes = plt.subplots(ncols=2, nrows=2)
ax1, ax2, ax3, ax4 = axes.ravel()
# scatter plot (Note: `plt.scatter` doesn't use default colors)
x, y = np.random.normal(size=(2, 200))
ax1.plot(x, y, 'o')
# sinusoidal lines with colors from default color cycle
L = 2*np.pi
x = np.linspace(0, L)
ncolors = len(plt.rcParams['axes.color_cycle'])
shift = np.linspace(0, L, ncolors, endpoint=False)
for s in shift:
ax2.plot(x, np.sin(x + s), '-')
ax2.margins(0)
# bar graphs
x = np.arange(5)
y1, y2 = np.random.randint(1, 25, size=(2, 5))
width = 0.25
ax3.bar(x, y1, width)
ax3.bar(x + width, y2, width, color=plt.rcParams['axes.color_cycle'][2])
ax3.set_xticks(x + width)
ax3.set_xticklabels(['a', 'b', 'c', 'd', 'e'])
# circles with colors from default color cycle
for i, color in enumerate(plt.rcParams['axes.color_cycle']):
xy = np.random.normal(size=2)
ax4.add_patch(plt.Circle(xy, radius=0.3, color=color))
ax4.axis('equal')
ax4.margins(0)
plt.show()
0707010001fb08000081a400001782000005de000000015689ead2000001b2000002600000050a00000000000000000000003f00000000reloc/matplotlib/examples/style_sheets/plot_fivethirtyeight.py """
This shows an example of the "fivethirtyeight" styling, which
tries to replicate the styles from FiveThirtyEight.com.
"""
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(0, 10)
with plt.style.context('fivethirtyeight'):
plt.plot(x, np.sin(x) + x + np.random.randn(50))
plt.plot(x, np.sin(x) + 0.5 * x + np.random.randn(50))
plt.plot(x, np.sin(x) + 2 * x + np.random.randn(50))
plt.show()
0707010001fa0e000041ed00001782000005de00000002570a54ff00000000000002600000050a00000000000000000000002900000000reloc/matplotlib/examples/pylab_examples 0707010001fa95000081ed00001782000005de00000001569316c1000002c7000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/pylab_examples/mathtext_demo.py #!/usr/bin/env python
"""
Use matplotlib's internal LaTeX parser and layout engine. For true
latex rendering, see the text.usetex option
"""
import numpy as np
from matplotlib.pyplot import figure, show
fig = figure()
fig.subplots_adjust(bottom=0.2)
ax = fig.add_subplot(111, axisbg='y')
ax.plot([1, 2, 3], 'r')
x = np.arange(0.0, 3.0, 0.1)
ax.grid(True)
ax.set_xlabel(r'$\Delta_i^j$', fontsize=20)
ax.set_ylabel(r'$\Delta_{i+1}^j$', fontsize=20)
tex = r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\sin(2 \pi f x_i)$'
ax.text(1, 1.6, tex, fontsize=20, va='bottom')
ax.legend([r"$\sqrt{x^2}$"])
ax.set_title(r'$\Delta_i^j \hspace{0.4} \mathrm{versus} \hspace{0.4} \Delta_{i+1}^j$', fontsize=20)
show()
0707010001fa46000081a400001782000005de000000015689ead2000003d2000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/pylab_examples/date_demo_convert.py #!/usr/bin/env python
import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange
from numpy import arange
date1 = datetime.datetime(2000, 3, 2)
date2 = datetime.datetime(2000, 3, 6)
delta = datetime.timedelta(hours=6)
dates = drange(date1, date2, delta)
y = arange(len(dates)*1.0)
fig, ax = plt.subplots()
ax.plot_date(dates, y*y)
# this is superfluous, since the autoscaler should get it right, but
# use date2num and num2date to convert between dates and floats if
# you want; both date2num and num2date convert an instance or sequence
ax.set_xlim(dates[0], dates[-1])
# The hour locator takes the hour or sequence of hours you want to
# tick, not the base multiple
ax.xaxis.set_major_locator(DayLocator())
ax.xaxis.set_minor_locator(HourLocator(arange(0, 25, 6)))
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S')
fig.autofmt_xdate()
plt.show()
0707010001fae7000081a400001782000005de00000001569316c100000196000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/pylab_examples/xcorr_demo.py import matplotlib.pyplot as plt
import numpy as np
x, y = np.random.randn(2, 100)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2)
ax1.grid(True)
ax1.axhline(0, color='black', lw=2)
ax2 = fig.add_subplot(212, sharex=ax1)
ax2.acorr(x, usevlines=True, normed=True, maxlags=50, lw=2)
ax2.grid(True)
ax2.axhline(0, color='black', lw=2)
plt.show()
0707010001fac7000081a400001782000005de000000015689ead2000000ff000002600000050a00000000000000000000003600000000reloc/matplotlib/examples/pylab_examples/stem_plot.py import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.1, 2*np.pi, 10)
markerline, stemlines, baseline = plt.stem(x, np.cos(x), '-.')
plt.setp(markerline, 'markerfacecolor', 'b')
plt.setp(baseline, 'color', 'r', 'linewidth', 2)
plt.show()
0707010001fa82000081a400001782000005de000000015689ead200001cb8000002600000050a00000000000000000000004200000000reloc/matplotlib/examples/pylab_examples/leftventricle_bulleye.py #!/usr/bin/env python
"""
This example demonstrates how to create the 17 segment model for the left
ventricle recommended by the American Heart Association (AHA).
"""
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def bullseye_plot(ax, data, segBold=None, cmap=None, norm=None):
"""
Bullseye representation for the left ventricle.
Parameters
----------
ax : axes
data : list of int and float
The intensity values for each of the 17 segments
segBold: list of int, optional
A list with the segments to highlight
cmap : ColorMap or None, optional
Optional argument to set the desired colormap
norm : Normalize or None, optional
Optional argument to normalize data into the [0.0, 1.0] range
Notes
-----
This function create the 17 segment model for the left ventricle according
to the American Heart Association (AHA) [1]_
References
----------
.. [1] M. D. Cerqueira, N. J. Weissman, V. Dilsizian, A. K. Jacobs,
S. Kaul, W. K. Laskey, D. J. Pennell, J. A. Rumberger, T. Ryan,
and M. S. Verani, "Standardized myocardial segmentation and
nomenclature for tomographic imaging of the heart",
Circulation, vol. 105, no. 4, pp. 539-542, 2002.
"""
if segBold is None:
segBold = []
linewidth = 2
data = np.array(data).ravel()
if cmap is None:
cmap = plt.cm.jet
if norm is None:
norm = mpl.colors.Normalize(vmin=data.min(), vmax=data.max())
theta = np.linspace(0, 2*np.pi, 768)
r = np.linspace(0.2, 1, 4)
# Create the bound for the segment 17
for i in range(r.shape[0]):
ax.plot(theta, np.repeat(r[i], theta.shape), '-k', lw=linewidth)
# Create the bounds for the segments 1-12
for i in range(6):
theta_i = i*60*np.pi/180
ax.plot([theta_i, theta_i], [r[1], 1], '-k', lw=linewidth)
# Create the bounds for the segmentss 13-16
for i in range(4):
theta_i = i*90*np.pi/180 - 45*np.pi/180
ax.plot([theta_i, theta_i], [r[0], r[1]], '-k', lw=linewidth)
# Fill the segments 1-6
r0 = r[2:4]
r0 = np.repeat(r0[:, np.newaxis], 128, axis=1).T
for i in range(6):
# First segment start at 60 degrees
theta0 = theta[i*128:i*128+128] + 60*np.pi/180
theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1)
z = np.ones((128, 2))*data[i]
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
if i+1 in segBold:
ax.plot(theta0, r0, '-k', lw=linewidth+2)
ax.plot(theta0[0], [r[2], r[3]], '-k', lw=linewidth+1)
ax.plot(theta0[-1], [r[2], r[3]], '-k', lw=linewidth+1)
# Fill the segments 7-12
r0 = r[1:3]
r0 = np.repeat(r0[:, np.newaxis], 128, axis=1).T
for i in range(6):
# First segment start at 60 degrees
theta0 = theta[i*128:i*128+128] + 60*np.pi/180
theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1)
z = np.ones((128, 2))*data[i+6]
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
if i+7 in segBold:
ax.plot(theta0, r0, '-k', lw=linewidth+2)
ax.plot(theta0[0], [r[1], r[2]], '-k', lw=linewidth+1)
ax.plot(theta0[-1], [r[1], r[2]], '-k', lw=linewidth+1)
# Fill the segments 13-16
r0 = r[0:2]
r0 = np.repeat(r0[:, np.newaxis], 192, axis=1).T
for i in range(4):
# First segment start at 45 degrees
theta0 = theta[i*192:i*192+192] + 45*np.pi/180
theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1)
z = np.ones((192, 2))*data[i+12]
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
if i+13 in segBold:
ax.plot(theta0, r0, '-k', lw=linewidth+2)
ax.plot(theta0[0], [r[0], r[1]], '-k', lw=linewidth+1)
ax.plot(theta0[-1], [r[0], r[1]], '-k', lw=linewidth+1)
# Fill the segments 17
if data.size == 17:
r0 = np.array([0, r[0]])
r0 = np.repeat(r0[:, np.newaxis], theta.size, axis=1).T
theta0 = np.repeat(theta[:, np.newaxis], 2, axis=1)
z = np.ones((theta.size, 2))*data[16]
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
if 17 in segBold:
ax.plot(theta0, r0, '-k', lw=linewidth+2)
ax.set_ylim([0, 1])
ax.set_yticklabels([])
ax.set_xticklabels([])
# Create the fake data
data = np.array(range(17)) + 1
# Make a figure and axes with dimensions as desired.
fig, ax = plt.subplots(figsize=(12, 8), nrows=1, ncols=3,
subplot_kw=dict(projection='polar'))
fig.canvas.set_window_title('Left Ventricle Bulls Eyes (AHA)')
# Create the axis for the colorbars
axl = fig.add_axes([0.14, 0.15, 0.2, 0.05])
axl2 = fig.add_axes([0.41, 0.15, 0.2, 0.05])
axl3 = fig.add_axes([0.69, 0.15, 0.2, 0.05])
# Set the colormap and norm to correspond to the data for which
# the colorbar will be used.
cmap = mpl.cm.jet
norm = mpl.colors.Normalize(vmin=1, vmax=17)
# ColorbarBase derives from ScalarMappable and puts a colorbar
# in a specified axes, so it has everything needed for a
# standalone colorbar. There are many more kwargs, but the
# following gives a basic continuous colorbar with ticks
# and labels.
cb1 = mpl.colorbar.ColorbarBase(axl, cmap=cmap, norm=norm,
orientation='horizontal')
cb1.set_label('Some Units')
# Set the colormap and norm to correspond to the data for which
# the colorbar will be used.
cmap2 = mpl.cm.cool
norm2 = mpl.colors.Normalize(vmin=1, vmax=17)
# ColorbarBase derives from ScalarMappable and puts a colorbar
# in a specified axes, so it has everything needed for a
# standalone colorbar. There are many more kwargs, but the
# following gives a basic continuous colorbar with ticks
# and labels.
cb2 = mpl.colorbar.ColorbarBase(axl2, cmap=cmap2, norm=norm2,
orientation='horizontal')
cb2.set_label('Some other units')
# The second example illustrates the use of a ListedColormap, a
# BoundaryNorm, and extended ends to show the "over" and "under"
# value colors.
cmap3 = mpl.colors.ListedColormap(['r', 'g', 'b', 'c'])
cmap3.set_over('0.35')
cmap3.set_under('0.75')
# If a ListedColormap is used, the length of the bounds array must be
# one greater than the length of the color list. The bounds must be
# monotonically increasing.
bounds = [2, 3, 7, 9, 15]
norm3 = mpl.colors.BoundaryNorm(bounds, cmap3.N)
cb3 = mpl.colorbar.ColorbarBase(axl3, cmap=cmap3, norm=norm3,
# to use 'extend', you must
# specify two extra boundaries:
boundaries=[0]+bounds+[18],
extend='both',
ticks=bounds, # optional
spacing='proportional',
orientation='horizontal')
cb3.set_label('Discrete intervals, some other units')
# Create the 17 segment model
bullseye_plot(ax[0], data, cmap=cmap, norm=norm)
ax[0].set_title('Bulls Eye (AHA)')
bullseye_plot(ax[1], data, cmap=cmap2, norm=norm2)
ax[1].set_title('Bulls Eye (AHA)')
bullseye_plot(ax[2], data, segBold=[3, 5, 6, 11, 12, 16],
cmap=cmap3, norm=norm3)
ax[2].set_title('Segments [3,5,6,11,12,16] in bold')
plt.show()
0707010001faa2000081ed00001782000005de000000015689ead20000023d000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/pylab_examples/nan_test.py """
Example: simple line plots with NaNs inserted.
"""
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(2 * 2 * np.pi * t)
t[41:60] = np.nan
plt.subplot(2, 1, 1)
plt.plot(t, s, '-', lw=2)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('A sine wave with a gap of NaNs between 0.4 and 0.6')
plt.grid(True)
plt.subplot(2, 1, 2)
t[0] = np.nan
t[-1] = np.nan
plt.plot(t, s, '-', lw=2)
plt.title('Also with NaN in first and last point')
plt.xlabel('time (s)')
plt.ylabel('more nans')
plt.grid(True)
plt.show()
0707010001fa1a000081a400001782000005de000000015689ead20000012c000002600000050a00000000000000000000003400000000reloc/matplotlib/examples/pylab_examples/arctest.py import matplotlib.pyplot as plt
import numpy as np
def f(t):
'a damped exponential'
s1 = np.cos(2 * np.pi * t)
e1 = np.exp(-t)
return s1 * e1
t1 = np.arange(0.0, 5.0, .2)
l = plt.plot(t1, f(t1), 'ro')
plt.setp(l, 'markersize', 30)
plt.setp(l, 'markerfacecolor', 'b')
plt.show()
0707010001fa6c000081ed00001782000005de000000015689ead2000009d4000002600000050a00000000000000000000004100000000reloc/matplotlib/examples/pylab_examples/ginput_manual_clabel.py #!/usr/bin/env python
# -*- noplot -*-
from __future__ import print_function
"""
This provides examples of uses of interactive functions, such as ginput,
waitforbuttonpress and manual clabel placement.
This script must be run interactively using a backend that has a
graphical user interface (for example, using GTKAgg backend, but not
PS backend).
See also ginput_demo.py
"""
import time
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
def tellme(s):
print(s)
plt.title(s, fontsize=16)
plt.draw()
##################################################
# Define a triangle by clicking three points
##################################################
plt.clf()
plt.axis([-1., 1., -1., 1.])
plt.setp(plt.gca(), autoscale_on=False)
tellme('You will define a triangle, click to begin')
plt.waitforbuttonpress()
happy = False
while not happy:
pts = []
while len(pts) < 3:
tellme('Select 3 corners with mouse')
pts = np.asarray(plt.ginput(3, timeout=-1))
if len(pts) < 3:
tellme('Too few points, starting over')
time.sleep(1) # Wait a second
ph = plt.fill(pts[:, 0], pts[:, 1], 'r', lw=2)
tellme('Happy? Key click for yes, mouse click for no')
happy = plt.waitforbuttonpress()
# Get rid of fill
if not happy:
for p in ph:
p.remove()
##################################################
# Now contour according to distance from triangle
# corners - just an example
##################################################
# Define a nice function of distance from individual pts
def f(x, y, pts):
z = np.zeros_like(x)
for p in pts:
z = z + 1/(np.sqrt((x - p[0])**2 + (y - p[1])**2))
return 1/z
X, Y = np.meshgrid(np.linspace(-1, 1, 51), np.linspace(-1, 1, 51))
Z = f(X, Y, pts)
CS = plt.contour(X, Y, Z, 20)
tellme('Use mouse to select contour label locations, middle button to finish')
CL = plt.clabel(CS, manual=True)
##################################################
# Now do a zoom
##################################################
tellme('Now do a nested zoom, click to begin')
plt.waitforbuttonpress()
happy = False
while not happy:
tellme('Select two corners of zoom, middle mouse button to finish')
pts = np.asarray(plt.ginput(2, timeout=-1))
happy = len(pts) < 2
if happy:
break
pts = np.sort(pts, axis=0)
plt.axis(pts.T.ravel())
tellme('All Done!')
plt.show()
0707010001fa8f000081a400001782000005de000000015689ead2000006a2000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/pylab_examples/major_minor_demo1.py """
Demonstrate how to use major and minor tickers.
The two relevant userland classes are Locators and Formatters.
Locators determine where the ticks are and formatters control the
formatting of ticks.
Minor ticks are off by default (NullLocator and NullFormatter). You
can turn minor ticks on w/o labels by setting the minor locator. You
can also turn labeling on for the minor ticker by setting the minor
formatter
Make a plot with major ticks that are multiples of 20 and minor ticks
that are multiples of 5. Label major ticks with %d formatting but
don't label minor ticks
The MultipleLocator ticker class is used to place ticks on multiples of
some base. The FormatStrFormatter uses a string format string (e.g.,
'%d' or '%1.2f' or '%1.1f cm' ) to format the tick
The pyplot interface grid command changes the grid settings of the
major ticks of the y and y axis together. If you want to control the
grid of the minor ticks for a given axis, use for example
ax.xaxis.grid(True, which='minor')
Note, you should not use the same locator between different Axis
because the locator stores references to the Axis data and view limits
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
majorLocator = MultipleLocator(20)
majorFormatter = FormatStrFormatter('%d')
minorLocator = MultipleLocator(5)
t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)
fig, ax = plt.subplots()
plt.plot(t, s)
ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)
# for the minor ticks, use no labels; default NullFormatter
ax.xaxis.set_minor_locator(minorLocator)
plt.show()
0707010001fac8000081a400001782000005de000000015689ead2000001af000002600000050a00000000000000000000003600000000reloc/matplotlib/examples/pylab_examples/step_demo.py import numpy as np
from numpy import ma
import matplotlib.pyplot as plt
x = np.arange(1, 7, 0.4)
y0 = np.sin(x)
y = y0.copy() + 2.5
plt.step(x, y, label='pre (default)')
y -= 0.5
plt.step(x, y, where='mid', label='mid')
y -= 0.5
plt.step(x, y, where='post', label='post')
y = ma.masked_where((y0 > -0.15) & (y0 < 0.15), y - 0.5)
plt.step(x, y, label='masked (pre)')
plt.legend()
plt.xlim(0, 7)
plt.ylim(-0.5, 4)
plt.show()
0707010001faa0000081a400001782000005de000000015689ead2000001c2000002600000050a00000000000000000000003f00000000reloc/matplotlib/examples/pylab_examples/multiple_figs_demo.py # Working with multiple figure windows and subplots
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.sin(4*np.pi*t)
plt.figure(1)
plt.subplot(211)
plt.plot(t, s1)
plt.subplot(212)
plt.plot(t, 2*s1)
plt.figure(2)
plt.plot(t, s2)
# now switch back to figure 1 and make some changes
plt.figure(1)
plt.subplot(211)
plt.plot(t, s2, 'gs')
ax = plt.gca()
ax.set_xticklabels([])
plt.show()
0707010001fa2b000081a400001782000005de000000015689ead200000087000002600000050a00000000000000000000003200000000reloc/matplotlib/examples/pylab_examples/break.py import matplotlib.pyplot as plt
plt.gcf().text(0.5, 0.95, 'Distance Histograms by Category is \
a really long title')
plt.show()
0707010001fa42000081a400001782000005de000000015689ead200000353000002600000050a00000000000000000000003b00000000reloc/matplotlib/examples/pylab_examples/dashpointlabel.py import matplotlib.pyplot as plt
DATA = ((1, 3),
(2, 4),
(3, 1),
(4, 2))
# dash_style =
# direction, length, (text)rotation, dashrotation, push
# (The parameters are varied to show their effects,
# not for visual appeal).
dash_style = (
(0, 20, -15, 30, 10),
(1, 30, 0, 15, 10),
(0, 40, 15, 15, 10),
(1, 20, 30, 60, 10),
)
fig, ax = plt.subplots()
(x, y) = zip(*DATA)
ax.plot(x, y, marker='o')
for i in range(len(DATA)):
(x, y) = DATA[i]
(dd, dl, r, dr, dp) = dash_style[i]
#print('dashlen call %d' % dl)
t = ax.text(x, y, str((x, y)), withdash=True,
dashdirection=dd,
dashlength=dl,
rotation=r,
dashrotation=dr,
dashpush=dp,
)
ax.set_xlim((0.0, 5.0))
ax.set_ylim((0.0, 5.0))
plt.show()
0707010001fa24000081a400001782000005de000000015689ead2000006eb000002600000050a00000000000000000000003600000000reloc/matplotlib/examples/pylab_examples/barb_demo.py '''
Demonstration of wind barb plots
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 5)
X, Y = np.meshgrid(x, x)
U, V = 12*X, 12*Y
data = [(-1.5, .5, -6, -6),
(1, -1, -46, 46),
(-3, -1, 11, -11),
(1, 1.5, 80, 80),
(0.5, 0.25, 25, 15),
(-1.5, -0.5, -5, 40)]
data = np.array(data, dtype=[('x', np.float32), ('y', np.float32),
('u', np.float32), ('v', np.float32)])
# Default parameters, uniform grid
ax = plt.subplot(2, 2, 1)
ax.barbs(X, Y, U, V)
# Arbitrary set of vectors, make them longer and change the pivot point
#(point around which they're rotated) to be the middle
ax = plt.subplot(2, 2, 2)
ax.barbs(data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle')
# Showing colormapping with uniform grid. Fill the circle for an empty barb,
# don't round the values, and change some of the size parameters
ax = plt.subplot(2, 2, 3)
ax.barbs(X, Y, U, V, np.sqrt(U*U + V*V), fill_empty=True, rounding=False,
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))
# Change colors as well as the increments for parts of the barbs
ax = plt.subplot(2, 2, 4)
ax.barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r',
barbcolor=['b', 'g'], barb_increments=dict(half=10, full=20, flag=100),
flip_barb=True)
# Masked arrays are also supported
masked_u = np.ma.masked_array(data['u'])
masked_u[4] = 1000 # Bad value that should not be plotted when masked
masked_u[4] = np.ma.masked
# Identical plot to panel 2 in the first figure, but with the point at
#(0.5, 0.25) missing (masked)
fig2 = plt.figure()
ax = fig2.add_subplot(1, 1, 1)
ax.barbs(data['x'], data['y'], masked_u, data['v'], length=8, pivot='middle')
plt.show()
0707010001fad5000081a400001782000005de000000015689ead200000598000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/pylab_examples/text_rotation.py """
The way matplotlib does text layout is counter-intuitive to some, so
this example is designed to make it a little clearer. The text is
aligned by it's bounding box (the rectangular box that surrounds the
ink rectangle). The order of operations is basically rotation then
alignment, rather than alignment then rotation. Basically, the text
is centered at your x,y location, rotated around this point, and then
aligned according to the bounding box of the rotated text.
So if you specify left, bottom alignment, the bottom left of the
bounding box of the rotated text will be at the x,y coordinate of the
text.
But a picture is worth a thousand words!
"""
import matplotlib.pyplot as plt
import numpy as np
def addtext(props):
plt.text(0.5, 0.5, 'text 0', props, rotation=0)
plt.text(1.5, 0.5, 'text 45', props, rotation=45)
plt.text(2.5, 0.5, 'text 135', props, rotation=135)
plt.text(3.5, 0.5, 'text 225', props, rotation=225)
plt.text(4.5, 0.5, 'text -45', props, rotation=-45)
plt.yticks([0, .5, 1])
plt.grid(True)
# the text bounding box
bbox = {'fc': '0.8', 'pad': 0}
plt.subplot(211)
addtext({'ha': 'center', 'va': 'center', 'bbox': bbox})
plt.xlim(0, 5)
plt.xticks(np.arange(0, 5.1, 0.5), [])
plt.ylabel('center / center')
plt.subplot(212)
addtext({'ha': 'left', 'va': 'bottom', 'bbox': bbox})
plt.xlim(0, 5)
plt.xticks(np.arange(0, 5.1, 0.5))
plt.ylabel('left / bottom')
plt.show()
0707010001fa69000081a400001782000005de000000015689ead200000417000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/pylab_examples/ganged_plots.py """
To create plots that share a common axes (visually) you can set the
hspace between the subplots close to zero (do not use zero itself).
Normally you'll want to turn off the tick labels on all but one of the
axes.
In this example the plots share a common xaxis but you can follow the
same logic to supply a common y axis.
"""
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.exp(-t)
s3 = s1*s2
# axes rect in relative 0,1 coords left, bottom, width, height. Turn
# off xtick labels on all but the lower plot
f = plt.figure()
plt.subplots_adjust(hspace=0.001)
ax1 = plt.subplot(311)
ax1.plot(t, s1)
plt.yticks(np.arange(-0.9, 1.0, 0.4))
plt.ylim(-1, 1)
ax2 = plt.subplot(312, sharex=ax1)
ax2.plot(t, s2)
plt.yticks(np.arange(0.1, 1.0, 0.2))
plt.ylim(0, 1)
ax3 = plt.subplot(313, sharex=ax1)
ax3.plot(t, s3)
plt.yticks(np.arange(-0.9, 1.0, 0.4))
plt.ylim(-1, 1)
xticklabels = ax1.get_xticklabels() + ax2.get_xticklabels()
plt.setp(xticklabels, visible=False)
plt.show()
0707010001fa61000081a400001782000005de000000015689ead200000635000002600000050a00000000000000000000003f00000000reloc/matplotlib/examples/pylab_examples/fill_betweenx_demo.py """
Copy of fill_between.py but using fill_betweenx() instead.
"""
import matplotlib.mlab as mlab
from matplotlib.pyplot import figure, show
import numpy as np
x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2*np.pi*x)
y2 = 1.2*np.sin(4*np.pi*x)
fig = figure()
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312, sharex=ax1)
ax3 = fig.add_subplot(313, sharex=ax1)
ax1.fill_betweenx(x, 0, y1)
ax1.set_ylabel('between y1 and 0')
ax2.fill_betweenx(x, y1, 1)
ax2.set_ylabel('between y1 and 1')
ax3.fill_betweenx(x, y1, y2)
ax3.set_ylabel('between y1 and y2')
ax3.set_xlabel('x')
# now fill between y1 and y2 where a logical condition is met. Note
# this is different than calling
# fill_between(x[where], y1[where],y2[where]
# because of edge effects over multiple contiguous regions.
fig = figure()
ax = fig.add_subplot(211)
ax.plot(y1, x, y2, x, color='black')
ax.fill_betweenx(x, y1, y2, where=y2 >= y1, facecolor='green')
ax.fill_betweenx(x, y1, y2, where=y2 <= y1, facecolor='red')
ax.set_title('fill between where')
# Test support for masked arrays.
y2 = np.ma.masked_greater(y2, 1.0)
ax1 = fig.add_subplot(212, sharex=ax)
ax1.plot(y1, x, y2, x, color='black')
ax1.fill_betweenx(x, y1, y2, where=y2 >= y1, facecolor='green')
ax1.fill_betweenx(x, y1, y2, where=y2 <= y1, facecolor='red')
ax1.set_title('Now regions with y2 > 1 are masked')
# This example illustrates a problem; because of the data
# gridding, there are undesired unfilled triangles at the crossover
# points. A brute-force solution would be to interpolate all
# arrays to a very fine grid before plotting.
show()
0707010001fa47000081a400001782000005de000000015689ead200000390000002600000050a00000000000000000000003c00000000reloc/matplotlib/examples/pylab_examples/date_demo_rrule.py #!/usr/bin/env python
"""
Show how to use an rrule instance to make a custom date ticker - here
we put a tick mark on every 5th easter
See https://moin.conectiva.com.br/DateUtil for help with rrules
"""
import matplotlib.pyplot as plt
from matplotlib.dates import YEARLY, DateFormatter, rrulewrapper, RRuleLocator, drange
import numpy as np
import datetime
# tick every 5th easter
rule = rrulewrapper(YEARLY, byeaster=1, interval=5)
loc = RRuleLocator(rule)
formatter = DateFormatter('%m/%d/%y')
date1 = datetime.date(1952, 1, 1)
date2 = datetime.date(2004, 4, 12)
delta = datetime.timedelta(days=100)
dates = drange(date1, date2, delta)
s = np.random.rand(len(dates)) # make up some random y values
fig, ax = plt.subplots()
plt.plot_date(dates, s)
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=30, fontsize=10)
plt.show()
0707010001fadb000081a400001782000005de000000015689ead200001563000002600000050a00000000000000000000004700000000reloc/matplotlib/examples/pylab_examples/tricontour_smooth_delaunay.py """
Demonstrates high-resolution tricontouring of a random set of points ;
a matplotlib.tri.TriAnalyzer is used to improve the plot quality.
The initial data points and triangular grid for this demo are:
- a set of random points is instantiated, inside [-1, 1] x [-1, 1] square
- A Delaunay triangulation of these points is then computed, of which a
random subset of triangles is masked out by the user (based on
*init_mask_frac* parameter). This simulates invalidated data.
The proposed generic procedure to obtain a high resolution contouring of such
a data set is the following:
1) Compute an extended mask with a matplotlib.tri.TriAnalyzer, which will
exclude badly shaped (flat) triangles from the border of the
triangulation. Apply the mask to the triangulation (using set_mask).
2) Refine and interpolate the data using a
matplotlib.tri.UniformTriRefiner.
3) Plot the refined data with tricontour.
"""
from matplotlib.tri import Triangulation, TriAnalyzer, UniformTriRefiner
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
#-----------------------------------------------------------------------------
# Analytical test function
#-----------------------------------------------------------------------------
def experiment_res(x, y):
""" An analytic function representing experiment results """
x = 2.*x
r1 = np.sqrt((0.5 - x)**2 + (0.5 - y)**2)
theta1 = np.arctan2(0.5 - x, 0.5 - y)
r2 = np.sqrt((-x - 0.2)**2 + (-y - 0.2)**2)
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
z = (4*(np.exp((r1/10)**2) - 1)*30. * np.cos(3*theta1) +
(np.exp((r2/10)**2) - 1)*30. * np.cos(5*theta2) +
2*(x**2 + y**2))
return (np.max(z) - z)/(np.max(z) - np.min(z))
#-----------------------------------------------------------------------------
# Generating the initial data test points and triangulation for the demo
#-----------------------------------------------------------------------------
# User parameters for data test points
n_test = 200 # Number of test data points, tested from 3 to 5000 for subdiv=3
subdiv = 3 # Number of recursive subdivisions of the initial mesh for smooth
# plots. Values >3 might result in a very high number of triangles
# for the refine mesh: new triangles numbering = (4**subdiv)*ntri
init_mask_frac = 0.0 # Float > 0. adjusting the proportion of
# (invalid) initial triangles which will be masked
# out. Enter 0 for no mask.
min_circle_ratio = .01 # Minimum circle ratio - border triangles with circle
# ratio below this will be masked if they touch a
# border. Suggested value 0.01 ; Use -1 to keep
# all triangles.
# Random points
random_gen = np.random.mtrand.RandomState(seed=127260)
x_test = random_gen.uniform(-1., 1., size=n_test)
y_test = random_gen.uniform(-1., 1., size=n_test)
z_test = experiment_res(x_test, y_test)
# meshing with Delaunay triangulation
tri = Triangulation(x_test, y_test)
ntri = tri.triangles.shape[0]
# Some invalid data are masked out
mask_init = np.zeros(ntri, dtype=np.bool)
masked_tri = random_gen.randint(0, ntri, int(ntri*init_mask_frac))
mask_init[masked_tri] = True
tri.set_mask(mask_init)
#-----------------------------------------------------------------------------
# Improving the triangulation before high-res plots: removing flat triangles
#-----------------------------------------------------------------------------
# masking badly shaped triangles at the border of the triangular mesh.
mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio)
tri.set_mask(mask)
# refining the data
refiner = UniformTriRefiner(tri)
tri_refi, z_test_refi = refiner.refine_field(z_test, subdiv=subdiv)
# analytical 'results' for comparison
z_expected = experiment_res(tri_refi.x, tri_refi.y)
# for the demo: loading the 'flat' triangles for plot
flat_tri = Triangulation(x_test, y_test)
flat_tri.set_mask(~mask)
#-----------------------------------------------------------------------------
# Now the plots
#-----------------------------------------------------------------------------
# User options for plots
plot_tri = True # plot of base triangulation
plot_masked_tri = True # plot of excessively flat excluded triangles
plot_refi_tri = False # plot of refined triangulation
plot_expected = False # plot of analytical function values for comparison
# Graphical options for tricontouring
levels = np.arange(0., 1., 0.025)
cmap = cm.get_cmap(name='Blues', lut=None)
plt.figure()
plt.gca().set_aspect('equal')
plt.title("Filtering a Delaunay mesh\n" +
"(application to high-resolution tricontouring)")
# 1) plot of the refined (computed) data countours:
plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
linewidths=[2.0, 0.5, 1.0, 0.5])
# 2) plot of the expected (analytical) data countours (dashed):
if plot_expected:
plt.tricontour(tri_refi, z_expected, levels=levels, cmap=cmap,
linestyles='--')
# 3) plot of the fine mesh on which interpolation was done:
if plot_refi_tri:
plt.triplot(tri_refi, color='0.97')
# 4) plot of the initial 'coarse' mesh:
if plot_tri:
plt.triplot(tri, color='0.7')
# 4) plot of the unvalidated triangles from naive Delaunay Triangulation:
if plot_masked_tri:
plt.triplot(flat_tri, color='red')
plt.show()
0707010001fa1d000081a400001782000005de000000015689ead2000001c6000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/pylab_examples/aspect_loglog.py import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.set_xscale("log")
ax1.set_yscale("log")
ax1.set_xlim(1e1, 1e3)
ax1.set_ylim(1e2, 1e3)
ax1.set_aspect(1)
ax1.set_title("adjustable = box")
ax2.set_xscale("log")
ax2.set_yscale("log")
ax2.set_adjustable("datalim")
ax2.plot([1, 3, 10], [1, 9, 100], "o-")
ax2.set_xlim(1e-1, 1e2)
ax2.set_ylim(1e-1, 1e3)
ax2.set_aspect(1)
ax2.set_title("adjustable = datalim")
plt.draw()
plt.show()
0707010001fa5a000081a400001782000005de000000015689ead2000011f2000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/pylab_examples/fancybox_demo.py import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
from matplotlib.patches import FancyBboxPatch
# Bbox object around which the fancy box will be drawn.
bb = mtransforms.Bbox([[0.3, 0.4], [0.7, 0.6]])
def draw_bbox(ax, bb):
# boxstyle=square with pad=0, i.e. bbox itself.
p_bbox = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="square,pad=0.",
ec="k", fc="none", zorder=10.,
)
ax.add_patch(p_bbox)
def test1(ax):
# a fancy box with round corners. pad=0.1
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.1",
fc=(1., .8, 1.),
ec=(1., 0.5, 1.))
ax.add_patch(p_fancy)
ax.text(0.1, 0.8,
r' boxstyle="round,pad=0.1"',
size=10, transform=ax.transAxes)
# draws control points for the fancy box.
#l = p_fancy.get_path().vertices
#ax.plot(l[:,0], l[:,1], ".")
# draw the original bbox in black
draw_bbox(ax, bb)
def test2(ax):
# bbox=round has two optional argument. pad and rounding_size.
# They can be set during the initialization.
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.1",
fc=(1., .8, 1.),
ec=(1., 0.5, 1.))
ax.add_patch(p_fancy)
# boxstyle and its argument can be later modified with
# set_boxstyle method. Note that the old attributes are simply
# forgotten even if the boxstyle name is same.
p_fancy.set_boxstyle("round,pad=0.1, rounding_size=0.2")
# or
#p_fancy.set_boxstyle("round", pad=0.1, rounding_size=0.2)
ax.text(0.1, 0.8,
' boxstyle="round,pad=0.1\n rounding\\_size=0.2"',
size=10, transform=ax.transAxes)
# draws control points for the fancy box.
#l = p_fancy.get_path().vertices
#ax.plot(l[:,0], l[:,1], ".")
draw_bbox(ax, bb)
def test3(ax):
# mutation_scale determine overall scale of the mutation,
# i.e. both pad and rounding_size is scaled according to this
# value.
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.1",
mutation_scale=2.,
fc=(1., .8, 1.),
ec=(1., 0.5, 1.))
ax.add_patch(p_fancy)
ax.text(0.1, 0.8,
' boxstyle="round,pad=0.1"\n mutation\\_scale=2',
size=10, transform=ax.transAxes)
# draws control points for the fancy box.
#l = p_fancy.get_path().vertices
#ax.plot(l[:,0], l[:,1], ".")
draw_bbox(ax, bb)
def test4(ax):
# When the aspect ratio of the axes is not 1, the fancy box may
# not be what you expected (green)
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.2",
fc="none",
ec=(0., .5, 0.), zorder=4)
ax.add_patch(p_fancy)
# You can compensate this by setting the mutation_aspect (pink).
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.3",
mutation_aspect=.5,
fc=(1., 0.8, 1.),
ec=(1., 0.5, 1.))
ax.add_patch(p_fancy)
ax.text(0.1, 0.8,
' boxstyle="round,pad=0.3"\n mutation\\_aspect=.5',
size=10, transform=ax.transAxes)
draw_bbox(ax, bb)
def test_all():
plt.clf()
ax = plt.subplot(2, 2, 1)
test1(ax)
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
ax.set_title("test1")
ax.set_aspect(1.)
ax = plt.subplot(2, 2, 2)
ax.set_title("test2")
test2(ax)
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
ax.set_aspect(1.)
ax = plt.subplot(2, 2, 3)
ax.set_title("test3")
test3(ax)
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
ax.set_aspect(1)
ax = plt.subplot(2, 2, 4)
ax.set_title("test4")
test4(ax)
ax.set_xlim(-0.5, 1.5)
ax.set_ylim(0., 1.)
ax.set_aspect(2.)
plt.draw()
plt.show()
test_all()
0707010001fac6000081a400001782000005de000000015689ead200000271000002600000050a00000000000000000000003c00000000reloc/matplotlib/examples/pylab_examples/stackplot_demo2.py import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
def layers(n, m):
"""
Return *n* random Gaussian mixtures, each of length *m*.
"""
def bump(a):
x = 1 / (.1 + np.random.random())
y = 2 * np.random.random() - .5
z = 10 / (.1 + np.random.random())
for i in range(m):
w = (i / float(m) - y) * z
a[i] += x * np.exp(-w * w)
a = np.zeros((m, n))
for i in range(n):
for j in range(5):
bump(a[:, i])
return a
d = layers(3, 100)
plt.subplots()
plt.stackplot(range(100), d.T, baseline='wiggle')
plt.show()
0707010001fa41000081a400001782000005de000000015689ead20000057b000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/pylab_examples/customize_rc.py """
I'm not trying to make a good looking figure here, but just to show
some examples of customizing rc params on the fly
If you like to work interactively, and need to create different sets
of defaults for figures (e.g., one set of defaults for publication, one
set for interactive exploration), you may want to define some
functions in a custom module that set the defaults, e.g.,
def set_pub():
rc('font', weight='bold') # bold fonts are easier to see
rc('tick', labelsize=15) # tick labels bigger
rc('lines', lw=1, color='k') # thicker black lines (no budget for color!)
rc('grid', c='0.5', ls='-', lw=0.5) # solid gray grid lines
rc('savefig', dpi=300) # higher res outputs
Then as you are working interactively, you just need to do
>>> set_pub()
>>> subplot(111)
>>> plot([1,2,3])
>>> savefig('myfig')
>>> rcdefaults() # restore the defaults
"""
import matplotlib.pyplot as plt
plt.subplot(311)
plt.plot([1, 2, 3])
# the axes attributes need to be set before the call to subplot
plt.rc('font', weight='bold')
plt.rc('xtick.major', size=5, pad=7)
plt.rc('xtick', labelsize=15)
# using aliases for color, linestyle and linewidth; gray, solid, thick
plt.rc('grid', c='0.5', ls='-', lw=5)
plt.rc('lines', lw=2, color='g')
plt.subplot(312)
plt.plot([1, 2, 3])
plt.grid(True)
plt.rcdefaults()
plt.subplot(313)
plt.plot([1, 2, 3])
plt.grid(True)
plt.show()
0707010001fa11000081ed00001782000005de000000015689ead20000038e000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/pylab_examples/agg_buffer.py #!/usr/bin/env python
"""
Use backend agg to access the figure canvas as an RGB string and then
convert it to an array and pass it to Pillow for rendering.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
try:
from PIL import Image
except ImportError:
raise SystemExit("Pillow must be installed to run this example")
plt.plot([1, 2, 3])
canvas = plt.get_current_fig_manager().canvas
agg = canvas.switch_backends(FigureCanvasAgg)
agg.draw()
s = agg.tostring_rgb()
# get the width and the height to resize the matrix
l, b, w, h = agg.figure.bbox.bounds
w, h = int(w), int(h)
X = np.fromstring(s, np.uint8)
X.shape = h, w, 3
try:
im = Image.fromstring("RGB", (w, h), s)
except Exception:
im = Image.frombytes("RGB", (w, h), s)
# Uncomment this line to display the image using ImageMagick's
# `display` tool.
# im.show()
0707010001fa27000081a400001782000005de000000015689ead20000021b000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/pylab_examples/barcode_demo.py import matplotlib.pyplot as plt
import numpy as np
# the bar
x = np.where(np.random.rand(500) > 0.7, 1.0, 0.0)
axprops = dict(xticks=[], yticks=[])
barprops = dict(aspect='auto', cmap=plt.cm.binary, interpolation='nearest')
fig = plt.figure()
# a vertical barcode -- this is broken at present
x.shape = len(x), 1
ax = fig.add_axes([0.1, 0.3, 0.1, 0.6], **axprops)
ax.imshow(x, **barprops)
x = x.copy()
# a horizontal barcode
x.shape = 1, len(x)
ax = fig.add_axes([0.3, 0.1, 0.6, 0.1], **axprops)
ax.imshow(x, **barprops)
plt.show()
0707010001fa59000081a400001782000005de00000001569316c100000575000002600000050a00000000000000000000003c00000000reloc/matplotlib/examples/pylab_examples/fancyarrow_demo.py import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
styles = mpatches.ArrowStyle.get_styles()
ncol = 2
nrow = (len(styles) + 1) // ncol
figheight = (nrow + 0.5)
fig1 = plt.figure(1, (4.*ncol/1.5, figheight/1.5))
fontsize = 0.2 * 70
ax = fig1.add_axes([0, 0, 1, 1], frameon=False, aspect=1.)
ax.set_xlim(0, 4*ncol)
ax.set_ylim(0, figheight)
def to_texstring(s):
s = s.replace("<", r"$<$")
s = s.replace(">", r"$>$")
s = s.replace("|", r"$|$")
return s
for i, (stylename, styleclass) in enumerate(sorted(styles.items())):
x = 3.2 + (i//nrow)*4
y = (figheight - 0.7 - i % nrow) # /figheight
p = mpatches.Circle((x, y), 0.2, fc="w")
ax.add_patch(p)
ax.annotate(to_texstring(stylename), (x, y),
(x - 1.2, y),
#xycoords="figure fraction", textcoords="figure fraction",
ha="right", va="center",
size=fontsize,
arrowprops=dict(arrowstyle=stylename,
patchB=p,
shrinkA=5,
shrinkB=5,
fc="w", ec="k",
connectionstyle="arc3,rad=-0.05",
),
bbox=dict(boxstyle="square", fc="w"))
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
plt.draw()
plt.show()
0707010001fa7e000081a400001782000005de000000015689ead200000406000002600000050a00000000000000000000004000000000reloc/matplotlib/examples/pylab_examples/image_slices_viewer.py from __future__ import print_function
import numpy
from matplotlib.pyplot import figure, show
class IndexTracker(object):
def __init__(self, ax, X):
self.ax = ax
ax.set_title('use scroll wheel to navigate images')
self.X = X
rows, cols, self.slices = X.shape
self.ind = self.slices/2
self.im = ax.imshow(self.X[:, :, self.ind])
self.update()
def onscroll(self, event):
print("%s %s" % (event.button, event.step))
if event.button == 'up':
self.ind = numpy.clip(self.ind + 1, 0, self.slices - 1)
else:
self.ind = numpy.clip(self.ind - 1, 0, self.slices - 1)
self.update()
def update(self):
self.im.set_data(self.X[:, :, self.ind])
ax.set_ylabel('slice %s' % self.ind)
self.im.axes.figure.canvas.draw()
fig = figure()
ax = fig.add_subplot(111)
X = numpy.random.rand(20, 20, 40)
tracker = IndexTracker(ax, X)
fig.canvas.mpl_connect('scroll_event', tracker.onscroll)
show()
0707010001fa44000081a400001782000005de000000015689ead2000005df000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/pylab_examples/date_demo1.py #!/usr/bin/env python
"""
Show how to make date plots in matplotlib using date tick locators and
formatters. See major_minor_demo1.py for more information on
controlling major and minor ticks
All matplotlib date plotting is done by converting date instances into
days since the 0001-01-01 UTC. The conversion, tick locating and
formatting is done behind the scenes so this is most transparent to
you. The dates module provides several converter functions date2num
and num2date
This example requires an active internet connection since it uses
yahoo finance to get the data for plotting
"""
import matplotlib.pyplot as plt
from matplotlib.finance import quotes_historical_yahoo_ochl
from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
import datetime
date1 = datetime.date(1995, 1, 1)
date2 = datetime.date(2004, 4, 12)
years = YearLocator() # every year
months = MonthLocator() # every month
yearsFmt = DateFormatter('%Y')
quotes = quotes_historical_yahoo_ochl('INTC', date1, date2)
if len(quotes) == 0:
raise SystemExit
dates = [q[0] for q in quotes]
opens = [q[1] for q in quotes]
fig, ax = plt.subplots()
ax.plot_date(dates, opens, '-')
# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.autoscale_view()
# format the coords message box
def price(x):
return '$%1.2f' % x
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.fmt_ydata = price
ax.grid(True)
fig.autofmt_xdate()
plt.show()
0707010001fad0000081a400001782000005de00000001569316c100000702000002600000050a00000000000000000000003b00000000reloc/matplotlib/examples/pylab_examples/system_monitor.py import time
import matplotlib.pyplot as plt
import numpy as np
def get_memory():
"Simulate a function that returns system memory"
return 100*(0.5 + 0.5*np.sin(0.5*np.pi*time.time()))
def get_cpu():
"Simulate a function that returns cpu usage"
return 100*(0.5 + 0.5*np.sin(0.2*np.pi*(time.time() - 0.25)))
def get_net():
"Simulate a function that returns network bandwidth"
return 100*(0.5 + 0.5*np.sin(0.7*np.pi*(time.time() - 0.1)))
def get_stats():
return get_memory(), get_cpu(), get_net()
fig, ax = plt.subplots()
ind = np.arange(1, 4)
# show the figure, but do not block
plt.show(block=False)
pm, pc, pn = plt.bar(ind, get_stats())
centers = ind + 0.5*pm.get_width()
pm.set_facecolor('r')
pc.set_facecolor('g')
pn.set_facecolor('b')
ax.set_xlim([0.5, 4])
ax.set_xticks(centers)
ax.set_ylim([0, 100])
ax.set_xticklabels(['Memory', 'CPU', 'Bandwidth'])
ax.set_ylabel('Percent usage')
ax.set_title('System Monitor')
start = time.time()
for i in range(200): # run for a little while
m, c, n = get_stats()
# update the animated artists
pm.set_height(m)
pc.set_height(c)
pn.set_height(n)
# ask the canvas to re-draw itself the next time it
# has a chance.
# For most of the GUI backends this adds an event to the queue
# of the GUI frameworks event loop.
fig.canvas.draw_idle()
try:
# make sure that the GUI framework has a chance to run its event loop
# and clear any GUI events. This needs to be in a try/except block
# because the default implemenation of this method is to raise
# NotImplementedError
fig.canvas.flush_events()
except NotImplementedError:
pass
stop = time.time()
print("{fps:.1f} frames per second".format(fps=200 / (stop - start)))
0707010001fa7a000081a400001782000005de000000015689ead2000007c2000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/pylab_examples/image_interp.py """
The same (small) array, interpolated with three different
interpolation methods.
The center of the pixel at A[i,j] is plotted at i+0.5, i+0.5. If you
are using interpolation='nearest', the region bounded by (i,j) and
(i+1,j+1) will have the same color. If you are using interpolation,
the pixel center will have the same color as it does with nearest, but
other pixels will be interpolated between the neighboring pixels.
Earlier versions of matplotlib (<0.63) tried to hide the edge effects
from you by setting the view limits so that they would not be visible.
A recent bugfix in antigrain, and a new implementation in the
matplotlib._image module which takes advantage of this fix, no longer
makes this necessary. To prevent edge effects, when doing
interpolation, the matplotlib._image module now pads the input array
with identical pixels around the edge. e.g., if you have a 5x5 array
with colors a-y as below
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y
the _image module creates the padded array,
a a b c d e e
a a b c d e e
f f g h i j j
k k l m n o o
p p q r s t t
o u v w x y y
o u v w x y y
does the interpolation/resizing, and then extracts the central region.
This allows you to plot the full range of your array w/o edge effects,
and for example to layer multiple images of different sizes over one
another with different interpolation methods - see
examples/layer_images.py. It also implies a performance hit, as this
new temporary, padded array must be created. Sophisticated
interpolation also implies a performance hit, so if you need maximal
performance or have very large images, interpolation='nearest' is
suggested.
"""
import matplotlib.pyplot as plt
import numpy as np
A = np.random.rand(5, 5)
plt.figure(1)
plt.imshow(A, interpolation='nearest')
plt.grid(True)
plt.figure(2)
plt.imshow(A, interpolation='bilinear')
plt.grid(True)
plt.figure(3)
plt.imshow(A, interpolation='bicubic')
plt.grid(True)
plt.show()
0707010001fab5000081a400001782000005de000000015689ead200000575000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/pylab_examples/scatter_demo2.py """
Demo of scatter plot with varying marker colors and sizes.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
# Load a numpy record array from yahoo csv data with fields date,
# open, close, volume, adj_close from the mpl-data/example directory.
# The record array stores python datetime.date as an object array in
# the date column
datafile = cbook.get_sample_data('goog.npy')
try:
# Python3 cannot load python2 .npy files with datetime(object) arrays
# unless the encoding is set to bytes. Hovever this option was
# not added until numpy 1.10 so this example will only work with
# python 2 or with numpy 1.10 and later
price_data = np.load(datafile, encoding='bytes').view(np.recarray)
except TypeError:
price_data = np.load(datafile).view(np.recarray)
price_data = price_data[-250:] # get the most recent 250 trading days
delta1 = np.diff(price_data.adj_close)/price_data.adj_close[:-1]
# Marker size in units of points^2
volume = (15 * price_data.volume[:-2] / price_data.volume[0])**2
close = 0.003 * price_data.close[:-2] / 0.003 * price_data.open[:-2]
fig, ax = plt.subplots()
ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5)
ax.set_xlabel(r'$\Delta_i$', fontsize=20)
ax.set_ylabel(r'$\Delta_{i+1}$', fontsize=20)
ax.set_title('Volume and percent change')
ax.grid(True)
fig.tight_layout()
plt.show()
0707010001fa92000081a400001782000005de0000000155f2504c000001c6000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/pylab_examples/marker_path.py import matplotlib.pyplot as plt
import matplotlib.path as mpath
import numpy as np
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
verts = np.concatenate([circle.vertices, star.vertices[::-1, ...]])
codes = np.concatenate([circle.codes, star.codes])
cut_star = mpath.Path(verts, codes)
plt.plot(np.arange(10)**2, '--r', marker=cut_star, markersize=15)
plt.show()
0707010001fa90000081a400001782000005de000000015689ead200000387000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/pylab_examples/major_minor_demo2.py #!/usr/bin/env python
"""
Automatic tick selection for major and minor ticks.
Use interactive pan and zoom to see how the tick intervals
change. There will be either 4 or 5 minor tick intervals
per major interval, depending on the major interval.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
# One can supply an argument to AutoMinorLocator to
# specify a fixed number of minor intervals per major interval, e.g.:
# minorLocator = AutoMinorLocator(2)
# would lead to a single minor tick between major ticks.
minorLocator = AutoMinorLocator()
t = np.arange(0.0, 100.0, 0.01)
s = np.sin(2*np.pi*t)*np.exp(-t*0.01)
fig, ax = plt.subplots()
plt.plot(t, s)
ax.xaxis.set_minor_locator(minorLocator)
plt.tick_params(which='both', width=2)
plt.tick_params(which='major', length=7)
plt.tick_params(which='minor', length=4, color='r')
plt.show()
0707010001fa83000081a400001782000005de000000015689ead2000002ab000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/pylab_examples/legend_demo2.py # Make a legend for specific lines.
import matplotlib.pyplot as plt
import numpy as np
t1 = np.arange(0.0, 2.0, 0.1)
t2 = np.arange(0.0, 2.0, 0.01)
# note that plot returns a list of lines. The "l1, = plot" usage
# extracts the first element of the list into l1 using tuple
# unpacking. So l1 is a Line2D instance, not a sequence of lines
l1, = plt.plot(t2, np.exp(-t2))
l2, l3 = plt.plot(t2, np.sin(2 * np.pi * t2), '--go', t1, np.log(1 + t1), '.')
l4, = plt.plot(t2, np.exp(-t2) * np.sin(2 * np.pi * t2), 'rs-.')
plt.legend((l2, l4), ('oscillatory', 'damped'), loc='upper right', shadow=True)
plt.xlabel('time')
plt.ylabel('volts')
plt.title('Damped oscillation')
plt.show()
0707010001fa76000081a400001782000005de000000015689ead20000036a000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/pylab_examples/hyperlinks.py #!/usr/bin/env python
# -*- noplot -*-
"""
This example demonstrates how to set a hyperlinks on various kinds of elements.
This currently only works with the SVG backend.
"""
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
f = plt.figure()
s = plt.scatter([1, 2, 3], [4, 5, 6])
s.set_urls(['http://www.bbc.co.uk/news', 'http://www.google.com', None])
f.canvas.print_figure('scatter.svg')
f = plt.figure()
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians
im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray,
origin='lower', extent=[-3, 3, -3, 3])
im.set_url('http://www.google.com')
f.canvas.print_figure('image.svg')
0707010001faac000081a400001782000005de000000015689ead2000000e9000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/pylab_examples/print_stdout.py # -*- noplot -*-
# print png to standard out
# usage: python print_stdout.py > somefile.png
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.savefig(sys.stdout)
plt.show()
0707010001fa8d000081a400001782000005de000000015689ead200000096000002600000050a00000000000000000000003500000000reloc/matplotlib/examples/pylab_examples/log_test.py import matplotlib.pyplot as plt
import numpy as np
dt = 0.01
t = np.arange(dt, 20.0, dt)
plt.semilogx(t, np.exp(-t/5.0))
plt.grid(True)
plt.show()
0707010001faa1000081a400001782000005de000000015689ead200000629000002600000050a00000000000000000000004700000000reloc/matplotlib/examples/pylab_examples/multiple_yaxis_with_spines.py import matplotlib.pyplot as plt
def make_patch_spines_invisible(ax):
ax.set_frame_on(True)
ax.patch.set_visible(False)
for sp in ax.spines.values():
sp.set_visible(False)
fig, host = plt.subplots()
fig.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
# Offset the right spine of par2. The ticks and label have already been
# placed on the right by twinx above.
par2.spines["right"].set_position(("axes", 1.2))
# Having been created by twinx, par2 has its frame off, so the line of its
# detached spine is invisible. First, activate the frame but make the patch
# and spines invisible.
make_patch_spines_invisible(par2)
# Second, show the right spine.
par2.spines["right"].set_visible(True)
p1, = host.plot([0, 1, 2], [0, 1, 2], "b-", label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], "r-", label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], "g-", label="Velocity")
host.set_xlim(0, 2)
host.set_ylim(0, 2)
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")
host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())
tkw = dict(size=4, width=1.5)
host.tick_params(axis='y', colors=p1.get_color(), **tkw)
par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
par2.tick_params(axis='y', colors=p3.get_color(), **tkw)
host.tick_params(axis='x', **tkw)
lines = [p1, p2, p3]
host.legend(lines, [l.get_label() for l in lines])
plt.show()
0707010001fa23000081a400001782000005de000000015689ead2000002d6000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/pylab_examples/bar_stacked.py #!/usr/bin/env python
# a stacked bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, menMeans, width, color='r', yerr=menStd)
p2 = plt.bar(ind, womenMeans, width, color='y',
bottom=menMeans, yerr=womenStd)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind + width/2., ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
plt.show()
0707010001fa3b000081a400001782000005de000000015689ead20000012e000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/pylab_examples/coords_report.py #!/usr/bin/env python
# override the default reporting of coords
import matplotlib.pyplot as plt
import numpy as np
def millions(x):
return '$%1.1fM' % (x*1e-6)
x = np.random.rand(20)
y = 1e7*np.random.rand(20)
fig, ax = plt.subplots()
ax.fmt_ydata = millions
plt.plot(x, y, 'o')
plt.show()
0707010001fa9d000081a400001782000005de000000015689ead2000006d5000002600000050a00000000000000000000003e00000000reloc/matplotlib/examples/pylab_examples/multicolored_line.py #!/usr/bin/env python
'''
Color parts of a line based on its properties, e.g., slope.
'''
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
z = np.cos(0.5 * (x[:-1] + x[1:])) # first derivative
# Create a colormap for red, green and blue and a norm to color
# f' < -0.5 red, f' > 0.5 blue, and the rest green
cmap = ListedColormap(['r', 'g', 'b'])
norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N)
# Create a set of line segments so that we can color them individually
# This creates the points as a N x 1 x 2 array so that we can stack points
# together easily to get the segments. The segments array for line collection
# needs to be numlines x points per line x 2 (x and y)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
# Create the line collection object, setting the colormapping parameters.
# Have to set the actual values used for colormapping separately.
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(z)
lc.set_linewidth(3)
fig1 = plt.figure()
plt.gca().add_collection(lc)
plt.xlim(x.min(), x.max())
plt.ylim(-1.1, 1.1)
# Now do a second plot coloring the curve using a continuous colormap
t = np.linspace(0, 10, 200)
x = np.cos(np.pi * t)
y = np.sin(t)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, cmap=plt.get_cmap('copper'),
norm=plt.Normalize(0, 10))
lc.set_array(t)
lc.set_linewidth(3)
fig2 = plt.figure()
plt.gca().add_collection(lc)
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.show()
0707010001fa7d000081ed00001782000005de00000001569316c1000002ce000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/pylab_examples/image_origin.py """
You can specify whether images should be plotted with the array origin
x[0,0] in the upper left or upper right by using the origin parameter.
You can also control the default be setting image.origin in your
matplotlibrc file; see http://matplotlib.org/matplotlibrc
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(100.0)
x.shape = (10, 10)
interp = 'bilinear'
#interp = 'nearest'
lim = -2, 11, -2, 6
plt.subplot(211, axisbg='g')
plt.title('blue should be up')
plt.imshow(x, origin='upper', interpolation=interp, cmap='jet')
#plt.axis(lim)
plt.subplot(212, axisbg='y')
plt.title('blue should be down')
plt.imshow(x, origin='lower', interpolation=interp, cmap='jet')
#plt.axis(lim)
plt.show()
0707010001fa28000081a400001782000005de000000015689ead200000508000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/pylab_examples/boxplot_demo.py import matplotlib.pyplot as plt
import numpy as np
# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low), 0)
# basic plot
plt.boxplot(data)
# notched plot
plt.figure()
plt.boxplot(data, 1)
# change outlier point symbols
plt.figure()
plt.boxplot(data, 0, 'gD')
# don't show outlier points
plt.figure()
plt.boxplot(data, 0, '')
# horizontal boxes
plt.figure()
plt.boxplot(data, 0, 'rs', 0)
# change whisker length
plt.figure()
plt.boxplot(data, 0, 'rs', 0, 0.75)
# fake up some more data
spread = np.random.rand(50) * 100
center = np.ones(25) * 40
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
d2 = np.concatenate((spread, center, flier_high, flier_low), 0)
data.shape = (-1, 1)
d2.shape = (-1, 1)
# data = concatenate( (data, d2), 1 )
# Making a 2-D array only works if all the columns are the
# same length. If they are not, then use a list instead.
# This is actually more efficient because boxplot converts
# a 2-D array into a list of vectors internally anyway.
data = [data, d2, d2[::2, 0]]
# multiple box plots on one figure
plt.figure()
plt.boxplot(data)
plt.show()
0707010001fabd000081a400001782000005de000000015689ead2000002a2000002600000050a00000000000000000000004700000000reloc/matplotlib/examples/pylab_examples/shared_axis_across_figures.py """
connect the data limits on the axes in one figure with the axes in
another. This is not the right way to do this for two axes in the
same figure -- use the sharex and sharey property in that case
"""
import numpy as np
import matplotlib.pyplot as plt
fig1 = plt.figure()
fig2 = plt.figure()
ax1 = fig1.add_subplot(111)
ax2 = fig2.add_subplot(111, sharex=ax1, sharey=ax1)
ax1.plot(np.random.rand(100), 'o')
ax2.plot(np.random.rand(100), 'o')
# In the latest release, it is no longer necessary to do anything
# special to share axes across figures:
# ax1.sharex_foreign(ax2)
# ax2.sharex_foreign(ax1)
# ax1.sharey_foreign(ax2)
# ax2.sharey_foreign(ax1)
plt.show()
0707010001fa2c000081a400001782000005de000000015689ead2000009dd000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/pylab_examples/broken_axis.py """
Broken axis example, where the y-axis will have a portion cut out.
"""
import matplotlib.pyplot as plt
import numpy as np
# 30 points between 0 0.2] originally made using np.random.rand(30)*.2
pts = np.array([
0.015, 0.166, 0.133, 0.159, 0.041, 0.024, 0.195, 0.039, 0.161, 0.018,
0.143, 0.056, 0.125, 0.096, 0.094, 0.051, 0.043, 0.021, 0.138, 0.075,
0.109, 0.195, 0.050, 0.074, 0.079, 0.155, 0.020, 0.010, 0.061, 0.008])
# Now let's make two outlier points which are far away from everything.
pts[[3, 14]] += .8
# If we were to simply plot pts, we'd lose most of the interesting
# details due to the outliers. So let's 'break' or 'cut-out' the y-axis
# into two portions - use the top (ax) for the outliers, and the bottom
# (ax2) for the details of the majority of our data
f, (ax, ax2) = plt.subplots(2, 1, sharex=True)
# plot the same data on both axes
ax.plot(pts)
ax2.plot(pts)
# zoom-in / limit the view to different portions of the data
ax.set_ylim(.78, 1.) # outliers only
ax2.set_ylim(0, .22) # most of the data
# hide the spines between ax and ax2
ax.spines['bottom'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax.xaxis.tick_top()
ax.tick_params(labeltop='off') # don't put tick labels at the top
ax2.xaxis.tick_bottom()
# This looks pretty good, and was fairly painless, but you can get that
# cut-out diagonal lines look with just a bit more work. The important
# thing to know here is that in axes coordinates, which are always
# between 0-1, spine endpoints are at these locations (0,0), (0,1),
# (1,0), and (1,1). Thus, we just need to put the diagonals in the
# appropriate corners of each of our axes, and so long as we use the
# right transform and disable clipping.
d = .015 # how big to make the diagonal lines in axes coordinates
# arguments to pass plot, just so we don't keep repeating them
kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)
ax.plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal
ax.plot((1 - d, 1 + d), (-d, +d), **kwargs) # top-right diagonal
kwargs.update(transform=ax2.transAxes) # switch to the bottom axes
ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs) # bottom-left diagonal
ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs) # bottom-right diagonal
# What's cool about this is that now if we vary the distance between
# ax and ax2 via f.subplots_adjust(hspace=...) or plt.subplot_tool(),
# the diagonal lines will move accordingly, and stay right at the tips
# of the spines they are 'breaking'
plt.show()
0707010001fabb000081a400001782000005de000000015689ead200000a07000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/pylab_examples/set_and_get.py """
The pyplot interface allows you to use setp and getp to set and get
object properties, as well as to do introspection on the object
set:
To set the linestyle of a line to be dashed, you can do
>>> line, = plt.plot([1,2,3])
>>> plt.setp(line, linestyle='--')
If you want to know the valid types of arguments, you can provide the
name of the property you want to set without a value
>>> plt.setp(line, 'linestyle')
linestyle: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' ]
If you want to see all the properties that can be set, and their
possible values, you can do
>>> plt.setp(line)
set operates on a single instance or a list of instances. If you are
in query mode introspecting the possible values, only the first
instance in the sequence is used. When actually setting values, all
the instances will be set. e.g., suppose you have a list of two lines,
the following will make both lines thicker and red
>>> x = np.arange(0,1.0,0.01)
>>> y1 = np.sin(2*np.pi*x)
>>> y2 = np.sin(4*np.pi*x)
>>> lines = plt.plot(x, y1, x, y2)
>>> plt.setp(lines, linewidth=2, color='r')
get:
get returns the value of a given attribute. You can use get to query
the value of a single attribute
>>> plt.getp(line, 'linewidth')
0.5
or all the attribute/value pairs
>>> plt.getp(line)
aa = True
alpha = 1.0
antialiased = True
c = b
clip_on = True
color = b
... long listing skipped ...
Aliases:
To reduce keystrokes in interactive mode, a number of properties
have short aliases, e.g., 'lw' for 'linewidth' and 'mec' for
'markeredgecolor'. When calling set or get in introspection mode,
these properties will be listed as 'fullname or aliasname', as in
"""
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 1.0, 0.01)
y1 = np.sin(2*np.pi*x)
y2 = np.sin(4*np.pi*x)
lines = plt.plot(x, y1, x, y2)
l1, l2 = lines
plt.setp(lines, linestyle='--') # set both to dashed
plt.setp(l1, linewidth=2, color='r') # line1 is thick and red
plt.setp(l2, linewidth=1, color='g') # line2 is thicker and green
print('Line setters')
plt.setp(l1)
print('Line getters')
plt.getp(l1)
print('Rectangle setters')
plt.setp(plt.gca().patch)
print('Rectangle getters')
plt.getp(plt.gca().patch)
t = plt.title('Hi mom')
print('Text setters')
plt.setp(t)
print('Text getters')
plt.getp(t)
plt.show()
0707010001fa14000081a400001782000005de000000015689ead200000f98000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/pylab_examples/anchored_artists.py from matplotlib.patches import Rectangle, Ellipse
from matplotlib.offsetbox import AnchoredOffsetbox, AuxTransformBox, VPacker,\
TextArea, DrawingArea
class AnchoredText(AnchoredOffsetbox):
def __init__(self, s, loc, pad=0.4, borderpad=0.5, prop=None, frameon=True):
self.txt = TextArea(s,
minimumdescent=False)
super(AnchoredText, self).__init__(loc, pad=pad, borderpad=borderpad,
child=self.txt,
prop=prop,
frameon=frameon)
class AnchoredSizeBar(AnchoredOffsetbox):
def __init__(self, transform, size, label, loc,
pad=0.1, borderpad=0.1, sep=2, prop=None, frameon=True):
"""
Draw a horizontal bar with the size in data coordinate of the give axes.
A label will be drawn underneath (center-aligned).
pad, borderpad in fraction of the legend font size (or prop)
sep in points.
"""
self.size_bar = AuxTransformBox(transform)
self.size_bar.add_artist(Rectangle((0, 0), size, 0, fc="none"))
self.txt_label = TextArea(label, minimumdescent=False)
self._box = VPacker(children=[self.size_bar, self.txt_label],
align="center",
pad=0, sep=sep)
AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
child=self._box,
prop=prop,
frameon=frameon)
class AnchoredEllipse(AnchoredOffsetbox):
def __init__(self, transform, width, height, angle, loc,
pad=0.1, borderpad=0.1, prop=None, frameon=True):
"""
Draw an ellipse the size in data coordinate of the give axes.
pad, borderpad in fraction of the legend font size (or prop)
"""
self._box = AuxTransformBox(transform)
self.ellipse = Ellipse((0, 0), width, height, angle)
self._box.add_artist(self.ellipse)
AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
child=self._box,
prop=prop,
frameon=frameon)
class AnchoredDrawingArea(AnchoredOffsetbox):
def __init__(self, width, height, xdescent, ydescent,
loc, pad=0.4, borderpad=0.5, prop=None, frameon=True):
self.da = DrawingArea(width, height, xdescent, ydescent)
super(AnchoredDrawingArea, self).__init__(loc, pad=pad, borderpad=borderpad,
child=self.da,
prop=None,
frameon=frameon)
if __name__ == "__main__":
import matplotlib.pyplot as plt
ax = plt.gca()
ax.set_aspect(1.)
at = AnchoredText("Figure 1a",
loc=2, frameon=True)
at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at)
from matplotlib.patches import Circle
ada = AnchoredDrawingArea(20, 20, 0, 0,
loc=1, pad=0., frameon=False)
p = Circle((10, 10), 10)
ada.da.add_artist(p)
ax.add_artist(ada)
# draw an ellipse of width=0.1, height=0.15 in the data coordinate
ae = AnchoredEllipse(ax.transData, width=0.1, height=0.15, angle=0.,
loc=3, pad=0.5, borderpad=0.4, frameon=True)
ax.add_artist(ae)
# draw a horizontal bar with length of 0.1 in Data coordinate
# (ax.transData) with a label underneath.
asb = AnchoredSizeBar(ax.transData,
0.1,
r"1$^{\prime}$",
loc=8,
pad=0.1, borderpad=0.5, sep=5,
frameon=False)
ax.add_artist(asb)
plt.draw()
plt.show()
0707010001fade000081a400001782000005de000000015689ead200000c07000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/pylab_examples/trigradient_demo.py """
Demonstrates computation of gradient with matplotlib.tri.CubicTriInterpolator.
"""
from matplotlib.tri import Triangulation, UniformTriRefiner,\
CubicTriInterpolator
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import math
#-----------------------------------------------------------------------------
# Electrical potential of a dipole
#-----------------------------------------------------------------------------
def dipole_potential(x, y):
""" The electric dipole potential V """
r_sq = x**2 + y**2
theta = np.arctan2(y, x)
z = np.cos(theta)/r_sq
return (np.max(z) - z) / (np.max(z) - np.min(z))
#-----------------------------------------------------------------------------
# Creating a Triangulation
#-----------------------------------------------------------------------------
# First create the x and y coordinates of the points.
n_angles = 30
n_radii = 10
min_radius = 0.2
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2*math.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += math.pi/n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
V = dipole_potential(x, y)
# Create the Triangulation; no triangles specified so Delaunay triangulation
# created.
triang = Triangulation(x, y)
# Mask off unwanted triangles.
xmid = x[triang.triangles].mean(axis=1)
ymid = y[triang.triangles].mean(axis=1)
mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0)
triang.set_mask(mask)
#-----------------------------------------------------------------------------
# Refine data - interpolates the electrical potential V
#-----------------------------------------------------------------------------
refiner = UniformTriRefiner(triang)
tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)
#-----------------------------------------------------------------------------
# Computes the electrical field (Ex, Ey) as gradient of electrical potential
#-----------------------------------------------------------------------------
tci = CubicTriInterpolator(triang, -V)
# Gradient requested here at the mesh nodes but could be anywhere else:
(Ex, Ey) = tci.gradient(triang.x, triang.y)
E_norm = np.sqrt(Ex**2 + Ey**2)
#-----------------------------------------------------------------------------
# Plot the triangulation, the potential iso-contours and the vector field
#-----------------------------------------------------------------------------
plt.figure()
plt.gca().set_aspect('equal')
plt.triplot(triang, color='0.8')
levels = np.arange(0., 1., 0.01)
cmap = cm.get_cmap(name='hot', lut=None)
plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
linewidths=[2.0, 1.0, 1.0, 1.0])
# Plots direction of the electrical vector field
plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
units='xy', scale=10., zorder=3, color='blue',
width=0.007, headwidth=3., headlength=4.)
plt.title('Gradient plot: an electrical dipole')
plt.show()
0707010001fa1f000081a400001782000005de000000015689ead200000248000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/pylab_examples/axes_props.py """
You can control the axis tick and grid properties
"""
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.grid(True)
ticklines = ax.get_xticklines() + ax.get_yticklines()
gridlines = ax.get_xgridlines() + ax.get_ygridlines()
ticklabels = ax.get_xticklabels() + ax.get_yticklabels()
for line in ticklines:
line.set_linewidth(3)
for line in gridlines:
line.set_linestyle('-')
for label in ticklabels:
label.set_color('r')
label.set_fontsize('medium')
plt.show()
0707010001fabe000081a400001782000005de000000015689ead2000006bc000002600000050a00000000000000000000003d00000000reloc/matplotlib/examples/pylab_examples/shared_axis_demo.py """
You can share the x or y axis limits for one axis with another by
passing an axes instance as a sharex or sharey kwarg.
Changing the axis limits on one axes will be reflected automatically
in the other, and vice-versa, so when you navigate with the toolbar
the axes will follow each other on their shared axes. Ditto for
changes in the axis scaling (e.g., log vs linear). However, it is
possible to have differences in tick labeling, e.g., you can selectively
turn off the tick labels on one axes.
The example below shows how to customize the tick labels on the
various axes. Shared axes share the tick locator, tick formatter,
view limits, and transformation (e.g., log, linear). But the ticklabels
themselves do not share properties. This is a feature and not a bug,
because you may want to make the tick labels smaller on the upper
axes, e.g., in the example below.
If you want to turn off the ticklabels for a given axes (e.g., on
subplot(211) or subplot(212), you cannot do the standard trick
setp(ax2, xticklabels=[])
because this changes the tick Formatter, which is shared among all
axes. But you can alter the visibility of the labels, which is a
property
setp( ax2.get_xticklabels(), visible=False)
"""
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.01, 5.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.exp(-t)
s3 = np.sin(4*np.pi*t)
ax1 = plt.subplot(311)
plt.plot(t, s1)
plt.setp(ax1.get_xticklabels(), fontsize=6)
# share x only
ax2 = plt.subplot(312, sharex=ax1)
plt.plot(t, s2)
# make these tick labels invisible
plt.setp(ax2.get_xticklabels(), visible=False)
# share x and y
ax3 = plt.subplot(313, sharex=ax1, sharey=ax1)
plt.plot(t, s3)
plt.xlim(0.01, 5.0)
plt.show()
0707010001fa68000081a400001782000005de00000001569316c100000839000002600000050a00000000000000000000003a00000000reloc/matplotlib/examples/pylab_examples/fonts_demo_kw.py """
Same as fonts_demo using kwargs. If you prefer a more pythonic, OO
style of coding, see examples/fonts_demo.py.
"""
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
import numpy as np
plt.subplot(111, axisbg='w')
alignment = {'horizontalalignment': 'center', 'verticalalignment': 'baseline'}
# Show family options
families = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
t = plt.text(-0.8, 0.9, 'family', size='large', **alignment)
yp = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]
for k, family in enumerate(families):
t = plt.text(-0.8, yp[k], family, family=family, **alignment)
# Show style options
styles = ['normal', 'italic', 'oblique']
t = plt.text(-0.4, 0.9, 'style', **alignment)
for k, style in enumerate(styles):
t = plt.text(-0.4, yp[k], style, family='sans-serif', style=style,
**alignment)
# Show variant options
variants = ['normal', 'small-caps']
t = plt.text(0.0, 0.9, 'variant', **alignment)
for k, variant in enumerate(variants):
t = plt.text(0.0, yp[k], variant, family='serif', variant=variant,
**alignment)
# Show weight options
weights = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
t = plt.text(0.4, 0.9, 'weight', **alignment)
for k, weight in enumerate(weights):
t = plt.text(0.4, yp[k], weight, weight=weight,
**alignment)
# Show size options
sizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
'x-large', 'xx-large']
t = plt.text(0.8, 0.9, 'size', **alignment)
for k, size in enumerate(sizes):
t = plt.text(0.8, yp[k], size, size=size,
**alignment)
x = -0.4
# Show bold italic
t = plt.text(x, 0.1, 'bold italic', style='italic',
weight='bold', size='x-small',
**alignment)
t = plt.text(x, 0.2, 'bold italic',
style='italic', weight='bold', size='medium',
**alignment)
t = plt.text(x, 0.3, 'bold italic',
style='italic', weight='bold', size='x-large',
**alignment)
plt.axis([-1, 1, 0, 1])
plt.show()
0707010001faaa000081a400001782000005de000000015689ead20000014d000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/pylab_examples/polar_demo.py """
Demo of a line plot on a polar axis.
"""
import numpy as np
import matplotlib.pyplot as plt
r = np.arange(0, 3.0, 0.01)
theta = 2 * np.pi * r
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r, color='r', linewidth=3)
ax.set_rmax(2.0)
ax.grid(True)
ax.set_title("A line plot on a polar axis", va='bottom')
plt.show()
0707010001fadd000081a400001782000005de000000015689ead2000005cb000002600000050a00000000000000000000004300000000reloc/matplotlib/examples/pylab_examples/tricontour_vs_griddata.py """
Comparison of griddata and tricontour for an unstructured triangular grid.
"""
from __future__ import print_function
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
import numpy.random as rnd
import matplotlib.mlab as mlab
import time
rnd.seed(0)
npts = 200
ngridx = 100
ngridy = 200
x = rnd.uniform(-2, 2, npts)
y = rnd.uniform(-2, 2, npts)
z = x*np.exp(-x**2 - y**2)
# griddata and contour.
start = time.clock()
plt.subplot(211)
xi = np.linspace(-2.1, 2.1, ngridx)
yi = np.linspace(-2.1, 2.1, ngridy)
zi = mlab.griddata(x, y, z, xi, yi, interp='linear')
plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k')
plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow,
norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max()))
plt.colorbar() # draw colorbar
plt.plot(x, y, 'ko', ms=3)
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.title('griddata and contour (%d points, %d grid points)' %
(npts, ngridx*ngridy))
print('griddata and contour seconds: %f' % (time.clock() - start))
# tricontour.
start = time.clock()
plt.subplot(212)
triang = tri.Triangulation(x, y)
plt.tricontour(x, y, z, 15, linewidths=0.5, colors='k')
plt.tricontourf(x, y, z, 15, cmap=plt.cm.rainbow,
norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max()))
plt.colorbar()
plt.plot(x, y, 'ko', ms=3)
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.title('tricontour (%d points)' % npts)
print('tricontour seconds: %f' % (time.clock() - start))
plt.show()
0707010001fa84000081a400001782000005de000000015689ead20000029f000002600000050a00000000000000000000003900000000reloc/matplotlib/examples/pylab_examples/legend_demo3.py import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1)
# Plot the lines y=x**n for n=1..4.
ax = plt.subplot(2, 1, 1)
for n in range(1, 5):
plt.plot(x, x**n, label="n={0}".format(n))
plt.legend(loc="upper left", bbox_to_anchor=[0, 1],
ncol=2, shadow=True, title="Legend", fancybox=True)
ax.get_legend().get_title().set_color("red")
# Demonstrate some more complex labels.
ax = plt.subplot(2, 1, 2)
plt.plot(x, x**2, label="multi\nline")
half_pi = np.linspace(0, np.pi / 2)
plt.plot(np.sin(half_pi), np.cos(half_pi), label=r"$\frac{1}{2}\pi$")
plt.plot(x, 2**(x**2), label="$2^{x^2}$")
plt.legend(shadow=True, fancybox=True)
plt.show()
0707010001fa45000081ed00001782000005de000000015689ead20000049f000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/pylab_examples/date_demo2.py #!/usr/bin/env python
"""
Show how to make date plots in matplotlib using date tick locators and
formatters. See major_minor_demo1.py for more information on
controlling major and minor ticks
"""
from __future__ import print_function
import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import MONDAY
from matplotlib.finance import quotes_historical_yahoo_ochl
from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter
date1 = datetime.date(2002, 1, 5)
date2 = datetime.date(2003, 12, 1)
# every monday
mondays = WeekdayLocator(MONDAY)
# every 3rd month
months = MonthLocator(range(1, 13), bymonthday=1, interval=3)
monthsFmt = DateFormatter("%b '%y")
quotes = quotes_historical_yahoo_ochl('INTC', date1, date2)
if len(quotes) == 0:
print('Found no quotes')
raise SystemExit
dates = [q[0] for q in quotes]
opens = [q[1] for q in quotes]
fig, ax = plt.subplots()
ax.plot_date(dates, opens, '-')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(monthsFmt)
ax.xaxis.set_minor_locator(mondays)
ax.autoscale_view()
#ax.xaxis.grid(False, 'major')
#ax.xaxis.grid(True, 'minor')
ax.grid(True)
fig.autofmt_xdate()
plt.show()
0707010001fa67000081a400001782000005de00000001569316c100000b37000002600000050a00000000000000000000003700000000reloc/matplotlib/examples/pylab_examples/fonts_demo.py """
Show how to set custom font properties.
For interactive users, you can also use kwargs to the text command,
which requires less typing. See examples/fonts_demo_kw.py
"""
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
plt.subplot(111, axisbg='w')
font0 = FontProperties()
alignment = {'horizontalalignment': 'center', 'verticalalignment': 'baseline'}
# Show family options
families = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
font1 = font0.copy()
font1.set_size('large')
t = plt.text(-0.8, 0.9, 'family', fontproperties=font1,
**alignment)
yp = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]
for k, family in enumerate(families):
font = font0.copy()
font.set_family(family)
t = plt.text(-0.8, yp[k], family, fontproperties=font,
**alignment)
# Show style options
styles = ['normal', 'italic', 'oblique']
t = plt.text(-0.4, 0.9, 'style', fontproperties=font1,
**alignment)
for k, style in enumerate(styles):
font = font0.copy()
font.set_family('sans-serif')
font.set_style(style)
t = plt.text(-0.4, yp[k], style, fontproperties=font,
**alignment)
# Show variant options
variants = ['normal', 'small-caps']
t = plt.text(0.0, 0.9, 'variant', fontproperties=font1,
**alignment)
for k, variant in enumerate(variants):
font = font0.copy()
font.set_family('serif')
font.set_variant(variant)
t = plt.text(0.0, yp[k], variant, fontproperties=font,
**alignment)
# Show weight options
weights = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
t = plt.text(0.4, 0.9, 'weight', fontproperties=font1,
**alignment)
for k, weight in enumerate(weights):
font = font0.copy()
font.set_weight(weight)
t = plt.text(0.4, yp[k], weight, fontproperties=font,
**alignment)
# Show size options
sizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
'x-large', 'xx-large']
t = plt.text(0.8, 0.9, 'size', fontproperties=font1,
**alignment)
for k, size in enumerate(sizes):
font = font0.copy()
font.set_size(size)
t = plt.text(0.8, yp[k], size, fontproperties=font,
**alignment)
# Show bold italic
font = font0.copy()
font.set_style('italic')
font.set_weight('bold')
font.set_size('x-small')
t = plt.text(-0.4, 0.1, 'bold italic', fontproperties=font,
**alignment)
font = font0.copy()
font.set_style('italic')
font.set_weight('bold')
font.set_size('medium')
t = plt.text(-0.4, 0.2, 'bold italic', fontproperties=font,
**alignment)
font = font0.copy()
font.set_style('italic')
font.set_weight('bold')
font.set_size('x-large')
t = plt.text(-0.4, 0.3, 'bold italic', fontproperties=font,
**alignment)
plt.axis([-1, 1, 0, 1])
plt.show()
0707010001fa43000081ed00001782000005de000000015689ead2000005dc000002600000050a00000000000000000000003800000000reloc/matplotlib/examples/pylab_examples/data_helper.py #!/usr/bin/env python
# Some functions to load a return data for the plot demos
from numpy import fromstring, argsort, take, array, resize
import matplotlib.cbook as cbook
def get_two_stock_data():
"""
load stock time and price data for two stocks The return values
(d1,p1,d2,p2) are the trade time (in days) and prices for stocks 1
and 2 (intc and aapl)
"""
ticker1, ticker2 = 'INTC', 'AAPL'
file1 = cbook.get_sample_data('INTC.dat.gz')
file2 = cbook.get_sample_data('AAPL.dat.gz')
M1 = fromstring(file1.read(), '