From fb3fe4a0bc9378fe3f8d6906fb92206ceaf13eca Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 18 Jan 2023 10:59:50 -0500 Subject: [PATCH 1/3] DOC: change all sphinx-gallery section separators to # %% This is so that IDEs will auto detect "cells" and make (re) running sub sections of the code easier for development and debugging. --- examples/animation/animated_histogram.py | 4 +- examples/animation/multiple_axes.py | 2 +- examples/axes_grid1/demo_axes_hbox_divider.py | 2 +- examples/axes_grid1/demo_fixed_size_axes.py | 4 +- examples/axes_grid1/inset_locator_demo.py | 6 +- .../make_room_for_ylabel_using_axesgrid.py | 4 +- .../axes_grid1/scatter_hist_locatable_axes.py | 2 +- examples/axes_grid1/simple_axes_divider1.py | 4 +- examples/axisartist/demo_floating_axes.py | 2 +- examples/color/color_by_yvalue.py | 2 +- examples/color/color_cycle_default.py | 2 +- examples/color/color_demo.py | 2 +- examples/color/colorbar_basics.py | 2 +- examples/color/colormap_reference.py | 4 +- examples/color/custom_cmap.py | 12 +-- examples/color/named_colors.py | 8 +- examples/event_handling/cursor_demo.py | 4 +- .../ginput_manual_clabel_sgskip.py | 6 +- examples/event_handling/pick_event_demo.py | 8 +- .../affine_image.py | 2 +- .../images_contours_and_fields/barb_demo.py | 4 +- .../barcode_demo.py | 2 +- .../colormap_normalizations.py | 12 +-- .../colormap_normalizations_symlognorm.py | 4 +- .../contour_corner_mask.py | 2 +- .../contour_demo.py | 14 ++-- .../contour_image.py | 2 +- .../contour_label_demo.py | 10 +-- .../contourf_demo.py | 8 +- .../contourf_hatching.py | 6 +- .../contourf_log.py | 2 +- .../demo_bboximage.py | 2 +- .../figimage_demo.py | 2 +- .../image_annotated_heatmap.py | 10 +-- .../image_antialiasing.py | 12 +-- .../image_clip_path.py | 2 +- .../images_contours_and_fields/image_demo.py | 12 +-- .../image_masked.py | 2 +- .../image_transparency_blend.py | 6 +- .../image_zcoord.py | 2 +- .../interpolation_methods.py | 2 +- .../irregulardatagrid.py | 2 +- .../layer_images.py | 2 +- .../images_contours_and_fields/matshow.py | 2 +- .../images_contours_and_fields/multi_image.py | 2 +- .../images_contours_and_fields/pcolor_demo.py | 8 +- .../pcolormesh_grids.py | 12 +-- .../pcolormesh_levels.py | 10 +-- .../plot_streamplot.py | 2 +- .../quadmesh_demo.py | 2 +- .../images_contours_and_fields/quiver_demo.py | 8 +- .../quiver_simple_demo.py | 2 +- .../shading_example.py | 2 +- .../specgram_demo.py | 2 +- .../images_contours_and_fields/spy_demos.py | 2 +- .../tricontour_demo.py | 14 ++-- .../tricontour_smooth_delaunay.py | 2 +- .../tricontour_smooth_user.py | 2 +- .../trigradient_demo.py | 2 +- .../triinterp_demo.py | 2 +- .../tripcolor_demo.py | 12 +-- .../triplot_demo.py | 10 +-- .../watermark_image.py | 2 +- .../lines_bars_and_markers/bar_label_demo.py | 12 +-- examples/lines_bars_and_markers/barchart.py | 2 +- .../categorical_variables.py | 2 +- .../curve_error_band.py | 4 +- .../errorbar_limits_simple.py | 4 +- examples/lines_bars_and_markers/fill.py | 6 +- .../fill_between_alpha.py | 6 +- .../fill_between_demo.py | 12 +-- .../fill_betweenx_demo.py | 4 +- .../lines_bars_and_markers/filled_step.py | 6 +- examples/lines_bars_and_markers/hat_graph.py | 2 +- .../horizontal_barchart_distribution.py | 2 +- .../marker_reference.py | 16 ++-- .../lines_bars_and_markers/markevery_demo.py | 8 +- examples/lines_bars_and_markers/psd_demo.py | 6 +- .../scatter_custom_symbol.py | 4 +- .../lines_bars_and_markers/scatter_hist.py | 6 +- .../scatter_with_legend.py | 6 +- .../lines_bars_and_markers/simple_plot.py | 2 +- .../lines_bars_and_markers/span_regions.py | 2 +- .../lines_bars_and_markers/stackplot_demo.py | 4 +- .../lines_bars_and_markers/stairs_demo.py | 6 +- examples/lines_bars_and_markers/stem_plot.py | 4 +- examples/lines_bars_and_markers/step_demo.py | 4 +- examples/lines_bars_and_markers/timeline.py | 4 +- .../xcorr_acorr_demo.py | 2 +- examples/misc/contour_manual.py | 8 +- examples/misc/fig_x.py | 2 +- examples/misc/histogram_path.py | 4 +- examples/misc/hyperlinks_sgskip.py | 4 +- examples/misc/logos2.py | 6 +- examples/misc/multiprocess_sgskip.py | 4 +- examples/misc/rasterization_demo.py | 2 +- examples/misc/tickedstroke_demo.py | 6 +- examples/misc/zorder_demo.py | 4 +- examples/mplot3d/stem3d_demo.py | 4 +- examples/mplot3d/surface3d.py | 2 +- examples/pie_and_polar_charts/bar_of_pie.py | 2 +- examples/pie_and_polar_charts/nested_pie.py | 6 +- .../pie_and_donut_labels.py | 8 +- examples/pie_and_polar_charts/pie_demo2.py | 2 +- examples/pie_and_polar_charts/pie_features.py | 2 +- examples/pie_and_polar_charts/polar_bar.py | 2 +- examples/pie_and_polar_charts/polar_demo.py | 2 +- .../pie_and_polar_charts/polar_error_caps.py | 6 +- examples/pie_and_polar_charts/polar_legend.py | 2 +- .../pie_and_polar_charts/polar_scatter.py | 6 +- examples/pyplots/axline.py | 4 +- examples/pyplots/pyplot_simple.py | 2 +- examples/pyplots/pyplot_text.py | 2 +- examples/pyplots/pyplot_three.py | 2 +- examples/pyplots/pyplot_two_subplots.py | 2 +- examples/scales/asinh_demo.py | 8 +- examples/scales/power_norm.py | 2 +- examples/scales/scales.py | 2 +- examples/scales/symlog_demo.py | 4 +- .../shapes_and_collections/arrow_guide.py | 8 +- .../artist_reference.py | 2 +- .../shapes_and_collections/collections.py | 2 +- .../shapes_and_collections/compound_path.py | 2 +- examples/shapes_and_collections/dolphin.py | 2 +- examples/shapes_and_collections/donut.py | 2 +- .../ellipse_collection.py | 2 +- .../shapes_and_collections/ellipse_demo.py | 4 +- .../shapes_and_collections/fancybox_demo.py | 6 +- examples/shapes_and_collections/hatch_demo.py | 2 +- .../hatch_style_reference.py | 6 +- .../shapes_and_collections/line_collection.py | 4 +- .../patch_collection.py | 2 +- examples/shapes_and_collections/path_patch.py | 2 +- .../shapes_and_collections/quad_bezier.py | 2 +- examples/shapes_and_collections/scatter.py | 2 +- examples/showcase/anatomy.py | 2 +- examples/showcase/stock_prices.py | 2 +- examples/showcase/xkcd.py | 4 +- examples/specialty_plots/anscombe.py | 2 +- examples/specialty_plots/radar_chart.py | 2 +- examples/specialty_plots/sankey_basics.py | 14 ++-- examples/specialty_plots/sankey_links.py | 2 +- examples/specialty_plots/sankey_rankine.py | 2 +- examples/specialty_plots/skewt.py | 2 +- examples/spines/spine_placement_demo.py | 6 +- examples/statistics/barchart_demo.py | 2 +- examples/statistics/boxplot.py | 6 +- examples/statistics/boxplot_color.py | 2 +- examples/statistics/boxplot_demo.py | 8 +- examples/statistics/boxplot_vs_violin.py | 2 +- examples/statistics/bxp.py | 8 +- examples/statistics/confidence_ellipse.py | 12 +-- examples/statistics/customized_violin.py | 2 +- examples/statistics/errorbar.py | 2 +- examples/statistics/errorbar_features.py | 2 +- examples/statistics/errorbar_limits.py | 2 +- examples/statistics/errorbars_and_boxes.py | 2 +- examples/statistics/hexbin_demo.py | 2 +- examples/statistics/hist.py | 10 +-- examples/statistics/histogram_cumulative.py | 2 +- examples/statistics/histogram_features.py | 2 +- examples/statistics/histogram_histtypes.py | 2 +- examples/statistics/histogram_multihist.py | 2 +- .../multiple_histograms_side_by_side.py | 2 +- examples/statistics/time_series_histogram.py | 2 +- examples/statistics/violinplot.py | 2 +- .../auto_subplots_adjust.py | 2 +- .../axes_box_aspect.py | 16 ++-- .../subplots_axes_and_figures/axes_margins.py | 4 +- .../colorbar_placement.py | 8 +- .../custom_figure_class.py | 2 +- .../demo_constrained_layout.py | 8 +- .../demo_tight_layout.py | 18 ++--- .../figure_size_units.py | 12 +-- .../subplots_axes_and_figures/figure_title.py | 2 +- .../subplots_axes_and_figures/geo_demo.py | 8 +- examples/subplots_axes_and_figures/mosaic.py | 44 +++++------ .../multiple_figs_demo.py | 6 +- .../secondary_axis.py | 8 +- .../subplots_axes_and_figures/subfigures.py | 6 +- examples/subplots_axes_and_figures/subplot.py | 4 +- .../subplots_demo.py | 26 +++---- .../subplots_axes_and_figures/two_scales.py | 2 +- .../zoom_inset_axes.py | 2 +- .../accented_text.py | 2 +- .../align_ylabels.py | 4 +- .../angle_annotation.py | 8 +- .../angles_on_bracket_arrows.py | 2 +- .../annotate_transform.py | 2 +- .../annotation_basic.py | 2 +- .../annotation_demo.py | 12 +-- .../annotation_polar.py | 2 +- .../custom_legends.py | 4 +- .../demo_annotation_box.py | 2 +- .../demo_text_rotation_mode.py | 2 +- .../fancyarrow_demo.py | 2 +- .../figlegend_demo.py | 2 +- .../font_family_rc.py | 8 +- .../text_labels_and_annotations/font_file.py | 2 +- .../label_subplots.py | 6 +- .../text_labels_and_annotations/legend.py | 2 +- .../legend_demo.py | 8 +- .../line_with_text.py | 2 +- .../mathtext_asarray.py | 2 +- .../text_labels_and_annotations/tex_demo.py | 2 +- .../text_alignment.py | 2 +- .../text_commands.py | 2 +- .../titles_demo.py | 4 +- .../watermark_text.py | 2 +- examples/ticks/auto_ticks.py | 4 +- .../ticks/colorbar_tick_labelling_demo.py | 4 +- examples/ticks/custom_ticker1.py | 2 +- examples/ticks/date_concise_formatter.py | 10 +-- examples/ticks/date_formatters_locators.py | 2 +- examples/ticks/date_index_formatter.py | 2 +- examples/ticks/date_precision_and_epochs.py | 16 ++-- examples/ticks/dollar_ticks.py | 2 +- examples/ticks/fig_axes_customize_simple.py | 4 +- examples/ticks/major_minor_demo.py | 4 +- examples/ticks/scalarformatter.py | 6 +- examples/ticks/tick-formatters.py | 6 +- examples/ticks/tick_labels_from_values.py | 2 +- examples/ticks/ticks_too_many.py | 6 +- examples/units/ellipse_with_units.py | 4 +- examples/user_interfaces/canvasagg.py | 2 +- .../web_application_server_sgskip.py | 2 +- examples/userdemo/connectionstyle_demo.py | 2 +- examples/userdemo/custom_boxstyle01.py | 4 +- examples/userdemo/demo_gridspec03.py | 2 +- examples/widgets/annotated_cursor.py | 2 +- examples/widgets/buttons.py | 2 +- examples/widgets/check_buttons.py | 2 +- examples/widgets/cursor.py | 2 +- .../widgets/lasso_selector_demo_sgskip.py | 2 +- examples/widgets/mouse_cursor.py | 2 +- examples/widgets/multicursor.py | 2 +- examples/widgets/polygon_selector_demo.py | 2 +- examples/widgets/polygon_selector_simple.py | 6 +- examples/widgets/radio_buttons.py | 2 +- examples/widgets/range_slider.py | 2 +- examples/widgets/rectangle_selector.py | 2 +- examples/widgets/slider_demo.py | 2 +- examples/widgets/slider_snap_demo.py | 2 +- examples/widgets/span_selector.py | 2 +- examples/widgets/textbox.py | 2 +- tutorials/advanced/blitting.py | 6 +- tutorials/advanced/path_tutorial.py | 4 +- tutorials/advanced/patheffects_guide.py | 8 +- tutorials/advanced/transforms_tutorial.py | 18 ++--- tutorials/colors/colorbar_only.py | 6 +- tutorials/colors/colormap-manipulation.py | 34 ++++----- tutorials/colors/colormapnorms.py | 14 ++-- tutorials/colors/colormaps.py | 22 +++--- tutorials/colors/colors.py | 4 +- tutorials/intermediate/arranging_axes.py | 30 ++++---- tutorials/intermediate/artists.py | 14 ++-- tutorials/intermediate/autoscale.py | 22 +++--- tutorials/intermediate/color_cycle.py | 10 +-- .../intermediate/constrainedlayout_guide.py | 74 +++++++++---------- tutorials/intermediate/imshow_extent.py | 6 +- tutorials/intermediate/legend_guide.py | 20 ++--- tutorials/intermediate/tight_layout_guide.py | 30 ++++---- tutorials/introductory/animation_tutorial.py | 6 +- tutorials/introductory/customizing.py | 18 ++--- tutorials/introductory/images.py | 26 +++---- tutorials/introductory/lifecycle.py | 30 ++++---- tutorials/introductory/pyplot.py | 22 +++--- tutorials/introductory/quick_start.py | 40 +++++----- tutorials/text/annotations.py | 46 ++++++------ tutorials/text/text_intro.py | 34 ++++----- tutorials/text/text_props.py | 2 +- 271 files changed, 825 insertions(+), 825 deletions(-) diff --git a/examples/animation/animated_histogram.py b/examples/animation/animated_histogram.py index 254155b62a5e..8b918895de71 100644 --- a/examples/animation/animated_histogram.py +++ b/examples/animation/animated_histogram.py @@ -21,7 +21,7 @@ data = np.random.randn(1000) n, _ = np.histogram(data, HIST_BINS) -############################################################################### +# %% # To animate the histogram, we need an ``animate`` function, which generates # a random set of numbers and updates the heights of rectangles. We utilize a # python closure to track an instance of `.BarContainer` whose `.Rectangle` @@ -39,7 +39,7 @@ def animate(frame_number): return bar_container.patches return animate -############################################################################### +# %% # Using :func:`~matplotlib.pyplot.hist` allows us to get an instance of # `.BarContainer`, which is a collection of `.Rectangle` instances. Calling # ``prepare_animation`` will define ``animate`` function working with supplied diff --git a/examples/animation/multiple_axes.py b/examples/animation/multiple_axes.py index 4a45aa28ea8c..349c979e267b 100644 --- a/examples/animation/multiple_axes.py +++ b/examples/animation/multiple_axes.py @@ -70,7 +70,7 @@ def animate(i): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/axes_grid1/demo_axes_hbox_divider.py b/examples/axes_grid1/demo_axes_hbox_divider.py index b3bfcc508468..81e0d09f2d6a 100644 --- a/examples/axes_grid1/demo_axes_hbox_divider.py +++ b/examples/axes_grid1/demo_axes_hbox_divider.py @@ -33,7 +33,7 @@ plt.show() -############################################################################### +# %% # Using a `.VBoxDivider` to arrange subplots. # # Note that both axes' location are adjusted so that they have diff --git a/examples/axes_grid1/demo_fixed_size_axes.py b/examples/axes_grid1/demo_fixed_size_axes.py index 85ab092982e4..3981aadd9898 100644 --- a/examples/axes_grid1/demo_fixed_size_axes.py +++ b/examples/axes_grid1/demo_fixed_size_axes.py @@ -8,7 +8,7 @@ from mpl_toolkits.axes_grid1 import Divider, Size -############################################################################### +# %% fig = plt.figure(figsize=(6, 6)) @@ -26,7 +26,7 @@ ax.plot([1, 2, 3]) -############################################################################### +# %% fig = plt.figure(figsize=(6, 6)) diff --git a/examples/axes_grid1/inset_locator_demo.py b/examples/axes_grid1/inset_locator_demo.py index ae1d56cda667..8c0c68b8785d 100644 --- a/examples/axes_grid1/inset_locator_demo.py +++ b/examples/axes_grid1/inset_locator_demo.py @@ -5,7 +5,7 @@ """ -############################################################################### +# %% # The `.inset_locator`'s `~.inset_locator.inset_axes` allows # easily placing insets in the corners of the axes by specifying a width and # height and optionally a location (loc) that accepts locations as codes, @@ -43,7 +43,7 @@ plt.show() -############################################################################### +# %% # The parameters *bbox_to_anchor* and *bbox_transform* can be used for a more # fine-grained control over the inset position and size or even to position # the inset at completely arbitrary positions. @@ -100,7 +100,7 @@ plt.show() -############################################################################### +# %% # In the above the axes transform together with 4-tuple bounding boxes has been # used as it mostly is useful to specify an inset relative to the axes it is # an inset to. However, other use cases are equally possible. The following diff --git a/examples/axes_grid1/make_room_for_ylabel_using_axesgrid.py b/examples/axes_grid1/make_room_for_ylabel_using_axesgrid.py index 802af8739b97..f350af22ee00 100644 --- a/examples/axes_grid1/make_room_for_ylabel_using_axesgrid.py +++ b/examples/axes_grid1/make_room_for_ylabel_using_axesgrid.py @@ -17,7 +17,7 @@ make_axes_area_auto_adjustable(ax) -############################################################################### +# %% fig = plt.figure() ax1 = fig.add_axes([0, 0, 1, 0.5]) @@ -31,7 +31,7 @@ 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]) -############################################################################### +# %% fig = plt.figure() ax1 = fig.add_axes([0, 0, 1, 1]) diff --git a/examples/axes_grid1/scatter_hist_locatable_axes.py b/examples/axes_grid1/scatter_hist_locatable_axes.py index c605e9e81258..e560cd969895 100644 --- a/examples/axes_grid1/scatter_hist_locatable_axes.py +++ b/examples/axes_grid1/scatter_hist_locatable_axes.py @@ -63,7 +63,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/axes_grid1/simple_axes_divider1.py b/examples/axes_grid1/simple_axes_divider1.py index 0ead9c27ae9f..d86117760548 100644 --- a/examples/axes_grid1/simple_axes_divider1.py +++ b/examples/axes_grid1/simple_axes_divider1.py @@ -18,7 +18,7 @@ def label_axes(ax, text): left=False, labelleft=False) -############################################################################## +# %% # Fixed axes sizes; fixed paddings. fig = plt.figure(figsize=(6, 6)) @@ -42,7 +42,7 @@ def label_axes(ax, text): ax4 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, nx1=4, ny=0)) label_axes(ax4, "nx=2, nx1=4, ny=0") -############################################################################## +# %% # Axes sizes that scale with the figure size; fixed paddings. fig = plt.figure(figsize=(6, 6)) diff --git a/examples/axisartist/demo_floating_axes.py b/examples/axisartist/demo_floating_axes.py index c87b44818ff7..90e43f198127 100644 --- a/examples/axisartist/demo_floating_axes.py +++ b/examples/axisartist/demo_floating_axes.py @@ -145,7 +145,7 @@ def setup_axes3(fig, rect): return ax1, aux_ax -########################################################## +# %% fig = plt.figure(figsize=(8, 4)) fig.subplots_adjust(wspace=0.3, left=0.05, right=0.95) diff --git a/examples/color/color_by_yvalue.py b/examples/color/color_by_yvalue.py index 585fe4dc86f8..a13796f50a82 100644 --- a/examples/color/color_by_yvalue.py +++ b/examples/color/color_by_yvalue.py @@ -22,7 +22,7 @@ ax.plot(t, smiddle, t, slower, t, supper) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/color/color_cycle_default.py b/examples/color/color_cycle_default.py index d098821d3306..e7ac1dbf0ae9 100644 --- a/examples/color/color_cycle_default.py +++ b/examples/color/color_cycle_default.py @@ -40,7 +40,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/color/color_demo.py b/examples/color/color_demo.py index 8a161442184b..b36585b2e188 100644 --- a/examples/color/color_demo.py +++ b/examples/color/color_demo.py @@ -61,7 +61,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/color/colorbar_basics.py b/examples/color/colorbar_basics.py index f31ded0100c7..c1a911132552 100644 --- a/examples/color/colorbar_basics.py +++ b/examples/color/colorbar_basics.py @@ -45,7 +45,7 @@ cbar.minorticks_on() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/color/colormap_reference.py b/examples/color/colormap_reference.py index 549345edffab..be497c48663e 100644 --- a/examples/color/colormap_reference.py +++ b/examples/color/colormap_reference.py @@ -68,7 +68,7 @@ def plot_color_gradients(cmap_category, cmap_list): plot_color_gradients(cmap_category, cmap_list) -############################################################################### +# %% # .. _reverse-cmap: # # Reversed colormaps @@ -83,7 +83,7 @@ def plot_color_gradients(cmap_category, cmap_list): # The built-in reversed colormaps are generated using `.Colormap.reversed`. # For an example, see :ref:`reversing-colormap` -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/color/custom_cmap.py b/examples/color/custom_cmap.py index a99127d972e6..bf90cfa28298 100644 --- a/examples/color/custom_cmap.py +++ b/examples/color/custom_cmap.py @@ -108,7 +108,7 @@ Z = np.cos(X) * np.sin(Y) * 10 -############################################################################### +# %% # Colormaps from a list # --------------------- @@ -126,7 +126,7 @@ fig.colorbar(im, ax=ax) -############################################################################### +# %% # Custom colormaps # ---------------- @@ -202,14 +202,14 @@ } -############################################################################### +# %% # Now we will use this example to illustrate 2 ways of # handling custom colormaps. # First, the most direct and explicit: blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1) -############################################################################### +# %% # Second, create the map explicitly and register it. # Like the first method, this method works with any kind # of Colormap, not just @@ -219,7 +219,7 @@ mpl.colormaps.register(LinearSegmentedColormap('BlueRed3', cdict3)) mpl.colormaps.register(LinearSegmentedColormap('BlueRedAlpha', cdict4)) -############################################################################### +# %% # Make the figure, with 4 subplots: fig, axs = plt.subplots(2, 2, figsize=(6, 9)) @@ -264,7 +264,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/color/named_colors.py b/examples/color/named_colors.py index 5a8e3667689a..35da0f41b4a6 100644 --- a/examples/color/named_colors.py +++ b/examples/color/named_colors.py @@ -73,21 +73,21 @@ def plot_colortable(colors, *, ncols=4, sort_colors=True): return fig -############################################################################# +# %% # ----------- # Base colors # ----------- plot_colortable(mcolors.BASE_COLORS, ncols=3, sort_colors=False) -############################################################################# +# %% # --------------- # Tableau Palette # --------------- plot_colortable(mcolors.TABLEAU_COLORS, ncols=2, sort_colors=False) -############################################################################# +# %% # ---------- # CSS Colors # ---------- @@ -96,7 +96,7 @@ def plot_colortable(colors, *, ncols=4, sort_colors=True): plot_colortable(mcolors.CSS4_COLORS) plt.show() -############################################################################# +# %% # ----------- # XKCD Colors # ----------- diff --git a/examples/event_handling/cursor_demo.py b/examples/event_handling/cursor_demo.py index 30604b549542..c82ddaaf93bf 100644 --- a/examples/event_handling/cursor_demo.py +++ b/examples/event_handling/cursor_demo.py @@ -72,7 +72,7 @@ def on_mouse_move(self, event): fig.canvas.mpl_connect('motion_notify_event', cursor.on_mouse_move) -############################################################################## +# %% # Faster redrawing using blitting # """"""""""""""""""""""""""""""" # This technique stores the rendered plot as a background image. Only the @@ -153,7 +153,7 @@ def on_mouse_move(self, event): fig.canvas.mpl_connect('motion_notify_event', blitted_cursor.on_mouse_move) -############################################################################## +# %% # Snapping to data points # """"""""""""""""""""""" # The following cursor snaps its position to the data points of a `.Line2D` diff --git a/examples/event_handling/ginput_manual_clabel_sgskip.py b/examples/event_handling/ginput_manual_clabel_sgskip.py index 00e548bfccb4..c13e751eceb8 100644 --- a/examples/event_handling/ginput_manual_clabel_sgskip.py +++ b/examples/event_handling/ginput_manual_clabel_sgskip.py @@ -26,7 +26,7 @@ def tellme(s): plt.title(s, fontsize=16) plt.draw() -################################################## +# %% # Define a triangle by clicking three points @@ -59,7 +59,7 @@ def tellme(s): p.remove() -################################################## +# %% # Now contour according to distance from triangle # corners - just an example @@ -79,7 +79,7 @@ def f(x, y, pts): 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') diff --git a/examples/event_handling/pick_event_demo.py b/examples/event_handling/pick_event_demo.py index 63f2bd130f17..14269a3e69b9 100644 --- a/examples/event_handling/pick_event_demo.py +++ b/examples/event_handling/pick_event_demo.py @@ -84,7 +84,7 @@ def pick_handler(event): np.random.seed(19680801) -############################################################################# +# %% # Simple picking, lines, rectangles and text # ------------------------------------------ @@ -117,7 +117,7 @@ def onpick1(event): fig.canvas.mpl_connect('pick_event', onpick1) -############################################################################# +# %% # Picking with a custom hit test function # --------------------------------------- # You can define custom pickers by setting picker to a callable function. The @@ -163,7 +163,7 @@ def onpick2(event): fig.canvas.mpl_connect('pick_event', onpick2) -############################################################################# +# %% # Picking on a scatter plot # ------------------------- # A scatter plot is backed by a `~matplotlib.collections.PathCollection`. @@ -181,7 +181,7 @@ def onpick3(event): fig.canvas.mpl_connect('pick_event', onpick3) -############################################################################# +# %% # Picking images # -------------- # Images plotted using `.Axes.imshow` are `~matplotlib.image.AxesImage` diff --git a/examples/images_contours_and_fields/affine_image.py b/examples/images_contours_and_fields/affine_image.py index 4b131d95588e..9b8fe6e68c10 100644 --- a/examples/images_contours_and_fields/affine_image.py +++ b/examples/images_contours_and_fields/affine_image.py @@ -64,7 +64,7 @@ def do_plot(ax, Z, transform): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/barb_demo.py b/examples/images_contours_and_fields/barb_demo.py index 4530dc813b3d..d3ade99d927c 100644 --- a/examples/images_contours_and_fields/barb_demo.py +++ b/examples/images_contours_and_fields/barb_demo.py @@ -47,7 +47,7 @@ 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, ax2 = plt.subplots() @@ -55,7 +55,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/barcode_demo.py b/examples/images_contours_and_fields/barcode_demo.py index 20fec531c097..109878edc0e0 100644 --- a/examples/images_contours_and_fields/barcode_demo.py +++ b/examples/images_contours_and_fields/barcode_demo.py @@ -37,7 +37,7 @@ interpolation='nearest') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/colormap_normalizations.py b/examples/images_contours_and_fields/colormap_normalizations.py index 7ad3423cce68..1a4420c81de9 100644 --- a/examples/images_contours_and_fields/colormap_normalizations.py +++ b/examples/images_contours_and_fields/colormap_normalizations.py @@ -12,7 +12,7 @@ import matplotlib.pyplot as plt import matplotlib.colors as colors -############################################################################### +# %% # Lognorm: Instead of pcolor log10(Z1) you can have colorbars that have # the exponential labels using a norm. @@ -38,7 +38,7 @@ fig.colorbar(pcm, ax=ax[1], extend='max') -############################################################################### +# %% # PowerNorm: Here a power-law trend in X partially obscures a rectified # sine wave in Y. We can remove the power law using a PowerNorm. @@ -54,7 +54,7 @@ pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r', shading='nearest') fig.colorbar(pcm, ax=ax[1], extend='max') -############################################################################### +# %% # SymLogNorm: two humps, one negative and one positive, The positive # with 5-times the amplitude. Linearly, you cannot see detail in the # negative hump. Here we logarithmically scale the positive and @@ -77,7 +77,7 @@ shading='nearest') fig.colorbar(pcm, ax=ax[1], extend='both') -############################################################################### +# %% # Custom Norm: An example with a customized normalization. This one # uses the example above, and normalizes the negative data differently # from the positive. @@ -103,7 +103,7 @@ def __call__(self, value, clip=None): return np.ma.masked_array(np.interp(value, x, y)) -##### +# %% fig, ax = plt.subplots(2, 1) pcm = ax[0].pcolormesh(X, Y, Z, @@ -115,7 +115,7 @@ def __call__(self, value, clip=None): shading='nearest') fig.colorbar(pcm, ax=ax[1], extend='both') -############################################################################### +# %% # BoundaryNorm: For this one you provide the boundaries for your colors, # and the Norm puts the first color in between the first pair, the # second color between the second pair, etc. diff --git a/examples/images_contours_and_fields/colormap_normalizations_symlognorm.py b/examples/images_contours_and_fields/colormap_normalizations_symlognorm.py index c5bd9d05f4dc..22eecd7caa18 100644 --- a/examples/images_contours_and_fields/colormap_normalizations_symlognorm.py +++ b/examples/images_contours_and_fields/colormap_normalizations_symlognorm.py @@ -8,7 +8,7 @@ .. redirect-from:: /gallery/userdemo/colormap_normalization_symlognorm """ -############################################################################### +# %% # Synthetic dataset consisting of two humps, one negative and one positive, # the positive with 8-times the amplitude. # Linearly, the negative hump is almost invisible, @@ -52,7 +52,7 @@ def rbf(x, y): ax[1].text(-2.5, 1.5, 'linear') -############################################################################### +# %% # In order to find the best visualization for any particular dataset, # it may be necessary to experiment with multiple different color scales. # As well as the `~.colors.SymLogNorm` scaling, there is also diff --git a/examples/images_contours_and_fields/contour_corner_mask.py b/examples/images_contours_and_fields/contour_corner_mask.py index c0854675c6d2..6467f1248c0b 100644 --- a/examples/images_contours_and_fields/contour_corner_mask.py +++ b/examples/images_contours_and_fields/contour_corner_mask.py @@ -37,7 +37,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/contour_demo.py b/examples/images_contours_and_fields/contour_demo.py index 266acccf2409..3716a00b844a 100644 --- a/examples/images_contours_and_fields/contour_demo.py +++ b/examples/images_contours_and_fields/contour_demo.py @@ -23,7 +23,7 @@ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) Z = (Z1 - Z2) * 2 -############################################################################### +# %% # Create a simple contour plot with labels using default colors. The inline # argument to clabel will control whether the labels are draw over the line # segments of the contour, removing the lines beneath the label. @@ -33,7 +33,7 @@ ax.clabel(CS, inline=True, fontsize=10) ax.set_title('Simplest default with labels') -############################################################################### +# %% # Contour labels can be placed manually by providing list of positions (in data # coordinate). See :doc:`/gallery/event_handling/ginput_manual_clabel_sgskip` # for interactive placement. @@ -45,7 +45,7 @@ ax.clabel(CS, inline=True, fontsize=10, manual=manual_locations) ax.set_title('labels at selected locations') -############################################################################### +# %% # You can force all the contours to be the same color. fig, ax = plt.subplots() @@ -53,7 +53,7 @@ ax.clabel(CS, fontsize=9, inline=True) ax.set_title('Single color - negative contours dashed') -############################################################################### +# %% # You can set negative contours to be solid instead of dashed: plt.rcParams['contour.negative_linestyle'] = 'solid' @@ -62,7 +62,7 @@ ax.clabel(CS, fontsize=9, inline=True) ax.set_title('Single color - negative contours solid') -############################################################################### +# %% # And you can manually specify the colors of the contour fig, ax = plt.subplots() @@ -73,7 +73,7 @@ ax.clabel(CS, fontsize=9, inline=True) ax.set_title('Crazy lines') -############################################################################### +# %% # Or you can use a colormap to specify the colors; the default # colormap will be used for the contour lines @@ -107,7 +107,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/contour_image.py b/examples/images_contours_and_fields/contour_image.py index a2a07f20f273..de21be680b66 100644 --- a/examples/images_contours_and_fields/contour_image.py +++ b/examples/images_contours_and_fields/contour_image.py @@ -95,7 +95,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/contour_label_demo.py b/examples/images_contours_and_fields/contour_label_demo.py index 0ea3d3694ca1..e8d096eb615d 100644 --- a/examples/images_contours_and_fields/contour_label_demo.py +++ b/examples/images_contours_and_fields/contour_label_demo.py @@ -14,7 +14,7 @@ import matplotlib.ticker as ticker import matplotlib.pyplot as plt -############################################################################### +# %% # Define our surface delta = 0.025 @@ -25,7 +25,7 @@ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) Z = (Z1 - Z2) * 2 -############################################################################### +# %% # Make contour labels with custom level formatters @@ -44,7 +44,7 @@ def fmt(x): ax.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10) -############################################################################### +# %% # Label contours with arbitrary strings using a dictionary fig1, ax1 = plt.subplots() @@ -60,7 +60,7 @@ def fmt(x): # Label every other level using strings ax1.clabel(CS1, CS1.levels[::2], inline=True, fmt=fmt, fontsize=10) -############################################################################### +# %% # Use a Formatter fig2, ax2 = plt.subplots() @@ -73,7 +73,7 @@ def fmt(x): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/contourf_demo.py b/examples/images_contours_and_fields/contourf_demo.py index d7b1bbe9c284..6b579934678c 100644 --- a/examples/images_contours_and_fields/contourf_demo.py +++ b/examples/images_contours_and_fields/contourf_demo.py @@ -33,7 +33,7 @@ interior = np.sqrt(X**2 + Y**2) < 0.5 Z[interior] = np.ma.masked -############################################################################# +# %% # Automatic contour levels # ------------------------ # We are using automatic selection of contour levels; this is usually not such @@ -60,7 +60,7 @@ # Add the contour line levels to the colorbar cbar.add_lines(CS2) -############################################################################# +# %% # Explicit contour levels # ----------------------- # Now make a contour plot with the levels specified, and with the colormap @@ -89,7 +89,7 @@ # needs from the ContourSet object, CS3. fig2.colorbar(CS3) -############################################################################# +# %% # Extension settings # ------------------ # Illustrate all 4 possible "extend" settings: @@ -111,7 +111,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/contourf_hatching.py b/examples/images_contours_and_fields/contourf_hatching.py index 10b4698eadc9..f8131b41cfa5 100644 --- a/examples/images_contours_and_fields/contourf_hatching.py +++ b/examples/images_contours_and_fields/contourf_hatching.py @@ -17,7 +17,7 @@ # we no longer need x and y to be 2 dimensional, so flatten them. x, y = x.flatten(), y.flatten() -############################################################################### +# %% # Plot 1: the simplest hatched plot with a colorbar fig1, ax1 = plt.subplots() @@ -25,7 +25,7 @@ cmap='gray', extend='both', alpha=0.5) fig1.colorbar(cs) -############################################################################### +# %% # Plot 2: a plot of hatches without color with a legend fig2, ax2 = plt.subplots() @@ -40,7 +40,7 @@ ax2.legend(artists, labels, handleheight=2, framealpha=1) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/contourf_log.py b/examples/images_contours_and_fields/contourf_log.py index 69b25d53df70..ae6b50dcd3f2 100644 --- a/examples/images_contours_and_fields/contourf_log.py +++ b/examples/images_contours_and_fields/contourf_log.py @@ -48,7 +48,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/demo_bboximage.py b/examples/images_contours_and_fields/demo_bboximage.py index 050d661a47ff..8e857e7a423d 100644 --- a/examples/images_contours_and_fields/demo_bboximage.py +++ b/examples/images_contours_and_fields/demo_bboximage.py @@ -50,7 +50,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/figimage_demo.py b/examples/images_contours_and_fields/figimage_demo.py index 1b1f1b19d694..5811d345693b 100644 --- a/examples/images_contours_and_fields/figimage_demo.py +++ b/examples/images_contours_and_fields/figimage_demo.py @@ -19,7 +19,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/image_annotated_heatmap.py b/examples/images_contours_and_fields/image_annotated_heatmap.py index f873423f50b0..9abbdeae118f 100644 --- a/examples/images_contours_and_fields/image_annotated_heatmap.py +++ b/examples/images_contours_and_fields/image_annotated_heatmap.py @@ -17,7 +17,7 @@ """ -############################################################################## +# %% # # A simple categorical heatmap # ---------------------------- @@ -79,7 +79,7 @@ plt.show() -############################################################################# +# %% # Using the helper function code style # ------------------------------------ # @@ -216,7 +216,7 @@ def annotate_heatmap(im, data=None, valfmt="{x:.2f}", return texts -########################################################################## +# %% # The above now allows us to keep the actual plot creation pretty compact. # @@ -230,7 +230,7 @@ def annotate_heatmap(im, data=None, valfmt="{x:.2f}", plt.show() -############################################################################# +# %% # Some more complex heatmap examples # ---------------------------------- # @@ -301,7 +301,7 @@ def func(x, pos): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/image_antialiasing.py b/examples/images_contours_and_fields/image_antialiasing.py index 0ada6251b653..800f1848748e 100644 --- a/examples/images_contours_and_fields/image_antialiasing.py +++ b/examples/images_contours_and_fields/image_antialiasing.py @@ -28,7 +28,7 @@ import numpy as np import matplotlib.pyplot as plt -############################################################################### +# %% # First we generate a 450x450 pixel image with varying frequency content: N = 450 x = np.arange(N) / N - 0.5 @@ -46,7 +46,7 @@ a[:int(N / 2), :][R[:int(N / 2), :] < 0.3] = 1 aa[:, int(N / 3):] = a[:, int(N / 3):] a = aa -############################################################################### +# %% # The following images are subsampled from 450 data pixels to either # 125 pixels or 250 pixels (depending on your display). # The Moiré patterns in the 'nearest' interpolation are caused by the @@ -80,7 +80,7 @@ ax.set_title(f"interpolation='{interp}'\nspace='{space}'") plt.show() -############################################################################### +# %% # Even up-sampling an image with 'nearest' interpolation will lead to Moiré # patterns when the upsampling factor is not integer. The following image # upsamples 500 data pixels to 530 rendered pixels. You may note a grid of @@ -93,14 +93,14 @@ ax.set_title("upsampled by factor a 1.048, interpolation='nearest'") plt.show() -############################################################################### +# %% # Better antialiasing algorithms can reduce this effect: fig, ax = plt.subplots(figsize=(6.8, 6.8)) ax.imshow(a, interpolation='antialiased', cmap='gray') ax.set_title("upsampled by factor a 1.048, interpolation='antialiased'") plt.show() -############################################################################### +# %% # Apart from the default 'hanning' antialiasing, `~.Axes.imshow` supports a # number of different interpolation algorithms, which may work better or # worse depending on the pattern. @@ -110,7 +110,7 @@ ax.set_title(f"interpolation='{interp}'") plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/image_clip_path.py b/examples/images_contours_and_fields/image_clip_path.py index f51dacb2a09e..a4f6737b22f4 100644 --- a/examples/images_contours_and_fields/image_clip_path.py +++ b/examples/images_contours_and_fields/image_clip_path.py @@ -21,7 +21,7 @@ ax.axis('off') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/image_demo.py b/examples/images_contours_and_fields/image_demo.py index 7484f858427c..774c379c1d95 100644 --- a/examples/images_contours_and_fields/image_demo.py +++ b/examples/images_contours_and_fields/image_demo.py @@ -21,7 +21,7 @@ # Fixing random state for reproducibility np.random.seed(19680801) -############################################################################### +# %% # First we'll generate a simple bivariate normal distribution. delta = 0.025 @@ -39,7 +39,7 @@ plt.show() -############################################################################### +# %% # It is also possible to show images of pictures. # A sample image @@ -71,7 +71,7 @@ plt.show() -############################################################################### +# %% # Interpolating images # -------------------- # @@ -129,7 +129,7 @@ plt.show() -############################################################################### +# %% # You can specify whether images should be plotted with the array origin # x[0, 0] in the upper left or lower right by using the origin parameter. # You can also control the default setting image.origin in your @@ -149,7 +149,7 @@ plt.show() -############################################################################### +# %% # Finally, we'll show an image using a clip path. delta = 0.025 @@ -172,7 +172,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/image_masked.py b/examples/images_contours_and_fields/image_masked.py index fa5f8047a8ff..0c97a01d3c95 100644 --- a/examples/images_contours_and_fields/image_masked.py +++ b/examples/images_contours_and_fields/image_masked.py @@ -68,7 +68,7 @@ fig.suptitle('imshow, with out-of-range and masked data') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/image_transparency_blend.py b/examples/images_contours_and_fields/image_transparency_blend.py index 48e0a28c89b1..cb7b4f14e4dc 100644 --- a/examples/images_contours_and_fields/image_transparency_blend.py +++ b/examples/images_contours_and_fields/image_transparency_blend.py @@ -62,7 +62,7 @@ def normal_pdf(x, mean, var): ax.imshow(weights, **imshow_kwargs) ax.set_axis_off() -############################################################################### +# %% # Blending in transparency # ======================== # @@ -82,7 +82,7 @@ def normal_pdf(x, mean, var): ax.imshow(weights, alpha=alphas, **imshow_kwargs) ax.set_axis_off() -############################################################################### +# %% # Using transparency to highlight values with high amplitude # ========================================================== # @@ -111,7 +111,7 @@ def normal_pdf(x, mean, var): ax.set_axis_off() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/image_zcoord.py b/examples/images_contours_and_fields/image_zcoord.py index 8e210eb7c603..1edcd90a0827 100644 --- a/examples/images_contours_and_fields/image_zcoord.py +++ b/examples/images_contours_and_fields/image_zcoord.py @@ -35,7 +35,7 @@ def format_coord(x, y): ax.format_coord = format_coord plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/interpolation_methods.py b/examples/images_contours_and_fields/interpolation_methods.py index 4d3151696dcd..496b39c56b9f 100644 --- a/examples/images_contours_and_fields/interpolation_methods.py +++ b/examples/images_contours_and_fields/interpolation_methods.py @@ -40,7 +40,7 @@ plt.tight_layout() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/irregulardatagrid.py b/examples/images_contours_and_fields/irregulardatagrid.py index aedf8033c9b4..e3cbc9d03ade 100644 --- a/examples/images_contours_and_fields/irregulardatagrid.py +++ b/examples/images_contours_and_fields/irregulardatagrid.py @@ -81,7 +81,7 @@ plt.subplots_adjust(hspace=0.5) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/layer_images.py b/examples/images_contours_and_fields/layer_images.py index abd8b2a9008e..bcaa25471500 100644 --- a/examples/images_contours_and_fields/layer_images.py +++ b/examples/images_contours_and_fields/layer_images.py @@ -41,7 +41,7 @@ def func3(x, y): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/matshow.py b/examples/images_contours_and_fields/matshow.py index 0add6bebf9a4..4d2debf1f6b0 100644 --- a/examples/images_contours_and_fields/matshow.py +++ b/examples/images_contours_and_fields/matshow.py @@ -15,7 +15,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/multi_image.py b/examples/images_contours_and_fields/multi_image.py index 5ca598a7e48c..ec7fbf0ce5cb 100644 --- a/examples/images_contours_and_fields/multi_image.py +++ b/examples/images_contours_and_fields/multi_image.py @@ -51,7 +51,7 @@ def update(changed_image): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/pcolor_demo.py b/examples/images_contours_and_fields/pcolor_demo.py index 2e17cd7db90b..847ccf2cfb2d 100644 --- a/examples/images_contours_and_fields/pcolor_demo.py +++ b/examples/images_contours_and_fields/pcolor_demo.py @@ -16,7 +16,7 @@ # Fixing random state for reproducibility np.random.seed(19680801) -############################################################################### +# %% # A simple pcolor demo # -------------------- @@ -33,7 +33,7 @@ fig.tight_layout() plt.show() -############################################################################### +# %% # Comparing pcolor with similar functions # --------------------------------------- # @@ -82,7 +82,7 @@ plt.show() -############################################################################### +# %% # Pcolor with a log scale # ----------------------- # @@ -109,7 +109,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/pcolormesh_grids.py b/examples/images_contours_and_fields/pcolormesh_grids.py index 7fc75f8b6dd9..35da1261fc08 100644 --- a/examples/images_contours_and_fields/pcolormesh_grids.py +++ b/examples/images_contours_and_fields/pcolormesh_grids.py @@ -18,7 +18,7 @@ import matplotlib.pyplot as plt import numpy as np -############################################################################### +# %% # Flat Shading # ------------ # @@ -49,7 +49,7 @@ def _annotate(ax, x, y, title): _annotate(ax, x, y, "shading='flat'") -############################################################################### +# %% # Flat Shading, same shape grid # ----------------------------- # @@ -65,7 +65,7 @@ def _annotate(ax, x, y, title): ax.pcolormesh(x, y, Z[:-1, :-1], shading='flat', vmin=Z.min(), vmax=Z.max()) _annotate(ax, x, y, "shading='flat': X, Y, C same shape") -############################################################################### +# %% # Nearest Shading, same shape grid # -------------------------------- # @@ -81,7 +81,7 @@ def _annotate(ax, x, y, title): ax.pcolormesh(x, y, Z, shading='nearest', vmin=Z.min(), vmax=Z.max()) _annotate(ax, x, y, "shading='nearest'") -############################################################################### +# %% # Auto Shading # ------------ # @@ -102,7 +102,7 @@ def _annotate(ax, x, y, title): ax.pcolormesh(x, y, Z, shading='auto', vmin=Z.min(), vmax=Z.max()) _annotate(ax, x, y, "shading='auto'; X, Y one larger than Z (flat)") -############################################################################### +# %% # Gouraud Shading # --------------- # @@ -117,7 +117,7 @@ def _annotate(ax, x, y, title): _annotate(ax, x, y, "shading='gouraud'; X, Y same shape as Z") plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/pcolormesh_levels.py b/examples/images_contours_and_fields/pcolormesh_levels.py index d462304ea4c5..a9052b922d7b 100644 --- a/examples/images_contours_and_fields/pcolormesh_levels.py +++ b/examples/images_contours_and_fields/pcolormesh_levels.py @@ -13,7 +13,7 @@ from matplotlib.ticker import MaxNLocator import numpy as np -############################################################################### +# %% # Basic pcolormesh # ---------------- # @@ -29,7 +29,7 @@ fig, ax = plt.subplots() ax.pcolormesh(x, y, Z) -############################################################################### +# %% # Non-rectilinear pcolormesh # -------------------------- # @@ -45,7 +45,7 @@ fig, ax = plt.subplots() ax.pcolormesh(X, Y, Z) -############################################################################### +# %% # Centered Coordinates # --------------------- # @@ -67,7 +67,7 @@ shading='flat') axs[1].set_title("shading='flat'") -############################################################################### +# %% # Making levels using Norms # ------------------------- # @@ -117,7 +117,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/plot_streamplot.py b/examples/images_contours_and_fields/plot_streamplot.py index fd587527fbc5..334d5ca0dc9b 100644 --- a/examples/images_contours_and_fields/plot_streamplot.py +++ b/examples/images_contours_and_fields/plot_streamplot.py @@ -71,7 +71,7 @@ plt.tight_layout() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/quadmesh_demo.py b/examples/images_contours_and_fields/quadmesh_demo.py index 430c428f5170..7f4dafbcf7b2 100644 --- a/examples/images_contours_and_fields/quadmesh_demo.py +++ b/examples/images_contours_and_fields/quadmesh_demo.py @@ -40,7 +40,7 @@ fig.tight_layout() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/quiver_demo.py b/examples/images_contours_and_fields/quiver_demo.py index 396e1c047e1b..784cfb0dbc79 100644 --- a/examples/images_contours_and_fields/quiver_demo.py +++ b/examples/images_contours_and_fields/quiver_demo.py @@ -19,7 +19,7 @@ U = np.cos(X) V = np.sin(Y) -############################################################################### +# %% fig1, ax1 = plt.subplots() ax1.set_title('Arrows scale with plot width, not view') @@ -27,7 +27,7 @@ qk = ax1.quiverkey(Q, 0.9, 0.9, 2, r'$2 \frac{m}{s}$', labelpos='E', coordinates='figure') -############################################################################### +# %% fig2, ax2 = plt.subplots() ax2.set_title("pivot='mid'; every third arrow; units='inches'") @@ -37,7 +37,7 @@ coordinates='figure') ax2.scatter(X[::3, ::3], Y[::3, ::3], color='r', s=5) -############################################################################### +# %% # sphinx_gallery_thumbnail_number = 3 @@ -52,7 +52,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/quiver_simple_demo.py b/examples/images_contours_and_fields/quiver_simple_demo.py index 1437d6f138c2..a17a7f2e87f7 100644 --- a/examples/images_contours_and_fields/quiver_simple_demo.py +++ b/examples/images_contours_and_fields/quiver_simple_demo.py @@ -22,7 +22,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/shading_example.py b/examples/images_contours_and_fields/shading_example.py index c3b969dcff8b..357eddd37ee3 100644 --- a/examples/images_contours_and_fields/shading_example.py +++ b/examples/images_contours_and_fields/shading_example.py @@ -62,7 +62,7 @@ def compare(z, cmap, ve=1): if __name__ == '__main__': main() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/specgram_demo.py b/examples/images_contours_and_fields/specgram_demo.py index 43ee7b3c1af8..ef1799c4429f 100644 --- a/examples/images_contours_and_fields/specgram_demo.py +++ b/examples/images_contours_and_fields/specgram_demo.py @@ -36,7 +36,7 @@ # - im: the .image.AxesImage instance representing the data in the plot plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/spy_demos.py b/examples/images_contours_and_fields/spy_demos.py index a61a3ffefcad..48347269e45f 100644 --- a/examples/images_contours_and_fields/spy_demos.py +++ b/examples/images_contours_and_fields/spy_demos.py @@ -31,7 +31,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/tricontour_demo.py b/examples/images_contours_and_fields/tricontour_demo.py index a5d4651b7818..7ae6ced22a17 100644 --- a/examples/images_contours_and_fields/tricontour_demo.py +++ b/examples/images_contours_and_fields/tricontour_demo.py @@ -9,7 +9,7 @@ import matplotlib.tri as tri import numpy as np -############################################################################### +# %% # Creating a Triangulation without specifying the triangles results in the # Delaunay triangulation of the points. @@ -35,7 +35,7 @@ y[triang.triangles].mean(axis=1)) < min_radius) -############################################################################### +# %% # pcolor plot. fig1, ax1 = plt.subplots() @@ -46,7 +46,7 @@ ax1.set_title('Contour plot of Delaunay triangulation') -############################################################################### +# %% # You could also specify hatching patterns along with different cmaps. fig2, ax2 = plt.subplots() @@ -61,7 +61,7 @@ ax2.tricontour(triang, z, linestyles="solid", colors="k", linewidths=2.0) ax2.set_title("Hatched Contour plot of Delaunay triangulation") -############################################################################### +# %% # You could also generate hatching patterns labeled with no color. fig3, ax3 = plt.subplots() @@ -80,7 +80,7 @@ artists, labels = tcf.legend_elements(str_format="{:2.1f}".format) ax3.legend(artists, labels, handleheight=2, framealpha=1) -############################################################################### +# %% # You can specify your own triangulation rather than perform a Delaunay # triangulation of the points, where each triangle is given by the indices of # the three points that make up the triangle, ordered in either a clockwise or @@ -130,7 +130,7 @@ [42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38], [33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]]) -############################################################################### +# %% # Rather than create a Triangulation object, can simply pass x, y and triangles # arrays to tripcolor directly. It would be better to use a Triangulation # object if the same triangulation was to be used more than once to save @@ -146,7 +146,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/tricontour_smooth_delaunay.py b/examples/images_contours_and_fields/tricontour_smooth_delaunay.py index 0815e78fb32d..3aacc6ad25c7 100644 --- a/examples/images_contours_and_fields/tricontour_smooth_delaunay.py +++ b/examples/images_contours_and_fields/tricontour_smooth_delaunay.py @@ -138,7 +138,7 @@ def experiment_res(x, y): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/tricontour_smooth_user.py b/examples/images_contours_and_fields/tricontour_smooth_user.py index c5a0a408f8e5..e69aa332dd0e 100644 --- a/examples/images_contours_and_fields/tricontour_smooth_user.py +++ b/examples/images_contours_and_fields/tricontour_smooth_user.py @@ -74,7 +74,7 @@ def function_z(x, y): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/trigradient_demo.py b/examples/images_contours_and_fields/trigradient_demo.py index 5abda65f5307..21ecde0fedbf 100644 --- a/examples/images_contours_and_fields/trigradient_demo.py +++ b/examples/images_contours_and_fields/trigradient_demo.py @@ -85,7 +85,7 @@ def dipole_potential(x, y): ax.set_title('Gradient plot: an electrical dipole') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/triinterp_demo.py b/examples/images_contours_and_fields/triinterp_demo.py index b06d0086d248..4f962ccdf767 100644 --- a/examples/images_contours_and_fields/triinterp_demo.py +++ b/examples/images_contours_and_fields/triinterp_demo.py @@ -59,7 +59,7 @@ fig.tight_layout() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/tripcolor_demo.py b/examples/images_contours_and_fields/tripcolor_demo.py index f78d275df2fc..fac0f622f5ec 100644 --- a/examples/images_contours_and_fields/tripcolor_demo.py +++ b/examples/images_contours_and_fields/tripcolor_demo.py @@ -9,7 +9,7 @@ import matplotlib.tri as tri import numpy as np -############################################################################### +# %% # Creating a Triangulation without specifying the triangles results in the # Delaunay triangulation of the points. @@ -35,7 +35,7 @@ y[triang.triangles].mean(axis=1)) < min_radius) -############################################################################### +# %% # tripcolor plot. fig1, ax1 = plt.subplots() @@ -44,7 +44,7 @@ fig1.colorbar(tpc) ax1.set_title('tripcolor of Delaunay triangulation, flat shading') -############################################################################### +# %% # Illustrate Gouraud shading. fig2, ax2 = plt.subplots() @@ -54,7 +54,7 @@ ax2.set_title('tripcolor of Delaunay triangulation, gouraud shading') -############################################################################### +# %% # You can specify your own triangulation rather than perform a Delaunay # triangulation of the points, where each triangle is given by the indices of # the three points that make up the triangle, ordered in either a clockwise or @@ -107,7 +107,7 @@ zfaces = np.exp(-0.01 * ((xmid - x0) * (xmid - x0) + (ymid - y0) * (ymid - y0))) -############################################################################### +# %% # Rather than create a Triangulation object, can simply pass x, y and triangles # arrays to tripcolor directly. It would be better to use a Triangulation # object if the same triangulation was to be used more than once to save @@ -125,7 +125,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/triplot_demo.py b/examples/images_contours_and_fields/triplot_demo.py index b25ca4a575c8..53a59a4e59f4 100644 --- a/examples/images_contours_and_fields/triplot_demo.py +++ b/examples/images_contours_and_fields/triplot_demo.py @@ -9,7 +9,7 @@ import matplotlib.tri as tri import numpy as np -############################################################################### +# %% # Creating a Triangulation without specifying the triangles results in the # Delaunay triangulation of the points. @@ -34,7 +34,7 @@ y[triang.triangles].mean(axis=1)) < min_radius) -############################################################################### +# %% # Plot the triangulation. fig1, ax1 = plt.subplots() @@ -43,7 +43,7 @@ ax1.set_title('triplot of Delaunay triangulation') -############################################################################### +# %% # You can specify your own triangulation rather than perform a Delaunay # triangulation of the points, where each triangle is given by the indices of # the three points that make up the triangle, ordered in either a clockwise or @@ -90,7 +90,7 @@ [42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38], [33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]]) -############################################################################### +# %% # Rather than create a Triangulation object, can simply pass x, y and triangles # arrays to triplot directly. It would be better to use a Triangulation object # if the same triangulation was to be used more than once to save duplicated @@ -105,7 +105,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/images_contours_and_fields/watermark_image.py b/examples/images_contours_and_fields/watermark_image.py index a8f0b0d90b04..cf850cbd77a8 100644 --- a/examples/images_contours_and_fields/watermark_image.py +++ b/examples/images_contours_and_fields/watermark_image.py @@ -23,7 +23,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/bar_label_demo.py b/examples/lines_bars_and_markers/bar_label_demo.py index 146b6934bb48..8774c24a9d42 100644 --- a/examples/lines_bars_and_markers/bar_label_demo.py +++ b/examples/lines_bars_and_markers/bar_label_demo.py @@ -17,7 +17,7 @@ import matplotlib.pyplot as plt import numpy as np -############################################################################### +# %% # data from https://allisonhorst.github.io/palmerpenguins/ species = ('Adelie', 'Chinstrap', 'Gentoo') @@ -42,7 +42,7 @@ plt.show() -############################################################################### +# %% # Horizontal bar chart # Fixing random state for reproducibility @@ -68,7 +68,7 @@ plt.show() -############################################################################### +# %% # Some of the more advanced things that one can do with bar labels fig, ax = plt.subplots() @@ -86,7 +86,7 @@ plt.show() -############################################################################### +# %% # Bar labels using {}-style format string fruit_names = ['Coffee', 'Salted Caramel', 'Pistachio'] @@ -97,7 +97,7 @@ ax.set(ylabel='pints sold', title='Gelato sales by flavor', ylim=(0, 8000)) ax.bar_label(bar_container, fmt='{:,.0f}') -############################################################################### +# %% # Bar labels using a callable animal_names = ['Lion', 'Gazelle', 'Cheetah'] @@ -110,7 +110,7 @@ bar_container, fmt=lambda x: '{:.1f} km/h'.format(x * 1.61) ) -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/barchart.py b/examples/lines_bars_and_markers/barchart.py index f5ee6833a881..79fe2958f11f 100644 --- a/examples/lines_bars_and_markers/barchart.py +++ b/examples/lines_bars_and_markers/barchart.py @@ -40,7 +40,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/categorical_variables.py b/examples/lines_bars_and_markers/categorical_variables.py index 01863b3c193c..bb42ec182ada 100644 --- a/examples/lines_bars_and_markers/categorical_variables.py +++ b/examples/lines_bars_and_markers/categorical_variables.py @@ -19,7 +19,7 @@ fig.suptitle('Categorical Plotting') -############################################################################### +# %% # This works on both axes: cat = ["bored", "happy", "bored", "bored", "happy", "bored"] diff --git a/examples/lines_bars_and_markers/curve_error_band.py b/examples/lines_bars_and_markers/curve_error_band.py index e55b467849a8..59db81a7d259 100644 --- a/examples/lines_bars_and_markers/curve_error_band.py +++ b/examples/lines_bars_and_markers/curve_error_band.py @@ -24,7 +24,7 @@ ax.plot(x, y, "k") ax.set(aspect=1) -############################################################################# +# %% # An error band can be used to indicate the uncertainty of the curve. # In this example we assume that the error can be given as a scalar *err* # that describes the uncertainty perpendicular to the curve in every point. @@ -77,7 +77,7 @@ def draw_error_band(ax, x, y, err, **kwargs): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/errorbar_limits_simple.py b/examples/lines_bars_and_markers/errorbar_limits_simple.py index 42d0daf6f281..7727137046b3 100644 --- a/examples/lines_bars_and_markers/errorbar_limits_simple.py +++ b/examples/lines_bars_and_markers/errorbar_limits_simple.py @@ -33,7 +33,7 @@ plt.legend(loc='lower right') -############################################################################## +# %% # Similarly ``xuplims`` and ``xlolims`` can be used on the horizontal ``xerr`` # errorbars. @@ -53,7 +53,7 @@ plt.legend() plt.show() -############################################################################## +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/fill.py b/examples/lines_bars_and_markers/fill.py index 79642a9e5ed5..cba430153763 100644 --- a/examples/lines_bars_and_markers/fill.py +++ b/examples/lines_bars_and_markers/fill.py @@ -51,7 +51,7 @@ def _koch_snowflake_complex(order): return x, y -############################################################################### +# %% # Basic usage: x, y = koch_snowflake(order=5) @@ -61,7 +61,7 @@ def _koch_snowflake_complex(order): plt.fill(x, y) plt.show() -############################################################################### +# %% # Use keyword arguments *facecolor* and *edgecolor* to modify the colors # of the polygon. Since the *linewidth* of the edge is 0 in the default # Matplotlib style, we have to set it as well for the edge to become visible. @@ -76,7 +76,7 @@ def _koch_snowflake_complex(order): plt.show() -############################################################################### +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/fill_between_alpha.py b/examples/lines_bars_and_markers/fill_between_alpha.py index 9f4351b0006f..235c4c6091fc 100644 --- a/examples/lines_bars_and_markers/fill_between_alpha.py +++ b/examples/lines_bars_and_markers/fill_between_alpha.py @@ -37,7 +37,7 @@ fig.suptitle('Google (GOOG) daily closing price') fig.autofmt_xdate() -############################################################################### +# %% # The alpha channel is not necessary here, but it can be used to soften # colors for more visually appealing plots. In other examples, as we'll # see below, the alpha channel is functionally useful as the shaded @@ -86,7 +86,7 @@ ax.set_ylabel('position') ax.grid() -############################################################################### +# %% # The ``where`` keyword argument is very handy for highlighting certain # regions of the graph. ``where`` takes a boolean mask the same length # as the x, ymin and ymax arguments, and only fills in the region where @@ -130,7 +130,7 @@ ax.set_ylabel('position') ax.grid() -############################################################################### +# %% # Another handy use of filled regions is to highlight horizontal or vertical # spans of an Axes -- for that Matplotlib has the helper functions # `~matplotlib.axes.Axes.axhspan` and `~matplotlib.axes.Axes.axvspan`. See diff --git a/examples/lines_bars_and_markers/fill_between_demo.py b/examples/lines_bars_and_markers/fill_between_demo.py index 79aef67ab4d9..1fcb808f2563 100644 --- a/examples/lines_bars_and_markers/fill_between_demo.py +++ b/examples/lines_bars_and_markers/fill_between_demo.py @@ -10,7 +10,7 @@ import matplotlib.pyplot as plt import numpy as np -############################################################################### +# %% # # Basic usage # ----------- @@ -34,7 +34,7 @@ ax3.set_xlabel('x') fig.tight_layout() -############################################################################### +# %% # # Example: Confidence bands # ------------------------- @@ -63,7 +63,7 @@ ax.fill_between(x, y_est - y_err, y_est + y_err, alpha=0.2) ax.plot(x, y, 'o', color='tab:brown') -############################################################################### +# %% # # Selectively filling horizontal regions # -------------------------------------- @@ -99,7 +99,7 @@ interpolate=True) fig.tight_layout() -############################################################################### +# %% # # .. note:: # @@ -108,7 +108,7 @@ # The gaps around masked values can only be reduced by adding more data # points close to the masked values. -############################################################################### +# %% # # Selectively marking horizontal regions across the whole Axes # ------------------------------------------------------------ @@ -130,7 +130,7 @@ ax.fill_between(x, 0, 1, where=y > threshold, color='green', alpha=0.5, transform=ax.get_xaxis_transform()) -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/fill_betweenx_demo.py b/examples/lines_bars_and_markers/fill_betweenx_demo.py index 06f219d9fb31..91650c3698c9 100644 --- a/examples/lines_bars_and_markers/fill_betweenx_demo.py +++ b/examples/lines_bars_and_markers/fill_betweenx_demo.py @@ -26,7 +26,7 @@ ax3.fill_betweenx(y, x1, x2) ax3.set_title('between (x1, x2)') -############################################################################# +# %% # Now fill between x1 and x2 where a logical condition is met. Note this is # different than calling:: # @@ -47,7 +47,7 @@ ax1.fill_betweenx(y, x1, x2, where=x2 <= x1, facecolor='red') ax1.set_title('regions with x2 > 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. diff --git a/examples/lines_bars_and_markers/filled_step.py b/examples/lines_bars_and_markers/filled_step.py index 102f2498ca4c..5edd7462cf15 100644 --- a/examples/lines_bars_and_markers/filled_step.py +++ b/examples/lines_bars_and_markers/filled_step.py @@ -190,7 +190,7 @@ def stack_hist(ax, stacked_data, sty_cycle, bottoms=None, stack_data = np.random.randn(4, 12250) dict_data = dict(zip((c['label'] for c in label_cycle), stack_data)) -############################################################################### +# %% # Work with plain arrays fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4.5), tight_layout=True) @@ -205,7 +205,7 @@ def stack_hist(ax, stacked_data, sty_cycle, bottoms=None, ax2.set_xlabel('counts') ax2.set_ylabel('x') -############################################################################### +# %% # Work with labeled data fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4.5), @@ -223,7 +223,7 @@ def stack_hist(ax, stacked_data, sty_cycle, bottoms=None, plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/hat_graph.py b/examples/lines_bars_and_markers/hat_graph.py index 6c939167b536..ddef3e9f631f 100644 --- a/examples/lines_bars_and_markers/hat_graph.py +++ b/examples/lines_bars_and_markers/hat_graph.py @@ -69,7 +69,7 @@ def label_bars(heights, rects): fig.tight_layout() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/horizontal_barchart_distribution.py b/examples/lines_bars_and_markers/horizontal_barchart_distribution.py index 3a22ce3ed4ae..600dcad92ba2 100644 --- a/examples/lines_bars_and_markers/horizontal_barchart_distribution.py +++ b/examples/lines_bars_and_markers/horizontal_barchart_distribution.py @@ -69,7 +69,7 @@ def survey(results, category_names): survey(results, category_names) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/marker_reference.py b/examples/lines_bars_and_markers/marker_reference.py index 0c742801998b..6d2eb77544e8 100644 --- a/examples/lines_bars_and_markers/marker_reference.py +++ b/examples/lines_bars_and_markers/marker_reference.py @@ -42,7 +42,7 @@ def split_list(a_list): return a_list[:i_half], a_list[i_half:] -############################################################################### +# %% # Unfilled markers # ================ # Unfilled markers are single-colored. @@ -60,7 +60,7 @@ def split_list(a_list): ax.plot([y] * 3, marker=marker, **marker_style) format_axes(ax) -############################################################################### +# %% # Filled markers # ============== @@ -72,7 +72,7 @@ def split_list(a_list): ax.plot([y] * 3, marker=marker, **marker_style) format_axes(ax) -############################################################################### +# %% # .. _marker_fill_styles: # # Marker fill styles @@ -97,7 +97,7 @@ def split_list(a_list): ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style) format_axes(ax) -############################################################################### +# %% # Markers created from TeX symbols # ================================ # @@ -120,7 +120,7 @@ def split_list(a_list): ax.plot([y] * 3, marker=marker, **marker_style) format_axes(ax) -############################################################################### +# %% # Markers created from Paths # ========================== # @@ -149,7 +149,7 @@ def split_list(a_list): ax.plot([y] * 3, marker=marker, **marker_style) format_axes(ax) -############################################################################### +# %% # Advanced marker modifications with transform # ============================================ # @@ -185,7 +185,7 @@ def split_list(a_list): fig.tight_layout() -############################################################################### +# %% # Setting marker cap style and join style # ======================================= # @@ -222,7 +222,7 @@ def split_list(a_list): ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center') format_axes(ax) -############################################################################### +# %% # Modifying the join style: fig, ax = plt.subplots() diff --git a/examples/lines_bars_and_markers/markevery_demo.py b/examples/lines_bars_and_markers/markevery_demo.py index 8dc02f52e28a..fc88db03cbf5 100644 --- a/examples/lines_bars_and_markers/markevery_demo.py +++ b/examples/lines_bars_and_markers/markevery_demo.py @@ -40,7 +40,7 @@ x = np.linspace(0, 10 - 2 * delta, 200) + delta y = np.sin(x) + 1.0 + delta -############################################################################### +# %% # markevery with linear scales # ---------------------------- @@ -49,7 +49,7 @@ ax.set_title(f'markevery={markevery}') ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery) -############################################################################### +# %% # markevery with log scales # ------------------------- # @@ -65,7 +65,7 @@ ax.set_yscale('log') ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery) -############################################################################### +# %% # markevery on zoomed plots # ------------------------- # @@ -82,7 +82,7 @@ ax.set_xlim((6, 6.7)) ax.set_ylim((1.1, 1.7)) -############################################################################### +# %% # markevery on polar plots # ------------------------ diff --git a/examples/lines_bars_and_markers/psd_demo.py b/examples/lines_bars_and_markers/psd_demo.py index 0ab038c2991b..5d30c6a784f6 100644 --- a/examples/lines_bars_and_markers/psd_demo.py +++ b/examples/lines_bars_and_markers/psd_demo.py @@ -31,7 +31,7 @@ plt.show() -############################################################################### +# %% # Compare this with the equivalent Matlab code to accomplish the same thing:: # # dt = 0.01; @@ -99,7 +99,7 @@ plt.show() -############################################################################### +# %% # This is a ported version of a MATLAB example from the signal # processing toolbox that showed some difference at one time between # Matplotlib's and MATLAB's scaling of the PSD. @@ -136,7 +136,7 @@ plt.show() -############################################################################### +# %% # This is a ported version of a MATLAB example from the signal # processing toolbox that showed some difference at one time between # Matplotlib's and MATLAB's scaling of the PSD. diff --git a/examples/lines_bars_and_markers/scatter_custom_symbol.py b/examples/lines_bars_and_markers/scatter_custom_symbol.py index b8e57b0e5e1f..614792d3d9a4 100644 --- a/examples/lines_bars_and_markers/scatter_custom_symbol.py +++ b/examples/lines_bars_and_markers/scatter_custom_symbol.py @@ -7,7 +7,7 @@ .. redirect-from:: /gallery/lines_bars_and_markers/scatter_piecharts """ -############################################################################## +# %% # Using TeX symbols # ----------------- # An easy way to customize scatter symbols is passing a TeX symbol name @@ -32,7 +32,7 @@ ax.legend() plt.show() -############################################################################## +# %% # Using a custom path # ------------------- # Alternatively, one can also pass a custom path of N vertices as a Nx2 array diff --git a/examples/lines_bars_and_markers/scatter_hist.py b/examples/lines_bars_and_markers/scatter_hist.py index 29b2f96947a4..15225430d271 100644 --- a/examples/lines_bars_and_markers/scatter_hist.py +++ b/examples/lines_bars_and_markers/scatter_hist.py @@ -54,7 +54,7 @@ def scatter_hist(x, y, ax, ax_histx, ax_histy): ax_histy.hist(y, bins=bins, orientation='horizontal') -############################################################################# +# %% # # Defining the axes positions using a gridspec # -------------------------------------------- @@ -78,7 +78,7 @@ def scatter_hist(x, y, ax, ax_histx, ax_histy): scatter_hist(x, y, ax, ax_histx, ax_histy) -############################################################################# +# %% # # Defining the axes positions using inset_axes # -------------------------------------------- @@ -108,7 +108,7 @@ def scatter_hist(x, y, ax, ax_histx, ax_histy): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/scatter_with_legend.py b/examples/lines_bars_and_markers/scatter_with_legend.py index 1562092f82d7..133115489364 100644 --- a/examples/lines_bars_and_markers/scatter_with_legend.py +++ b/examples/lines_bars_and_markers/scatter_with_legend.py @@ -31,7 +31,7 @@ plt.show() -############################################################################## +# %% # .. _automatedlegendcreation: # # Automated legend creation @@ -64,7 +64,7 @@ plt.show() -############################################################################## +# %% # Further arguments to the `.PathCollection.legend_elements` method # can be used to steer how many legend entries are to be created and how they # should be labeled. The following shows how to use some of them. @@ -99,7 +99,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/simple_plot.py b/examples/lines_bars_and_markers/simple_plot.py index 86b51db41259..520d6fac8204 100644 --- a/examples/lines_bars_and_markers/simple_plot.py +++ b/examples/lines_bars_and_markers/simple_plot.py @@ -23,7 +23,7 @@ fig.savefig("test.png") plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/span_regions.py b/examples/lines_bars_and_markers/span_regions.py index f5d1cce9cf9b..073f4a02aae6 100644 --- a/examples/lines_bars_and_markers/span_regions.py +++ b/examples/lines_bars_and_markers/span_regions.py @@ -22,7 +22,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/stackplot_demo.py b/examples/lines_bars_and_markers/stackplot_demo.py index 142b3d2a0ce0..f52bb9fabac6 100644 --- a/examples/lines_bars_and_markers/stackplot_demo.py +++ b/examples/lines_bars_and_markers/stackplot_demo.py @@ -4,7 +4,7 @@ =========================== """ -############################################################################## +# %% # Stackplots # ---------- # @@ -37,7 +37,7 @@ plt.show() -############################################################################## +# %% # Streamgraphs # ------------ # diff --git a/examples/lines_bars_and_markers/stairs_demo.py b/examples/lines_bars_and_markers/stairs_demo.py index 79f63975b32b..040d12f4a10d 100644 --- a/examples/lines_bars_and_markers/stairs_demo.py +++ b/examples/lines_bars_and_markers/stairs_demo.py @@ -43,7 +43,7 @@ ax.legend() plt.show() -############################################################################# +# %% # *baseline* can take an array to allow for stacked histogram plots A = [[0, 0, 0], [1, 2, 3], @@ -53,7 +53,7 @@ for i in range(len(A) - 1): plt.stairs(A[i+1], baseline=A[i], fill=True) -############################################################################# +# %% # Comparison of `.pyplot.step` and `.pyplot.stairs` # ------------------------------------------------- # @@ -80,7 +80,7 @@ plt.title('step() vs. stairs()') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/stem_plot.py b/examples/lines_bars_and_markers/stem_plot.py index 4f74d50bde16..f3035c1673e6 100644 --- a/examples/lines_bars_and_markers/stem_plot.py +++ b/examples/lines_bars_and_markers/stem_plot.py @@ -15,7 +15,7 @@ plt.stem(x, y) plt.show() -############################################################################# +# %% # # The position of the baseline can be adapted using *bottom*. # The parameters *linefmt*, *markerfmt*, and *basefmt* control basic format @@ -28,7 +28,7 @@ markerline.set_markerfacecolor('none') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/step_demo.py b/examples/lines_bars_and_markers/step_demo.py index f1016ead5283..11954c6872cb 100644 --- a/examples/lines_bars_and_markers/step_demo.py +++ b/examples/lines_bars_and_markers/step_demo.py @@ -36,7 +36,7 @@ plt.title('plt.step(where=...)') plt.show() -############################################################################# +# %% # The same behavior can be achieved by using the ``drawstyle`` parameter of # `.pyplot.plot`. @@ -54,7 +54,7 @@ plt.title('plt.plot(drawstyle=...)') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/timeline.py b/examples/lines_bars_and_markers/timeline.py index 2b4f7d81d059..2c8507922f7f 100644 --- a/examples/lines_bars_and_markers/timeline.py +++ b/examples/lines_bars_and_markers/timeline.py @@ -52,7 +52,7 @@ # Convert date strings (e.g. 2014-10-18) to datetime dates = [datetime.strptime(d, "%Y-%m-%d") for d in dates] -############################################################################## +# %% # Next, we'll create a stem plot with some variation in levels as to # distinguish even close-by events. We add markers on the baseline for visual # emphasis on the one-dimensional nature of the timeline. @@ -95,7 +95,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/lines_bars_and_markers/xcorr_acorr_demo.py b/examples/lines_bars_and_markers/xcorr_acorr_demo.py index 493cad034de8..933f21054867 100644 --- a/examples/lines_bars_and_markers/xcorr_acorr_demo.py +++ b/examples/lines_bars_and_markers/xcorr_acorr_demo.py @@ -24,7 +24,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/misc/contour_manual.py b/examples/misc/contour_manual.py index cc47bce184c5..4cde4f0ad6ef 100644 --- a/examples/misc/contour_manual.py +++ b/examples/misc/contour_manual.py @@ -10,20 +10,20 @@ 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]]] -############################################################################### +# %% fig, ax = plt.subplots() @@ -39,7 +39,7 @@ ax.set(xlim=(-0.5, 3.5), ylim=(-0.5, 4.5), 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. diff --git a/examples/misc/fig_x.py b/examples/misc/fig_x.py index eaa16d80fa35..2ef1e8d9a709 100644 --- a/examples/misc/fig_x.py +++ b/examples/misc/fig_x.py @@ -17,7 +17,7 @@ fig.add_artist(lines.Line2D([0, 1], [1, 0])) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/misc/histogram_path.py b/examples/misc/histogram_path.py index e45f990e2053..3de9e07b4813 100644 --- a/examples/misc/histogram_path.py +++ b/examples/misc/histogram_path.py @@ -46,7 +46,7 @@ axs[0].add_patch(patch) axs[0].autoscale_view() -############################################################################# +# %% # Instead of creating a three-dimensional array and using # `~.path.Path.make_compound_path_from_polys`, we could as well create the # compound path directly using vertices and codes as shown below @@ -76,7 +76,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/misc/hyperlinks_sgskip.py b/examples/misc/hyperlinks_sgskip.py index 2d0f6819cfb8..6528cc2d44eb 100644 --- a/examples/misc/hyperlinks_sgskip.py +++ b/examples/misc/hyperlinks_sgskip.py @@ -14,14 +14,14 @@ import matplotlib.cm as cm import matplotlib.pyplot as plt -############################################################################### +# %% fig = plt.figure() s = plt.scatter([1, 2, 3], [4, 5, 6]) s.set_urls(['https://www.bbc.com/news', 'https://www.google.com/', None]) fig.savefig('scatter.svg') -############################################################################### +# %% fig = plt.figure() delta = 0.025 diff --git a/examples/misc/logos2.py b/examples/misc/logos2.py index 8febb8b57d60..03b18305e0ee 100644 --- a/examples/misc/logos2.py +++ b/examples/misc/logos2.py @@ -138,18 +138,18 @@ def make_logo(height_px, lw_bars, lw_grid, lw_border, rgrid, with_text=False): return fig, ax -############################################################################## +# %% # A large logo: make_logo(height_px=110, lw_bars=0.7, lw_grid=0.5, lw_border=1, rgrid=[1, 3, 5, 7]) -############################################################################## +# %% # A small 32px logo: make_logo(height_px=32, lw_bars=0.3, lw_grid=0.3, lw_border=0.3, rgrid=[5]) -############################################################################## +# %% # A large logo including text, as used on the matplotlib website. make_logo(height_px=110, lw_bars=0.7, lw_grid=0.5, lw_border=1, diff --git a/examples/misc/multiprocess_sgskip.py b/examples/misc/multiprocess_sgskip.py index 0ab57e6e3b7c..5951dab1b895 100644 --- a/examples/misc/multiprocess_sgskip.py +++ b/examples/misc/multiprocess_sgskip.py @@ -18,7 +18,7 @@ # Fixing random state for reproducibility np.random.seed(19680801) -############################################################################### +# %% # # Processing Class # ================ @@ -60,7 +60,7 @@ def __call__(self, pipe): print('...done') plt.show() -############################################################################### +# %% # # Plotting class # ============== diff --git a/examples/misc/rasterization_demo.py b/examples/misc/rasterization_demo.py index f0188c684fc7..a00b9c1341e5 100644 --- a/examples/misc/rasterization_demo.py +++ b/examples/misc/rasterization_demo.py @@ -82,7 +82,7 @@ plt.savefig("test_rasterization.svg", dpi=150) # svg backend currently ignores the dpi -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/misc/tickedstroke_demo.py b/examples/misc/tickedstroke_demo.py index 0e4b00b7d5cb..70933d4a45a6 100644 --- a/examples/misc/tickedstroke_demo.py +++ b/examples/misc/tickedstroke_demo.py @@ -20,7 +20,7 @@ `. """ -############################################################################### +# %% # Applying TickedStroke to paths # ============================== import matplotlib.patches as patches @@ -41,7 +41,7 @@ plt.show() -############################################################################### +# %% # Applying TickedStroke to lines # ============================== fig, ax = plt.subplots(figsize=(6, 6)) @@ -57,7 +57,7 @@ plt.show() -############################################################################### +# %% # Applying TickedStroke to contour plots # ====================================== # diff --git a/examples/misc/zorder_demo.py b/examples/misc/zorder_demo.py index 1eb769c307a6..36c5e7965ba2 100644 --- a/examples/misc/zorder_demo.py +++ b/examples/misc/zorder_demo.py @@ -40,7 +40,7 @@ x = r * np.sin(theta) y = r * np.cos(theta) -############################################################################### +# %% # The following example contains a `.Line2D` created by `~.axes.Axes.plot()` # and the dots (a `.PatchCollection`) created by `~.axes.Axes.scatter()`. # Hence, by default the dots are below the line (first subplot). @@ -59,7 +59,7 @@ plt.tight_layout() -############################################################################### +# %% # Many functions that create a visible object accepts a ``zorder`` parameter. # Alternatively, you can call ``set_zorder()`` on the created object later. diff --git a/examples/mplot3d/stem3d_demo.py b/examples/mplot3d/stem3d_demo.py index 0e2dac2f9b58..6f1773c1b505 100644 --- a/examples/mplot3d/stem3d_demo.py +++ b/examples/mplot3d/stem3d_demo.py @@ -20,7 +20,7 @@ plt.show() -############################################################################# +# %% # # The position of the baseline can be adapted using *bottom*. The parameters # *linefmt*, *markerfmt*, and *basefmt* control basic format properties of the @@ -35,7 +35,7 @@ plt.show() -############################################################################# +# %% # # The orientation of the stems and baseline can be changed using *orientation*. # This determines in which direction the stems are projected from the head diff --git a/examples/mplot3d/surface3d.py b/examples/mplot3d/surface3d.py index 07019cb15e31..5a4a5cd79dbd 100644 --- a/examples/mplot3d/surface3d.py +++ b/examples/mplot3d/surface3d.py @@ -40,7 +40,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pie_and_polar_charts/bar_of_pie.py b/examples/pie_and_polar_charts/bar_of_pie.py index eaacb5053cdb..4cc66afeca49 100644 --- a/examples/pie_and_polar_charts/bar_of_pie.py +++ b/examples/pie_and_polar_charts/bar_of_pie.py @@ -70,7 +70,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pie_and_polar_charts/nested_pie.py b/examples/pie_and_polar_charts/nested_pie.py index 5a31ab1ffdc8..1d8083e4de62 100644 --- a/examples/pie_and_polar_charts/nested_pie.py +++ b/examples/pie_and_polar_charts/nested_pie.py @@ -11,7 +11,7 @@ import matplotlib.pyplot as plt import numpy as np -############################################################################### +# %% # The most straightforward way to build a pie chart is to use the # `~matplotlib.axes.Axes.pie` method. # @@ -43,7 +43,7 @@ ax.set(aspect="equal", title='Pie plot with `ax.pie`') plt.show() -############################################################################### +# %% # However, you can accomplish the same output by using a bar plot on # axes with a polar coordinate system. This may give more flexibility on # the exact design of the plot. @@ -77,7 +77,7 @@ ax.set_axis_off() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pie_and_polar_charts/pie_and_donut_labels.py b/examples/pie_and_polar_charts/pie_and_donut_labels.py index 9ef280935c18..26ec6c2dd236 100644 --- a/examples/pie_and_polar_charts/pie_and_donut_labels.py +++ b/examples/pie_and_polar_charts/pie_and_donut_labels.py @@ -9,7 +9,7 @@ as well as with `annotations `. """ -############################################################################### +# %% # As usual we would start by defining the imports and create a figure with # subplots. # Now it's time for the pie. Starting with a pie recipe, we create the data @@ -62,7 +62,7 @@ def func(pct, allvals): plt.show() -############################################################################### +# %% # Now it's time for the donut. Starting with a donut recipe, we transcribe # the data to numbers (converting 1 egg to 50 g), and directly plot the pie. # The pie? Wait... it's going to be donut, is it not? @@ -117,13 +117,13 @@ def func(pct, allvals): plt.show() -############################################################################### +# %% # And here it is, the donut. Note however, that if we were to use this recipe, # the ingredients would suffice for around 6 donuts - producing one huge # donut is untested and might result in kitchen errors. -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pie_and_polar_charts/pie_demo2.py b/examples/pie_and_polar_charts/pie_demo2.py index 1f1ffcefbd96..61f88a15d8c8 100644 --- a/examples/pie_and_polar_charts/pie_demo2.py +++ b/examples/pie_and_polar_charts/pie_demo2.py @@ -45,7 +45,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pie_and_polar_charts/pie_features.py b/examples/pie_and_polar_charts/pie_features.py index d25ce839bf62..0cf8b058fef0 100644 --- a/examples/pie_and_polar_charts/pie_features.py +++ b/examples/pie_and_polar_charts/pie_features.py @@ -34,7 +34,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pie_and_polar_charts/polar_bar.py b/examples/pie_and_polar_charts/polar_bar.py index 75ad64ba3ff4..4172cb71bb33 100644 --- a/examples/pie_and_polar_charts/polar_bar.py +++ b/examples/pie_and_polar_charts/polar_bar.py @@ -24,7 +24,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pie_and_polar_charts/polar_demo.py b/examples/pie_and_polar_charts/polar_demo.py index 59db1792f172..0d807d8edd08 100644 --- a/examples/pie_and_polar_charts/polar_demo.py +++ b/examples/pie_and_polar_charts/polar_demo.py @@ -22,7 +22,7 @@ ax.set_title("A line plot on a polar axis", va='bottom') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pie_and_polar_charts/polar_error_caps.py b/examples/pie_and_polar_charts/polar_error_caps.py index 009f697346f3..985749184124 100644 --- a/examples/pie_and_polar_charts/polar_error_caps.py +++ b/examples/pie_and_polar_charts/polar_error_caps.py @@ -21,7 +21,7 @@ ax.set_title("Pretty polar error bars") plt.show() -############################################################################# +# %% # Please acknowledge that large theta error bars will be overlapping. # This may reduce readability of the output plot. See example figure below: @@ -31,7 +31,7 @@ ax.set_title("Overlapping theta error bars") plt.show() -############################################################################# +# %% # On the other hand, large radius error bars will never overlap, they just # lead to unwanted scale in the data, reducing the displayed range. @@ -42,7 +42,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pie_and_polar_charts/polar_legend.py b/examples/pie_and_polar_charts/polar_legend.py index 955e435c9abd..a4508b0e9f3a 100644 --- a/examples/pie_and_polar_charts/polar_legend.py +++ b/examples/pie_and_polar_charts/polar_legend.py @@ -27,7 +27,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pie_and_polar_charts/polar_scatter.py b/examples/pie_and_polar_charts/polar_scatter.py index fffb6d2091fd..89b1f6592f9d 100644 --- a/examples/pie_and_polar_charts/polar_scatter.py +++ b/examples/pie_and_polar_charts/polar_scatter.py @@ -24,7 +24,7 @@ ax = fig.add_subplot(projection='polar') c = ax.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75) -############################################################################### +# %% # Scatter plot on polar axis, with offset origin # ---------------------------------------------- # @@ -39,7 +39,7 @@ ax.set_rorigin(-2.5) ax.set_theta_zero_location('W', offset=10) -############################################################################### +# %% # Scatter plot on polar axis confined to a sector # ----------------------------------------------- # @@ -55,7 +55,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pyplots/axline.py b/examples/pyplots/axline.py index 5da9dc1a68ef..4c6a1e53db63 100644 --- a/examples/pyplots/axline.py +++ b/examples/pyplots/axline.py @@ -28,7 +28,7 @@ plt.legend(fontsize=14) plt.show() -############################################################################## +# %% # `~.axes.Axes.axline` can also be used with a ``transform`` parameter, which # applies to the point, but not to the slope. This can be useful for drawing # diagonal grid lines with a fixed slope, which stay in place when the @@ -41,7 +41,7 @@ plt.xlim([0, 1]) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pyplots/pyplot_simple.py b/examples/pyplots/pyplot_simple.py index 096323b626dc..48a862c7fee3 100644 --- a/examples/pyplots/pyplot_simple.py +++ b/examples/pyplots/pyplot_simple.py @@ -17,7 +17,7 @@ plt.ylabel('some numbers') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pyplots/pyplot_text.py b/examples/pyplots/pyplot_text.py index 00e738ef414b..42654cf50191 100644 --- a/examples/pyplots/pyplot_text.py +++ b/examples/pyplots/pyplot_text.py @@ -26,7 +26,7 @@ plt.ylabel('Voltage [mV]') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pyplots/pyplot_three.py b/examples/pyplots/pyplot_three.py index 7dfcddb7bb94..74d2000fb3b3 100644 --- a/examples/pyplots/pyplot_three.py +++ b/examples/pyplots/pyplot_three.py @@ -16,7 +16,7 @@ plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/pyplots/pyplot_two_subplots.py b/examples/pyplots/pyplot_two_subplots.py index d316da2fc930..1ac39dea479b 100644 --- a/examples/pyplots/pyplot_two_subplots.py +++ b/examples/pyplots/pyplot_two_subplots.py @@ -26,7 +26,7 @@ def f(t): plt.plot(t2, np.cos(2*np.pi*t2), color='tab:orange', linestyle='--') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/scales/asinh_demo.py b/examples/scales/asinh_demo.py index ae13fb1265de..6a57ada6dc9d 100644 --- a/examples/scales/asinh_demo.py +++ b/examples/scales/asinh_demo.py @@ -46,7 +46,7 @@ # Prepare sample values for variations on y=x graph: x = np.linspace(-3, 6, 500) -############################################################################### +# %% # Compare "symlog" and "asinh" behaviour on sample y=x graph, # where there is a discontinuous gradient in "symlog" near y=2: fig1 = plt.figure() @@ -63,7 +63,7 @@ ax1.set_title('asinh') -############################################################################### +# %% # Compare "asinh" graphs with different scale parameter "linear_width": fig2 = plt.figure(constrained_layout=True) axs = fig2.subplots(1, 3, sharex=True) @@ -77,7 +77,7 @@ ax.legend(loc='best', fontsize='small') -############################################################################### +# %% # Compare "symlog" and "asinh" scalings # on 2D Cauchy-distributed random numbers, # where one may be able to see more subtle artifacts near y=2 @@ -100,7 +100,7 @@ plt.show() -############################################################################### +# %% # # .. admonition:: References # diff --git a/examples/scales/power_norm.py b/examples/scales/power_norm.py index 9ab8454465f5..17a1b1e74cd6 100644 --- a/examples/scales/power_norm.py +++ b/examples/scales/power_norm.py @@ -36,7 +36,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/scales/scales.py b/examples/scales/scales.py index 25ec82608f01..d587c57f005d 100644 --- a/examples/scales/scales.py +++ b/examples/scales/scales.py @@ -101,7 +101,7 @@ def inverse(a): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/scales/symlog_demo.py b/examples/scales/symlog_demo.py index 6c5f04ade8d6..5ebac4c9ca4f 100644 --- a/examples/scales/symlog_demo.py +++ b/examples/scales/symlog_demo.py @@ -34,13 +34,13 @@ fig.tight_layout() plt.show() -############################################################################### +# %% # It should be noted that the coordinate transform used by ``symlog`` # has a discontinuous gradient at the transition between its linear # and logarithmic regions. The ``asinh`` axis scale is an alternative # technique that may avoid visual artifacts caused by these discontinuities. -############################################################################### +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/arrow_guide.py b/examples/shapes_and_collections/arrow_guide.py index efe169d909f3..89956e0576a9 100644 --- a/examples/shapes_and_collections/arrow_guide.py +++ b/examples/shapes_and_collections/arrow_guide.py @@ -37,7 +37,7 @@ dy = y_head - y_tail -############################################################################### +# %% # Head shape fixed in display space and anchor points fixed in data space # ----------------------------------------------------------------------- # @@ -59,7 +59,7 @@ axs[1].add_patch(arrow) axs[1].set(xlim=(0, 2), ylim=(0, 2)) -############################################################################### +# %% # Head shape and anchor points fixed in display space # --------------------------------------------------- # @@ -86,7 +86,7 @@ axs[1].set(xlim=(0, 2), ylim=(0, 2)) -############################################################################### +# %% # Head shape and anchor points fixed in data space # ------------------------------------------------ # @@ -120,6 +120,6 @@ width=.1, length_includes_head=True, color="C2") axs[1].set(xlim=(0, 2), ylim=(0, 2)) -############################################################################### +# %% plt.show() diff --git a/examples/shapes_and_collections/artist_reference.py b/examples/shapes_and_collections/artist_reference.py index 054c1f1e088a..17b46ef77bb9 100644 --- a/examples/shapes_and_collections/artist_reference.py +++ b/examples/shapes_and_collections/artist_reference.py @@ -102,7 +102,7 @@ def label(xy, text): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/collections.py b/examples/shapes_and_collections/collections.py index b7ce0d6340ac..518032657d8e 100644 --- a/examples/shapes_and_collections/collections.py +++ b/examples/shapes_and_collections/collections.py @@ -123,7 +123,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/compound_path.py b/examples/shapes_and_collections/compound_path.py index d721eaf1c392..6a68e28bdf83 100644 --- a/examples/shapes_and_collections/compound_path.py +++ b/examples/shapes_and_collections/compound_path.py @@ -33,7 +33,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/dolphin.py b/examples/shapes_and_collections/dolphin.py index 325b55a96f7b..4e56b244d674 100644 --- a/examples/shapes_and_collections/dolphin.py +++ b/examples/shapes_and_collections/dolphin.py @@ -103,7 +103,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/donut.py b/examples/shapes_and_collections/donut.py index d4c308e75fae..fba51732acaa 100644 --- a/examples/shapes_and_collections/donut.py +++ b/examples/shapes_and_collections/donut.py @@ -62,7 +62,7 @@ def make_circle(r): ax.set_aspect(1.0) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/ellipse_collection.py b/examples/shapes_and_collections/ellipse_collection.py index 7a92eff580ee..4c55ecc44328 100644 --- a/examples/shapes_and_collections/ellipse_collection.py +++ b/examples/shapes_and_collections/ellipse_collection.py @@ -36,7 +36,7 @@ cbar.set_label('X+Y') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/ellipse_demo.py b/examples/shapes_and_collections/ellipse_demo.py index 8d2615af7717..62cb68df016a 100644 --- a/examples/shapes_and_collections/ellipse_demo.py +++ b/examples/shapes_and_collections/ellipse_demo.py @@ -34,7 +34,7 @@ plt.show() -############################################################################# +# %% # =============== # Ellipse Rotated # =============== @@ -56,7 +56,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/fancybox_demo.py b/examples/shapes_and_collections/fancybox_demo.py index ea1383d01941..d9d71d55a1df 100644 --- a/examples/shapes_and_collections/fancybox_demo.py +++ b/examples/shapes_and_collections/fancybox_demo.py @@ -13,7 +13,7 @@ import matplotlib.patches as mpatch from matplotlib.patches import FancyBboxPatch -############################################################################### +# %% # First we'll show some sample boxes with fancybox. styles = mpatch.BoxStyle.get_styles() @@ -39,7 +39,7 @@ horizontalalignment="left", verticalalignment="center") -############################################################################### +# %% # Next we'll show off multiple fancy boxes at once. @@ -110,7 +110,7 @@ def draw_control_points_for_patches(ax): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/hatch_demo.py b/examples/shapes_and_collections/hatch_demo.py index 00b3200a2268..0873b2dc77d1 100644 --- a/examples/shapes_and_collections/hatch_demo.py +++ b/examples/shapes_and_collections/hatch_demo.py @@ -45,7 +45,7 @@ axs['patches'].set_aspect(1) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/hatch_style_reference.py b/examples/shapes_and_collections/hatch_style_reference.py index 5fa13163ff33..b2ac2c269100 100644 --- a/examples/shapes_and_collections/hatch_style_reference.py +++ b/examples/shapes_and_collections/hatch_style_reference.py @@ -30,7 +30,7 @@ def hatches_plot(ax, h): for ax, h in zip(axs.flat, hatches): hatches_plot(ax, h) -############################################################################### +# %% # Hatching patterns can be repeated to increase the density. fig, axs = plt.subplots(2, 5, constrained_layout=True, figsize=(6.4, 3.2)) @@ -40,7 +40,7 @@ def hatches_plot(ax, h): for ax, h in zip(axs.flat, hatches): hatches_plot(ax, h) -############################################################################### +# %% # Hatching patterns can be combined to create additional patterns. fig, axs = plt.subplots(2, 5, constrained_layout=True, figsize=(6.4, 3.2)) @@ -50,7 +50,7 @@ def hatches_plot(ax, h): for ax, h in zip(axs.flat, hatches): hatches_plot(ax, h) -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/line_collection.py b/examples/shapes_and_collections/line_collection.py index c0c44a7d8b8b..57b15f347050 100644 --- a/examples/shapes_and_collections/line_collection.py +++ b/examples/shapes_and_collections/line_collection.py @@ -43,7 +43,7 @@ ax.set_title('Line collection with masked arrays') plt.show() -############################################################################### +# %% # In the following example, instead of passing a list of colors # (``colors=colors``), we pass an array of values (``array=x``) that get # colormapped. @@ -67,7 +67,7 @@ plt.sci(line_segments) # This allows interactive changing of the colormap. plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/patch_collection.py b/examples/shapes_and_collections/patch_collection.py index cdd9f4687619..d1f16b6387c5 100644 --- a/examples/shapes_and_collections/patch_collection.py +++ b/examples/shapes_and_collections/patch_collection.py @@ -56,7 +56,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/path_patch.py b/examples/shapes_and_collections/path_patch.py index 08f1a9457957..9e0f1874923b 100644 --- a/examples/shapes_and_collections/path_patch.py +++ b/examples/shapes_and_collections/path_patch.py @@ -38,7 +38,7 @@ ax.axis('equal') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/quad_bezier.py b/examples/shapes_and_collections/quad_bezier.py index 0059d627126d..4cf8f985d2cc 100644 --- a/examples/shapes_and_collections/quad_bezier.py +++ b/examples/shapes_and_collections/quad_bezier.py @@ -25,7 +25,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/shapes_and_collections/scatter.py b/examples/shapes_and_collections/scatter.py index f5ecd8f10139..6b8bef2b48b4 100644 --- a/examples/shapes_and_collections/scatter.py +++ b/examples/shapes_and_collections/scatter.py @@ -21,7 +21,7 @@ plt.scatter(x, y, s=area, c=colors, alpha=0.5) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/showcase/anatomy.py b/examples/showcase/anatomy.py index f53aa2bb9d9e..94e7a8a0a5dc 100644 --- a/examples/showcase/anatomy.py +++ b/examples/showcase/anatomy.py @@ -103,7 +103,7 @@ def annotate(x, y, text, code): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/showcase/stock_prices.py b/examples/showcase/stock_prices.py index 7f7ffba08f03..768efdfd1891 100644 --- a/examples/showcase/stock_prices.py +++ b/examples/showcase/stock_prices.py @@ -105,7 +105,7 @@ def convertdate(x): # fig.savefig('stock-prices.png', bbox_inches='tight') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/showcase/xkcd.py b/examples/showcase/xkcd.py index 4088a0133814..7708e5f5c747 100644 --- a/examples/showcase/xkcd.py +++ b/examples/showcase/xkcd.py @@ -8,7 +8,7 @@ import matplotlib.pyplot as plt import numpy as np -############################################################################### +# %% with plt.xkcd(): # Based on "Stove Ownership" from XKCD by Randall Munroe @@ -37,7 +37,7 @@ '"Stove Ownership" from xkcd by Randall Munroe', ha='center') -############################################################################### +# %% with plt.xkcd(): # Based on "The Data So Far" from XKCD by Randall Munroe diff --git a/examples/specialty_plots/anscombe.py b/examples/specialty_plots/anscombe.py index 0d45ca350229..333eb6ef42c2 100644 --- a/examples/specialty_plots/anscombe.py +++ b/examples/specialty_plots/anscombe.py @@ -53,7 +53,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/specialty_plots/radar_chart.py b/examples/specialty_plots/radar_chart.py index ae76308f52e6..c452bc0b47ce 100644 --- a/examples/specialty_plots/radar_chart.py +++ b/examples/specialty_plots/radar_chart.py @@ -199,7 +199,7 @@ def example_data(): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/specialty_plots/sankey_basics.py b/examples/specialty_plots/sankey_basics.py index 3bb0cc91cb52..308c22dfb435 100644 --- a/examples/specialty_plots/sankey_basics.py +++ b/examples/specialty_plots/sankey_basics.py @@ -11,7 +11,7 @@ from matplotlib.sankey import Sankey -############################################################################### +# %% # Example 1 -- Mostly defaults # # This demonstrates how to create a simple diagram by implicitly calling the @@ -22,7 +22,7 @@ orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish() plt.title("The default settings produce a diagram like this.") -############################################################################### +# %% # Notice: # # 1. Axes weren't provided when Sankey() was instantiated, so they were @@ -32,7 +32,7 @@ # 3. By default, the lengths of the paths are justified. -############################################################################### +# %% # Example 2 # # This demonstrates: @@ -63,7 +63,7 @@ diagrams[0].texts[-1].set_color('r') diagrams[0].text.set_fontweight('bold') -############################################################################### +# %% # Notice: # # 1. Since the sum of the flows is nonzero, the width of the trunk isn't @@ -72,7 +72,7 @@ # logged at the DEBUG level. -############################################################################### +# %% # Example 3 # # This demonstrates: @@ -93,7 +93,7 @@ diagrams[-1].patch.set_hatch('/') plt.legend() -############################################################################### +# %% # Notice that only one connection is specified, but the systems form a # circuit since: (1) the lengths of the paths are justified and (2) the # orientation and ordering of the flows is mirrored. @@ -101,7 +101,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/specialty_plots/sankey_links.py b/examples/specialty_plots/sankey_links.py index 851111e8d693..c6b1b2101fbe 100644 --- a/examples/specialty_plots/sankey_links.py +++ b/examples/specialty_plots/sankey_links.py @@ -56,7 +56,7 @@ def corner(sankey): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/specialty_plots/sankey_rankine.py b/examples/specialty_plots/sankey_rankine.py index 6313ba3acdcf..5662902384fa 100644 --- a/examples/specialty_plots/sankey_rankine.py +++ b/examples/specialty_plots/sankey_rankine.py @@ -83,7 +83,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/specialty_plots/skewt.py b/examples/specialty_plots/skewt.py index 4cf3f1905e5c..13a46fdc306a 100644 --- a/examples/specialty_plots/skewt.py +++ b/examples/specialty_plots/skewt.py @@ -259,7 +259,7 @@ def upper_xlim(self): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/spines/spine_placement_demo.py b/examples/spines/spine_placement_demo.py index 7d14d854f41a..e4fc00ecd561 100644 --- a/examples/spines/spine_placement_demo.py +++ b/examples/spines/spine_placement_demo.py @@ -12,7 +12,7 @@ import matplotlib.pyplot as plt -############################################################################### +# %% x = np.linspace(0, 2*np.pi, 100) y = 2 * np.sin(x) @@ -50,7 +50,7 @@ ax.spines.bottom.set_position(('data', 2)) ax.spines[['top', 'right']].set_visible(False) -############################################################################### +# %% # Define a method that adjusts the location of the axis spines @@ -75,7 +75,7 @@ def adjust_spines(ax, spines): ax.xaxis.set_ticks([]) -############################################################################### +# %% # Create another figure using our new ``adjust_spines`` method fig = plt.figure() diff --git a/examples/statistics/barchart_demo.py b/examples/statistics/barchart_demo.py index 18819ca35b08..bf73625c4ea0 100644 --- a/examples/statistics/barchart_demo.py +++ b/examples/statistics/barchart_demo.py @@ -99,7 +99,7 @@ def plot_student_results(student, scores_by_test, cohort_size): plot_student_results(student, scores_by_test, cohort_size=62) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/boxplot.py b/examples/statistics/boxplot.py index fa8500cfc42f..f5499e793b86 100644 --- a/examples/statistics/boxplot.py +++ b/examples/statistics/boxplot.py @@ -24,7 +24,7 @@ labels = list('ABCD') fs = 10 # fontsize -############################################################################### +# %% # Demonstrate how to toggle the display of different elements: fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(6, 6), sharey=True) @@ -55,7 +55,7 @@ plt.show() -############################################################################### +# %% # Demonstrate how to customize the display different elements: boxprops = dict(linestyle='--', linewidth=3, color='darkgoldenrod') @@ -95,7 +95,7 @@ fig.subplots_adjust(hspace=0.4) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/boxplot_color.py b/examples/statistics/boxplot_color.py index c26b6672f567..eb3273e34717 100644 --- a/examples/statistics/boxplot_color.py +++ b/examples/statistics/boxplot_color.py @@ -52,7 +52,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/boxplot_demo.py b/examples/statistics/boxplot_demo.py index 252ca25bd58d..5d5e7fdbb42c 100644 --- a/examples/statistics/boxplot_demo.py +++ b/examples/statistics/boxplot_demo.py @@ -75,7 +75,7 @@ plt.show() -############################################################################### +# %% # Below we'll generate data from five different probability distributions, # each with different characteristics. We want to play with how an IID # bootstrap resample of the data preserves the distributional @@ -188,7 +188,7 @@ plt.show() -############################################################################### +# %% # Here we write a custom function to bootstrap confidence intervals. # We can then use the boxplot along with this function to show these intervals. @@ -234,7 +234,7 @@ def fake_bootstrapper(n): plt.show() -############################################################################### +# %% # Here we customize the widths of the caps . x = np.linspace(-7, 7, 140) @@ -245,7 +245,7 @@ def fake_bootstrapper(n): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/boxplot_vs_violin.py b/examples/statistics/boxplot_vs_violin.py index f1162a1ef7a7..dce8912013b0 100644 --- a/examples/statistics/boxplot_vs_violin.py +++ b/examples/statistics/boxplot_vs_violin.py @@ -52,7 +52,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/bxp.py b/examples/statistics/bxp.py index 374db300b5bd..7dc4c99649e7 100644 --- a/examples/statistics/bxp.py +++ b/examples/statistics/bxp.py @@ -26,7 +26,7 @@ # compute the boxplot stats stats = cbook.boxplot_stats(data, labels=labels, bootstrap=10000) -############################################################################### +# %% # After we've computed the stats, we can go through and change anything. # Just to prove it, I'll set the median of each set to the median of all # the data, and double the means @@ -39,7 +39,7 @@ fs = 10 # fontsize -############################################################################### +# %% # Demonstrate how to toggle the display of different elements: fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(6, 6), sharey=True) @@ -69,7 +69,7 @@ fig.subplots_adjust(hspace=0.4) plt.show() -############################################################################### +# %% # Demonstrate how to customize the display different elements: boxprops = dict(linestyle='--', linewidth=3, color='darkgoldenrod') @@ -103,7 +103,7 @@ fig.subplots_adjust(hspace=0.4) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/confidence_ellipse.py b/examples/statistics/confidence_ellipse.py index c67da152ad7d..512154c67672 100644 --- a/examples/statistics/confidence_ellipse.py +++ b/examples/statistics/confidence_ellipse.py @@ -23,7 +23,7 @@ import matplotlib.transforms as transforms -############################################################################# +# %% # # The plotting function itself # """""""""""""""""""""""""""" @@ -92,7 +92,7 @@ def confidence_ellipse(x, y, ax, n_std=3.0, facecolor='none', **kwargs): return ax.add_patch(ellipse) -############################################################################# +# %% # # A helper function to create a correlated dataset # """""""""""""""""""""""""""""""""""""""""""""""" @@ -111,7 +111,7 @@ def get_correlated_dataset(n, dependency, mu, scale): return scaled_with_offset[:, 0], scaled_with_offset[:, 1] -############################################################################# +# %% # # Positive, negative and weak correlation # """"""""""""""""""""""""""""""""""""""" @@ -152,7 +152,7 @@ def get_correlated_dataset(n, dependency, mu, scale): plt.show() -############################################################################# +# %% # # Different number of standard deviations # """"""""""""""""""""""""""""""""""""""" @@ -185,7 +185,7 @@ def get_correlated_dataset(n, dependency, mu, scale): plt.show() -############################################################################# +# %% # # Using the keyword arguments # """"""""""""""""""""""""""" @@ -215,7 +215,7 @@ def get_correlated_dataset(n, dependency, mu, scale): fig.subplots_adjust(hspace=0.25) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/customized_violin.py b/examples/statistics/customized_violin.py index 59978815e57e..c1d2e432ca2e 100644 --- a/examples/statistics/customized_violin.py +++ b/examples/statistics/customized_violin.py @@ -71,7 +71,7 @@ def set_axis_style(ax, labels): plt.subplots_adjust(bottom=0.15, wspace=0.05) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/errorbar.py b/examples/statistics/errorbar.py index 8d674095b4e4..0498734eb480 100644 --- a/examples/statistics/errorbar.py +++ b/examples/statistics/errorbar.py @@ -19,7 +19,7 @@ ax.errorbar(x, y, xerr=0.2, yerr=0.4) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/errorbar_features.py b/examples/statistics/errorbar_features.py index 78e80f0aeb88..d15a045cbf67 100644 --- a/examples/statistics/errorbar_features.py +++ b/examples/statistics/errorbar_features.py @@ -46,7 +46,7 @@ ax1.set_yscale('log') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/errorbar_limits.py b/examples/statistics/errorbar_limits.py index 5013b82ed977..1d92c40c0d17 100644 --- a/examples/statistics/errorbar_limits.py +++ b/examples/statistics/errorbar_limits.py @@ -75,7 +75,7 @@ ax.set_title('Errorbar upper and lower limits') plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/errorbars_and_boxes.py b/examples/statistics/errorbars_and_boxes.py index a8bdd7a46384..d253665796dd 100644 --- a/examples/statistics/errorbars_and_boxes.py +++ b/examples/statistics/errorbars_and_boxes.py @@ -68,7 +68,7 @@ def make_error_boxes(ax, xdata, ydata, xerror, yerror, facecolor='r', plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/hexbin_demo.py b/examples/statistics/hexbin_demo.py index b97e4f6c4347..9c26249f02c5 100644 --- a/examples/statistics/hexbin_demo.py +++ b/examples/statistics/hexbin_demo.py @@ -33,7 +33,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/hist.py b/examples/statistics/hist.py index 6c880961c922..7e8ff37e234c 100644 --- a/examples/statistics/hist.py +++ b/examples/statistics/hist.py @@ -14,7 +14,7 @@ # Create a random number generator with a fixed seed for reproducibility rng = np.random.default_rng(19680801) -############################################################################### +# %% # Generate data and plot a simple histogram # ----------------------------------------- # @@ -36,7 +36,7 @@ axs[1].hist(dist2, bins=n_bins) -############################################################################### +# %% # Updating histogram colors # ------------------------- # @@ -68,7 +68,7 @@ axs[1].yaxis.set_major_formatter(PercentFormatter(xmax=1)) -############################################################################### +# %% # Plot a 2D histogram # ------------------- # @@ -79,7 +79,7 @@ hist = ax.hist2d(dist1, dist2) -############################################################################### +# %% # Customizing your histogram # -------------------------- # @@ -100,7 +100,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/histogram_cumulative.py b/examples/statistics/histogram_cumulative.py index 443d30e69ee0..67e3d15a8683 100644 --- a/examples/statistics/histogram_cumulative.py +++ b/examples/statistics/histogram_cumulative.py @@ -70,7 +70,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/histogram_features.py b/examples/statistics/histogram_features.py index 31f88384f24c..972ee1621418 100644 --- a/examples/statistics/histogram_features.py +++ b/examples/statistics/histogram_features.py @@ -46,7 +46,7 @@ fig.tight_layout() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/histogram_histtypes.py b/examples/statistics/histogram_histtypes.py index ca5c051d943c..f6088cc72347 100644 --- a/examples/statistics/histogram_histtypes.py +++ b/examples/statistics/histogram_histtypes.py @@ -49,7 +49,7 @@ fig.tight_layout() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/histogram_multihist.py b/examples/statistics/histogram_multihist.py index c832259c6670..63fc651b8813 100644 --- a/examples/statistics/histogram_multihist.py +++ b/examples/statistics/histogram_multihist.py @@ -45,7 +45,7 @@ fig.tight_layout() plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/multiple_histograms_side_by_side.py b/examples/statistics/multiple_histograms_side_by_side.py index 814229636682..5113222d7c15 100644 --- a/examples/statistics/multiple_histograms_side_by_side.py +++ b/examples/statistics/multiple_histograms_side_by_side.py @@ -61,7 +61,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/time_series_histogram.py b/examples/statistics/time_series_histogram.py index a22ceb4e24d4..24b268d6d126 100644 --- a/examples/statistics/time_series_histogram.py +++ b/examples/statistics/time_series_histogram.py @@ -95,7 +95,7 @@ print(f"{toc-tic:.3f} sec. elapsed") plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/statistics/violinplot.py b/examples/statistics/violinplot.py index 7d519554a795..799757c7fa5a 100644 --- a/examples/statistics/violinplot.py +++ b/examples/statistics/violinplot.py @@ -86,7 +86,7 @@ fig.subplots_adjust(hspace=0.4) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/subplots_axes_and_figures/auto_subplots_adjust.py b/examples/subplots_axes_and_figures/auto_subplots_adjust.py index bd6326b8291f..a99c84d18a90 100644 --- a/examples/subplots_axes_and_figures/auto_subplots_adjust.py +++ b/examples/subplots_axes_and_figures/auto_subplots_adjust.py @@ -69,7 +69,7 @@ def on_draw(event): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/subplots_axes_and_figures/axes_box_aspect.py b/examples/subplots_axes_and_figures/axes_box_aspect.py index 019c7e43c787..752d8d9ba64c 100644 --- a/examples/subplots_axes_and_figures/axes_box_aspect.py +++ b/examples/subplots_axes_and_figures/axes_box_aspect.py @@ -13,7 +13,7 @@ The following lists a few use cases for `~.Axes.set_box_aspect`. """ -############################################################################ +# %% # A square axes, independent of data # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # @@ -29,7 +29,7 @@ plt.show() -############################################################################ +# %% # Shared square axes # ~~~~~~~~~~~~~~~~~~ # @@ -45,7 +45,7 @@ plt.show() -############################################################################ +# %% # Square twin axes # ~~~~~~~~~~~~~~~~ # @@ -65,7 +65,7 @@ plt.show() -############################################################################ +# %% # Normal plot next to image # ~~~~~~~~~~~~~~~~~~~~~~~~~ # @@ -88,7 +88,7 @@ plt.show() -############################################################################ +# %% # Square joint/marginal plot # ~~~~~~~~~~~~~~~~~~~~~~~~~~ # @@ -114,7 +114,7 @@ plt.show() -############################################################################ +# %% # Square joint/marginal plot # ~~~~~~~~~~~~~~~~~~~~~~~~~~ # @@ -131,7 +131,7 @@ plt.show() -############################################################################ +# %% # Box aspect for many subplots # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # @@ -145,7 +145,7 @@ ax.scatter(i % 3, -((i // 3) - 0.5)*200, c=[plt.cm.hsv(i / 6)], s=300) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/subplots_axes_and_figures/axes_margins.py b/examples/subplots_axes_and_figures/axes_margins.py index e84a6e835924..7eb3a461beef 100644 --- a/examples/subplots_axes_and_figures/axes_margins.py +++ b/examples/subplots_axes_and_figures/axes_margins.py @@ -39,7 +39,7 @@ def f(t): plt.show() -############################################################################# +# %% # # On the "stickiness" of certain plotting methods # """"""""""""""""""""""""""""""""""""""""""""""" @@ -74,7 +74,7 @@ def f(t): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/subplots_axes_and_figures/colorbar_placement.py b/examples/subplots_axes_and_figures/colorbar_placement.py index 66e267ce6d43..8581dbb7255f 100644 --- a/examples/subplots_axes_and_figures/colorbar_placement.py +++ b/examples/subplots_axes_and_figures/colorbar_placement.py @@ -24,7 +24,7 @@ cmap=cmaps[col]) fig.colorbar(pcm, ax=ax) -###################################################################### +# %% # The first column has the same type of data in both rows, so it may # be desirable to combine the colorbar which we do by calling # `.Figure.colorbar` with a list of axes instead of a single axes. @@ -38,7 +38,7 @@ cmap=cmaps[col]) fig.colorbar(pcm, ax=axs[:, col], shrink=0.6) -###################################################################### +# %% # Relatively complicated colorbar layouts are possible using this # paradigm. Note that this example works far better with # ``constrained_layout=True`` @@ -52,7 +52,7 @@ fig.colorbar(pcm, ax=axs[1:, :], location='right', shrink=0.6) fig.colorbar(pcm, ax=[axs[2, 1]], location='left') -###################################################################### +# %% # Colorbars with fixed-aspect-ratio axes # ====================================== # @@ -73,7 +73,7 @@ if row == 1: fig.colorbar(pcm, ax=ax, shrink=0.6) -###################################################################### +# %% # One way around this issue is to use an `.Axes.inset_axes` to locate the # axes in axes coordinates. Note that if you zoom in on the axes, and # change the shape of the axes, the colorbar will also change position. diff --git a/examples/subplots_axes_and_figures/custom_figure_class.py b/examples/subplots_axes_and_figures/custom_figure_class.py index efaa3f3621f1..49070bcd7c54 100644 --- a/examples/subplots_axes_and_figures/custom_figure_class.py +++ b/examples/subplots_axes_and_figures/custom_figure_class.py @@ -39,7 +39,7 @@ def __init__(self, *args, watermark=None, **kwargs): plt.plot(x, y) -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/subplots_axes_and_figures/demo_constrained_layout.py b/examples/subplots_axes_and_figures/demo_constrained_layout.py index 26109cbe3129..a6d03be09c4b 100644 --- a/examples/subplots_axes_and_figures/demo_constrained_layout.py +++ b/examples/subplots_axes_and_figures/demo_constrained_layout.py @@ -22,7 +22,7 @@ def example_plot(ax): ax.set_title('Title', fontsize=14) -############################################################################### +# %% # If we don't use constrained_layout, then labels overlap the axes fig, axs = plt.subplots(nrows=2, ncols=2, constrained_layout=False) @@ -30,7 +30,7 @@ def example_plot(ax): for ax in axs.flat: example_plot(ax) -############################################################################### +# %% # adding ``constrained_layout=True`` automatically adjusts. fig, axs = plt.subplots(nrows=2, ncols=2, constrained_layout=True) @@ -38,7 +38,7 @@ def example_plot(ax): for ax in axs.flat: example_plot(ax) -############################################################################### +# %% # Below is a more complicated example using nested gridspecs. fig = plt.figure(constrained_layout=True) @@ -60,7 +60,7 @@ def example_plot(ax): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/subplots_axes_and_figures/demo_tight_layout.py b/examples/subplots_axes_and_figures/demo_tight_layout.py index e3f22618ede5..8c76e4821355 100644 --- a/examples/subplots_axes_and_figures/demo_tight_layout.py +++ b/examples/subplots_axes_and_figures/demo_tight_layout.py @@ -26,13 +26,13 @@ def example_plot(ax): ax.set_title('Title', fontsize=next(fontsizes)) -############################################################################### +# %% fig, ax = plt.subplots() example_plot(ax) fig.tight_layout() -############################################################################### +# %% fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2) example_plot(ax1) @@ -41,28 +41,28 @@ def example_plot(ax): example_plot(ax4) fig.tight_layout() -############################################################################### +# %% fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1) example_plot(ax1) example_plot(ax2) fig.tight_layout() -############################################################################### +# %% fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2) example_plot(ax1) example_plot(ax2) fig.tight_layout() -############################################################################### +# %% fig, axs = plt.subplots(nrows=3, ncols=3) for ax in axs.flat: example_plot(ax) fig.tight_layout() -############################################################################### +# %% plt.figure() ax1 = plt.subplot(221) @@ -73,7 +73,7 @@ def example_plot(ax): example_plot(ax3) plt.tight_layout() -############################################################################### +# %% plt.figure() ax1 = plt.subplot2grid((3, 3), (0, 0)) @@ -86,7 +86,7 @@ def example_plot(ax): example_plot(ax4) plt.tight_layout() -############################################################################### +# %% fig = plt.figure() @@ -120,7 +120,7 @@ def example_plot(ax): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/subplots_axes_and_figures/figure_size_units.py b/examples/subplots_axes_and_figures/figure_size_units.py index 94de72c1554c..2af10405a569 100644 --- a/examples/subplots_axes_and_figures/figure_size_units.py +++ b/examples/subplots_axes_and_figures/figure_size_units.py @@ -14,7 +14,7 @@ import matplotlib.pyplot as plt text_kwargs = dict(ha='center', va='center', fontsize=28, color='C1') -############################################################################## +# %% # Figure size in inches (default) # ------------------------------- # @@ -23,7 +23,7 @@ plt.show() -############################################################################# +# %% # Figure size in centimeter # ------------------------- # Multiplying centimeter-based numbers with a conversion factor from cm to @@ -37,7 +37,7 @@ plt.show() -############################################################################# +# %% # Figure size in pixel # -------------------- # Similarly, one can use a conversion from pixels. @@ -50,7 +50,7 @@ plt.text(0.5, 0.5, '600px x 200px', **text_kwargs) plt.show() -############################################################################# +# %% # Quick interactive work is usually rendered to the screen, making pixels a # good size of unit. But defining the conversion factor may feel a little # tedious for quick iterations. @@ -62,14 +62,14 @@ plt.text(0.5, 0.5, '600px x 200px', **text_kwargs) plt.show() -############################################################################# +# %% # .. [#] Unfortunately, this does not work well for the ``matplotlib inline`` # backend in Jupyter because that backend uses a different default of # ``rcParams['figure.dpi'] = 72``. Additionally, it saves the figure # with ``bbox_inches='tight'``, which crops the figure and makes the # actual size unpredictable. -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/subplots_axes_and_figures/figure_title.py b/examples/subplots_axes_and_figures/figure_title.py index 0b8a7e2c5855..c3277fa6d8c0 100644 --- a/examples/subplots_axes_and_figures/figure_title.py +++ b/examples/subplots_axes_and_figures/figure_title.py @@ -30,7 +30,7 @@ fig.suptitle('Different types of oscillations', fontsize=16) -############################################################################## +# %% # A global x- or y-label can be set using the `.FigureBase.supxlabel` and # `.FigureBase.supylabel` methods. diff --git a/examples/subplots_axes_and_figures/geo_demo.py b/examples/subplots_axes_and_figures/geo_demo.py index 27b6f27ae6e4..f2f22751b215 100644 --- a/examples/subplots_axes_and_figures/geo_demo.py +++ b/examples/subplots_axes_and_figures/geo_demo.py @@ -11,28 +11,28 @@ import matplotlib.pyplot as plt -############################################################################### +# %% plt.figure() plt.subplot(projection="aitoff") plt.title("Aitoff") plt.grid(True) -############################################################################### +# %% plt.figure() plt.subplot(projection="hammer") plt.title("Hammer") plt.grid(True) -############################################################################### +# %% plt.figure() plt.subplot(projection="lambert") plt.title("Lambert") plt.grid(True) -############################################################################### +# %% plt.figure() plt.subplot(projection="mollweide") diff --git a/examples/subplots_axes_and_figures/mosaic.py b/examples/subplots_axes_and_figures/mosaic.py index 9b77893bb2d6..b64a052cd226 100644 --- a/examples/subplots_axes_and_figures/mosaic.py +++ b/examples/subplots_axes_and_figures/mosaic.py @@ -53,7 +53,7 @@ def identify_axes(ax_dict, fontsize=48): ax.text(0.5, 0.5, k, transform=ax.transAxes, **kw) -############################################################################### +# %% # If we want a 2x2 grid we can use `.Figure.subplots` which returns a 2D array # of `.axes.Axes` which we can index into to do our plotting. np.random.seed(19680801) @@ -72,7 +72,7 @@ def identify_axes(ax_dict, fontsize=48): {(j, k): a for j, r in enumerate(ax_array) for k, a in enumerate(r)}, ) -############################################################################### +# %% # Using `.Figure.subplot_mosaic` we can produce the same mosaic but give the # axes semantic names @@ -89,7 +89,7 @@ def identify_axes(ax_dict, fontsize=48): ax_dict["image"].imshow([[1, 2], [2, 1]]) identify_axes(ax_dict) -############################################################################### +# %% # A key difference between `.Figure.subplots` and # `.Figure.subplot_mosaic` is the return value. While the former # returns an array for index access, the latter returns a dictionary @@ -98,7 +98,7 @@ def identify_axes(ax_dict, fontsize=48): print(ax_dict) -############################################################################### +# %% # String short-hand # ================= # @@ -111,7 +111,7 @@ def identify_axes(ax_dict, fontsize=48): CD """ -############################################################################### +# %% # will give us 4 Axes laid out in a 2x2 grid and generates the same # figure mosaic as above (but now labeled with ``{"A", "B", "C", # "D"}`` rather than ``{"bar", "plot", "hist", "image"}``). @@ -120,11 +120,11 @@ def identify_axes(ax_dict, fontsize=48): ax_dict = fig.subplot_mosaic(mosaic) identify_axes(ax_dict) -############################################################################### +# %% # Alternatively, you can use the more compact string notation mosaic = "AB;CD" -############################################################################### +# %% # will give you the same composition, where the ``";"`` is used # as the row separator instead of newline. @@ -132,7 +132,7 @@ def identify_axes(ax_dict, fontsize=48): ax_dict = fig.subplot_mosaic(mosaic) identify_axes(ax_dict) -############################################################################### +# %% # Axes spanning multiple rows/columns # =================================== # @@ -141,7 +141,7 @@ def identify_axes(ax_dict, fontsize=48): # several rows or columns. -############################################################################### +# %% # If we want to re-arrange our four Axes to have ``"C"`` be a horizontal # span on the bottom and ``"D"`` be a vertical span on the right we would do @@ -153,7 +153,7 @@ def identify_axes(ax_dict, fontsize=48): ) identify_axes(axd) -############################################################################### +# %% # If we do not want to fill in all the spaces in the Figure with Axes, # we can specify some spaces in the grid to be blank @@ -168,7 +168,7 @@ def identify_axes(ax_dict, fontsize=48): identify_axes(axd) -############################################################################### +# %% # If we prefer to use another character (rather than a period ``"."``) # to mark the empty space, we can use *empty_sentinel* to specify the # character to use. @@ -183,7 +183,7 @@ def identify_axes(ax_dict, fontsize=48): identify_axes(axd) -############################################################################### +# %% # # Internally there is no meaning attached to the letters we use, any # Unicode code point is valid! @@ -194,7 +194,7 @@ def identify_axes(ax_dict, fontsize=48): ) identify_axes(axd) -############################################################################### +# %% # It is not recommended to use white space as either a label or an # empty sentinel with the string shorthand because it may be stripped # while processing the input. @@ -225,7 +225,7 @@ def identify_axes(ax_dict, fontsize=48): ) identify_axes(axd) -############################################################################### +# %% # Other `.gridspec.GridSpec` keywords can be passed via *gridspec_kw*. For # example, use the {*left*, *right*, *bottom*, *top*} keyword arguments to # position the overall mosaic to put multiple versions of the same @@ -260,7 +260,7 @@ def identify_axes(ax_dict, fontsize=48): ) identify_axes(axd) -############################################################################### +# %% # Alternatively, you can use the sub-Figure functionality: mosaic = """AA @@ -274,7 +274,7 @@ def identify_axes(ax_dict, fontsize=48): identify_axes(axd) -############################################################################### +# %% # Controlling subplot creation # ============================ # @@ -288,7 +288,7 @@ def identify_axes(ax_dict, fontsize=48): ) identify_axes(axd) -############################################################################### +# %% # Per-Axes subplot keyword arguments # ---------------------------------- # @@ -309,7 +309,7 @@ def identify_axes(ax_dict, fontsize=48): ) identify_axes(axd) -############################################################################### +# %% # If the layout is specified with the string short-hand, then we know the # Axes labels will be one character and can unambiguously interpret longer # strings in *per_subplot_kw* to specify a set of Axes to apply the @@ -325,7 +325,7 @@ def identify_axes(ax_dict, fontsize=48): ) identify_axes(axd) -############################################################################### +# %% # If *subplot_kw* and *per_subplot_kw* are used together, then they are # merged with *per_subplot_kw* taking priority: @@ -341,7 +341,7 @@ def identify_axes(ax_dict, fontsize=48): identify_axes(axd) -############################################################################### +# %% # Nested list input # ================= # @@ -360,7 +360,7 @@ def identify_axes(ax_dict, fontsize=48): identify_axes(axd) -############################################################################### +# %% # In addition, using the list input we can specify nested mosaics. Any element # of the inner list can be another set of nested lists: @@ -379,7 +379,7 @@ def identify_axes(ax_dict, fontsize=48): identify_axes(axd, fontsize=36) -############################################################################### +# %% # We can also pass in a 2D NumPy array to do things like mosaic = np.zeros((4, 4), dtype=int) for j in range(4): diff --git a/examples/subplots_axes_and_figures/multiple_figs_demo.py b/examples/subplots_axes_and_figures/multiple_figs_demo.py index ee667e95565f..9bb9962c8e28 100644 --- a/examples/subplots_axes_and_figures/multiple_figs_demo.py +++ b/examples/subplots_axes_and_figures/multiple_figs_demo.py @@ -24,7 +24,7 @@ s1 = np.sin(2*np.pi*t) s2 = np.sin(4*np.pi*t) -############################################################################### +# %% # Create figure 1 plt.figure(1) @@ -33,13 +33,13 @@ plt.subplot(212) plt.plot(t, 2*s1) -############################################################################### +# %% # Create figure 2 plt.figure(2) plt.plot(t, s2) -############################################################################### +# %% # Now switch back to figure 1 and make some changes plt.figure(1) diff --git a/examples/subplots_axes_and_figures/secondary_axis.py b/examples/subplots_axes_and_figures/secondary_axis.py index a8ba17d3478b..cabe46023a73 100644 --- a/examples/subplots_axes_and_figures/secondary_axis.py +++ b/examples/subplots_axes_and_figures/secondary_axis.py @@ -38,7 +38,7 @@ def rad2deg(x): secax.set_xlabel('angle [rad]') plt.show() -########################################################################### +# %% # Here is the case of converting from wavenumber to wavelength in a # log-log scale. # @@ -74,7 +74,7 @@ def one_over(x): secax.set_xlabel('period [s]') plt.show() -########################################################################### +# %% # Sometime we want to relate the axes in a transform that is ad-hoc from # the data, and is derived empirically. In that case we can set the # forward and inverse transforms functions to be linear interpolations from the @@ -120,7 +120,7 @@ def inverse(x): plt.show() -########################################################################### +# %% # A final example translates np.datetime64 to yearday on the x axis and # from Celsius to Fahrenheit on the y axis. Note the addition of a # third y axis, and that it can be placed using a float for the @@ -181,7 +181,7 @@ def anomaly_to_celsius(x): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/subplots_axes_and_figures/subfigures.py b/examples/subplots_axes_and_figures/subfigures.py index 1e7ae401554b..48a2d3e17581 100644 --- a/examples/subplots_axes_and_figures/subfigures.py +++ b/examples/subplots_axes_and_figures/subfigures.py @@ -57,7 +57,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): plt.show() -############################################################################## +# %% # It is possible to mix subplots and subfigures using # `matplotlib.figure.Figure.add_subfigure`. This requires getting # the gridspec that the subplots are laid out on. @@ -86,7 +86,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.suptitle('Figure suptitle', fontsize='xx-large') plt.show() -############################################################################## +# %% # Subfigures can have different widths and heights. This is exactly the # same example as the first example, but *width_ratios* has been changed: @@ -116,7 +116,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): plt.show() -############################################################################## +# %% # Subfigures can be also be nested: fig = plt.figure(constrained_layout=True, figsize=(10, 8)) diff --git a/examples/subplots_axes_and_figures/subplot.py b/examples/subplots_axes_and_figures/subplot.py index c368746a8856..3aeb8af45a97 100644 --- a/examples/subplots_axes_and_figures/subplot.py +++ b/examples/subplots_axes_and_figures/subplot.py @@ -19,7 +19,7 @@ x2 = np.linspace(0.0, 2.0) y2 = np.cos(2 * np.pi * x2) -############################################################################### +# %% # `~.pyplot.subplots()` is the recommended method to generate simple subplot # arrangements: @@ -35,7 +35,7 @@ plt.show() -############################################################################### +# %% # Subplots can also be generated one at a time using `~.pyplot.subplot()`: plt.subplot(2, 1, 1) diff --git a/examples/subplots_axes_and_figures/subplots_demo.py b/examples/subplots_axes_and_figures/subplots_demo.py index 41b14dadd620..2e2dc3681cde 100644 --- a/examples/subplots_axes_and_figures/subplots_demo.py +++ b/examples/subplots_axes_and_figures/subplots_demo.py @@ -19,7 +19,7 @@ x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) -############################################################################### +# %% # A figure with just one subplot # """""""""""""""""""""""""""""" # @@ -33,7 +33,7 @@ ax.plot(x, y) ax.set_title('A single plot') -############################################################################### +# %% # Stacking subplots in one direction # """""""""""""""""""""""""""""""""" # @@ -48,7 +48,7 @@ axs[0].plot(x, y) axs[1].plot(x, -y) -############################################################################### +# %% # If you are creating just a few Axes, it's handy to unpack them immediately to # dedicated variables for each Axes. That way, we can use ``ax1`` instead of # the more verbose ``axs[0]``. @@ -58,7 +58,7 @@ ax1.plot(x, y) ax2.plot(x, -y) -############################################################################### +# %% # To obtain side-by-side subplots, pass parameters ``1, 2`` for one row and two # columns. @@ -67,7 +67,7 @@ ax1.plot(x, y) ax2.plot(x, -y) -############################################################################### +# %% # Stacking subplots in two directions # """"""""""""""""""""""""""""""""""" # @@ -93,7 +93,7 @@ for ax in axs.flat: ax.label_outer() -############################################################################### +# %% # You can use tuple-unpacking also in 2D to assign all subplots to dedicated # variables: @@ -107,7 +107,7 @@ for ax in fig.get_axes(): ax.label_outer() -############################################################################### +# %% # Sharing axes # """""""""""" # @@ -119,7 +119,7 @@ ax1.plot(x, y) ax2.plot(x + 1, -y) -############################################################################### +# %% # You can use *sharex* or *sharey* to align the horizontal or vertical axis. fig, (ax1, ax2) = plt.subplots(2, sharex=True) @@ -127,7 +127,7 @@ ax1.plot(x, y) ax2.plot(x + 1, -y) -############################################################################### +# %% # Setting *sharex* or *sharey* to ``True`` enables global sharing across the # whole grid, i.e. also the y-axes of vertically stacked subplots have the # same scale when using ``sharey=True``. @@ -138,7 +138,7 @@ axs[1].plot(x, 0.3 * y, 'o') axs[2].plot(x, y, '+') -############################################################################### +# %% # For subplots that are sharing axes one set of tick labels is enough. Tick # labels of inner Axes are automatically removed by *sharex* and *sharey*. # Still there remains an unused empty space between the subplots. @@ -163,7 +163,7 @@ for ax in axs: ax.label_outer() -############################################################################### +# %% # Apart from ``True`` and ``False``, both *sharex* and *sharey* accept the # values 'row' and 'col' to share the values only per row or column. @@ -179,7 +179,7 @@ for ax in fig.get_axes(): ax.label_outer() -############################################################################### +# %% # If you want a more complex sharing structure, you can first create the # grid of axes with no sharing, and then call `.axes.Axes.sharex` or # `.axes.Axes.sharey` to add sharing info a posteriori. @@ -196,7 +196,7 @@ axs[1, 1].set_title("also unrelated") fig.tight_layout() -############################################################################### +# %% # Polar axes # """""""""" # diff --git a/examples/subplots_axes_and_figures/two_scales.py b/examples/subplots_axes_and_figures/two_scales.py index 307f6c7053be..75660b2d7bcd 100644 --- a/examples/subplots_axes_and_figures/two_scales.py +++ b/examples/subplots_axes_and_figures/two_scales.py @@ -39,7 +39,7 @@ fig.tight_layout() # otherwise the right y-label is slightly clipped plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/subplots_axes_and_figures/zoom_inset_axes.py b/examples/subplots_axes_and_figures/zoom_inset_axes.py index db78aedb318f..e0939c2029c0 100644 --- a/examples/subplots_axes_and_figures/zoom_inset_axes.py +++ b/examples/subplots_axes_and_figures/zoom_inset_axes.py @@ -40,7 +40,7 @@ def get_demo_image(): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/accented_text.py b/examples/text_labels_and_annotations/accented_text.py index 9e9ad65e9f15..f57b19532a43 100644 --- a/examples/text_labels_and_annotations/accented_text.py +++ b/examples/text_labels_and_annotations/accented_text.py @@ -24,7 +24,7 @@ ax.text(4, 0.5, r"$F=m\ddot{x}$") fig.tight_layout() -############################################################################# +# %% # You can also use Unicode characters directly in strings. fig, ax = plt.subplots() ax.set_title("GISCARD CHAHUTÉ À L'ASSEMBLÉE") diff --git a/examples/text_labels_and_annotations/align_ylabels.py b/examples/text_labels_and_annotations/align_ylabels.py index 8e47909cc6c1..c0e08729039f 100644 --- a/examples/text_labels_and_annotations/align_ylabels.py +++ b/examples/text_labels_and_annotations/align_ylabels.py @@ -47,7 +47,7 @@ def make_plot(axs): fig.align_ylabels(axs[:, 1]) plt.show() -############################################################################# +# %% # # .. seealso:: # `.Figure.align_ylabels` and `.Figure.align_labels` for a direct method @@ -71,7 +71,7 @@ def make_plot(axs): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/angle_annotation.py b/examples/text_labels_and_annotations/angle_annotation.py index 8272dd1f3e06..613ffc74e805 100644 --- a/examples/text_labels_and_annotations/angle_annotation.py +++ b/examples/text_labels_and_annotations/angle_annotation.py @@ -28,7 +28,7 @@ the :ref:`angle-annotation-usage` section. """ -######################################################################### +# %% # AngleAnnotation class # ~~~~~~~~~~~~~~~~~~~~~ # The essential idea here is to subclass `~.patches.Arc` and set its transform @@ -210,7 +210,7 @@ def R(a, r, w, h): self.text.set_position([offs*np.cos(angle), offs*np.sin(angle)]) -######################################################################### +# %% # .. _angle-annotation-usage: # # Usage @@ -251,7 +251,7 @@ def R(a, r, w, h): text_kw=dict(fontsize=16, color="gray")) -######################################################################### +# %% # ``AngleLabel`` options # ~~~~~~~~~~~~~~~~~~~~~~ # @@ -310,7 +310,7 @@ def plot_angle(ax, pos, angle, length=0.95, acol="C0", **kwargs): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/angles_on_bracket_arrows.py b/examples/text_labels_and_annotations/angles_on_bracket_arrows.py index 35a6cad22130..b48e7c9cc34f 100644 --- a/examples/text_labels_and_annotations/angles_on_bracket_arrows.py +++ b/examples/text_labels_and_annotations/angles_on_bracket_arrows.py @@ -54,7 +54,7 @@ def get_point_of_rotated_vertical(origin, line_length, degrees): ax.text(vline[0] - dir * 0.15, y + 0.3, f'{angle}°', ha="center", va="center") -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/annotate_transform.py b/examples/text_labels_and_annotations/annotate_transform.py index 1145f7fdb9a2..bfd7027e5a5b 100644 --- a/examples/text_labels_and_annotations/annotate_transform.py +++ b/examples/text_labels_and_annotations/annotate_transform.py @@ -43,7 +43,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/annotation_basic.py b/examples/text_labels_and_annotations/annotation_basic.py index d9ea9748197f..f42b5d85c512 100644 --- a/examples/text_labels_and_annotations/annotation_basic.py +++ b/examples/text_labels_and_annotations/annotation_basic.py @@ -26,7 +26,7 @@ ax.set_ylim(-2, 2) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/annotation_demo.py b/examples/text_labels_and_annotations/annotation_demo.py index 2008a8744675..a37859a1b59e 100644 --- a/examples/text_labels_and_annotations/annotation_demo.py +++ b/examples/text_labels_and_annotations/annotation_demo.py @@ -16,7 +16,7 @@ from matplotlib.text import OffsetFrom -############################################################################### +# %% # Specifying text points and annotation points # -------------------------------------------- # @@ -96,7 +96,7 @@ ax.set(xlim=(-1, 5), ylim=(-3, 5)) -############################################################################### +# %% # Using multiple coordinate systems and axis types # ------------------------------------------------ # @@ -125,7 +125,7 @@ horizontalalignment='left', verticalalignment='bottom') -############################################################################# +# %% # You can also use polar notation on a cartesian axes. Here the native # coordinate system ('data') is cartesian, so you need to specify the # xycoords and textcoords as 'polar' if you want to use (theta, radius). @@ -148,7 +148,7 @@ ax.set(xlim=[-20, 20], ylim=[-20, 20]) -############################################################################### +# %% # Customizing arrow and bubble styles # ----------------------------------- # @@ -231,7 +231,7 @@ ax.set(xlim=(-1, 5), ylim=(-4, 3)) -############################################################################# +# %% # We'll create another figure so that it doesn't get too cluttered fig, ax = plt.subplots() @@ -295,7 +295,7 @@ ax.set(xlim=(-1, 5), ylim=(-5, 3)) -############################################################################### +# %% # More examples of coordinate systems # ----------------------------------- # diff --git a/examples/text_labels_and_annotations/annotation_polar.py b/examples/text_labels_and_annotations/annotation_polar.py index a7f8b764d914..08778fe8ec46 100644 --- a/examples/text_labels_and_annotations/annotation_polar.py +++ b/examples/text_labels_and_annotations/annotation_polar.py @@ -32,7 +32,7 @@ ) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/custom_legends.py b/examples/text_labels_and_annotations/custom_legends.py index 7f4ca07398f4..ecb61e200d3d 100644 --- a/examples/text_labels_and_annotations/custom_legends.py +++ b/examples/text_labels_and_annotations/custom_legends.py @@ -36,7 +36,7 @@ lines = ax.plot(data) ax.legend() -############################################################################## +# %% # Note that no legend entries were created. # In this case, we can compose a legend using Matplotlib objects that aren't # explicitly tied to the data that was plotted. For example: @@ -51,7 +51,7 @@ ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']) -############################################################################### +# %% # There are many other Matplotlib objects that can be used in this way. In the # code below we've listed a few common ones. diff --git a/examples/text_labels_and_annotations/demo_annotation_box.py b/examples/text_labels_and_annotations/demo_annotation_box.py index 1f2f812649a4..52a1c854c4cb 100644 --- a/examples/text_labels_and_annotations/demo_annotation_box.py +++ b/examples/text_labels_and_annotations/demo_annotation_box.py @@ -103,7 +103,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/demo_text_rotation_mode.py b/examples/text_labels_and_annotations/demo_text_rotation_mode.py index 8920cb543162..a571a07edf49 100644 --- a/examples/text_labels_and_annotations/demo_text_rotation_mode.py +++ b/examples/text_labels_and_annotations/demo_text_rotation_mode.py @@ -78,7 +78,7 @@ def test_rotation_mode(fig, mode): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/fancyarrow_demo.py b/examples/text_labels_and_annotations/fancyarrow_demo.py index 12bf39ee57b6..85df80c700cf 100644 --- a/examples/text_labels_and_annotations/fancyarrow_demo.py +++ b/examples/text_labels_and_annotations/fancyarrow_demo.py @@ -50,7 +50,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/figlegend_demo.py b/examples/text_labels_and_annotations/figlegend_demo.py index c749ae795cd5..7f4e59d573db 100644 --- a/examples/text_labels_and_annotations/figlegend_demo.py +++ b/examples/text_labels_and_annotations/figlegend_demo.py @@ -29,7 +29,7 @@ plt.tight_layout() plt.show() -############################################################################## +# %% # Sometimes we do not want the legend to overlap the axes. If you use # constrained_layout you can specify "outside right upper", and # constrained_layout will make room for the legend. diff --git a/examples/text_labels_and_annotations/font_family_rc.py b/examples/text_labels_and_annotations/font_family_rc.py index d840a8575920..f7fc4376383e 100644 --- a/examples/text_labels_and_annotations/font_family_rc.py +++ b/examples/text_labels_and_annotations/font_family_rc.py @@ -36,7 +36,7 @@ print(plt.rcParams["font.monospace"][0]) -################################################################# +# %% # Choose default sans-serif font def print_text(text): @@ -50,7 +50,7 @@ def print_text(text): print_text("Hello World! 01") -################################################################# +# %% # Choose sans-serif font and specify to it to "Nimbus Sans" plt.rcParams["font.family"] = "sans-serif" @@ -58,14 +58,14 @@ def print_text(text): print_text("Hello World! 02") -################################################################## +# %% # Choose default monospace font plt.rcParams["font.family"] = "monospace" print_text("Hello World! 03") -################################################################### +# %% # Choose monospace font and specify to it to "FreeMono" plt.rcParams["font.family"] = "monospace" diff --git a/examples/text_labels_and_annotations/font_file.py b/examples/text_labels_and_annotations/font_file.py index 7d808a122231..575affa9b011 100644 --- a/examples/text_labels_and_annotations/font_file.py +++ b/examples/text_labels_and_annotations/font_file.py @@ -30,7 +30,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/label_subplots.py b/examples/text_labels_and_annotations/label_subplots.py index 974b775a9a97..2cd7ba684752 100644 --- a/examples/text_labels_and_annotations/label_subplots.py +++ b/examples/text_labels_and_annotations/label_subplots.py @@ -28,7 +28,7 @@ plt.show() -############################################################################## +# %% # We may prefer the labels outside the axes, but still aligned # with each other, in which case we use a slightly different transform: @@ -43,7 +43,7 @@ plt.show() -############################################################################## +# %% # If we want it aligned with the title, either incorporate in the title or # use the *loc* keyword argument: @@ -56,7 +56,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/legend.py b/examples/text_labels_and_annotations/legend.py index 33d8af3204e4..d0df56d3a205 100644 --- a/examples/text_labels_and_annotations/legend.py +++ b/examples/text_labels_and_annotations/legend.py @@ -28,7 +28,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/legend_demo.py b/examples/text_labels_and_annotations/legend_demo.py index 0dc0858f3cc4..6fc0efa20cd7 100644 --- a/examples/text_labels_and_annotations/legend_demo.py +++ b/examples/text_labels_and_annotations/legend_demo.py @@ -36,7 +36,7 @@ plt.show() -############################################################################### +# %% # Next we'll demonstrate plotting more complex labels. x = np.linspace(0, 1) @@ -60,7 +60,7 @@ plt.show() -############################################################################### +# %% # Here we attach legends to more complex plots. fig, axs = plt.subplots(3, 1, constrained_layout=True) @@ -83,7 +83,7 @@ plt.show() -############################################################################### +# %% # Now we'll showcase legend entries with more than one legend key. fig, (ax1, ax2) = plt.subplots(2, 1, constrained_layout=True) @@ -115,7 +115,7 @@ (rneg, rpos): HandlerTuple(ndivide=None, pad=0.)}) plt.show() -############################################################################### +# %% # Finally, it is also possible to write custom classes that define # how to stylize legends. diff --git a/examples/text_labels_and_annotations/line_with_text.py b/examples/text_labels_and_annotations/line_with_text.py index 51f1a27d98ec..12cd5e77ff0d 100644 --- a/examples/text_labels_and_annotations/line_with_text.py +++ b/examples/text_labels_and_annotations/line_with_text.py @@ -62,7 +62,7 @@ def draw(self, renderer): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/mathtext_asarray.py b/examples/text_labels_and_annotations/mathtext_asarray.py index 224634046c68..a90421b86760 100644 --- a/examples/text_labels_and_annotations/mathtext_asarray.py +++ b/examples/text_labels_and_annotations/mathtext_asarray.py @@ -46,7 +46,7 @@ def text_to_rgba(s, *, dpi, **kwargs): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/tex_demo.py b/examples/text_labels_and_annotations/tex_demo.py index 830058daf370..44dbad90948b 100644 --- a/examples/text_labels_and_annotations/tex_demo.py +++ b/examples/text_labels_and_annotations/tex_demo.py @@ -30,7 +30,7 @@ ax.set_title(r'\TeX\ is Number $\displaystyle\sum_{n=1}^\infty' r'\frac{-e^{i\pi}}{2^n}$!', fontsize=16, color='r') -############################################################################# +# %% # A more complex example. fig, ax = plt.subplots() diff --git a/examples/text_labels_and_annotations/text_alignment.py b/examples/text_labels_and_annotations/text_alignment.py index a748481d5261..7ad0d07c6572 100644 --- a/examples/text_labels_and_annotations/text_alignment.py +++ b/examples/text_labels_and_annotations/text_alignment.py @@ -42,7 +42,7 @@ """ -############################################################################# +# %% # The following plot uses this to align text relative to a plotted rectangle. import matplotlib.pyplot as plt diff --git a/examples/text_labels_and_annotations/text_commands.py b/examples/text_labels_and_annotations/text_commands.py index cb6d5413f8d4..35f2c1c1a0c4 100644 --- a/examples/text_labels_and_annotations/text_commands.py +++ b/examples/text_labels_and_annotations/text_commands.py @@ -41,7 +41,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/text_labels_and_annotations/titles_demo.py b/examples/text_labels_and_annotations/titles_demo.py index 57323aac38e3..b9be1a691c07 100644 --- a/examples/text_labels_and_annotations/titles_demo.py +++ b/examples/text_labels_and_annotations/titles_demo.py @@ -17,7 +17,7 @@ plt.show() -########################################################################### +# %% # The vertical position is automatically chosen to avoid decorations # (i.e. labels and ticks) on the topmost x-axis: @@ -37,7 +37,7 @@ ax.set_title('Center Title') plt.show() -########################################################################### +# %% # Automatic positioning can be turned off by manually specifying the *y* # keyword argument for the title or setting :rc:`axes.titley` in the rcParams. diff --git a/examples/text_labels_and_annotations/watermark_text.py b/examples/text_labels_and_annotations/watermark_text.py index 200a3c8dac15..568a2b39f57a 100644 --- a/examples/text_labels_and_annotations/watermark_text.py +++ b/examples/text_labels_and_annotations/watermark_text.py @@ -22,7 +22,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/ticks/auto_ticks.py b/examples/ticks/auto_ticks.py index 3ceaf415645b..93f501b517d5 100644 --- a/examples/ticks/auto_ticks.py +++ b/examples/ticks/auto_ticks.py @@ -23,7 +23,7 @@ ax.scatter(x, y, c=x+y) plt.show() -############################################################################### +# %% # If you want to keep ticks at round numbers, and also have ticks at the edges # you can switch :rc:`axes.autolimit_mode` to 'round_numbers'. This expands the # axis limits to the next round number. @@ -38,7 +38,7 @@ ax.scatter(x, y, c=x+y) plt.show() -############################################################################### +# %% # The round numbers autolimit_mode is still respected if you set an additional # margin around the data using `.Axes.set_xmargin` / `.Axes.set_ymargin`: diff --git a/examples/ticks/colorbar_tick_labelling_demo.py b/examples/ticks/colorbar_tick_labelling_demo.py index b0d56943fe30..9c3c375510d1 100644 --- a/examples/ticks/colorbar_tick_labelling_demo.py +++ b/examples/ticks/colorbar_tick_labelling_demo.py @@ -17,7 +17,7 @@ # Fixing random state for reproducibility np.random.seed(19680801) -############################################################################### +# %% # Make plot with vertical (default) colorbar fig, ax = plt.subplots() @@ -31,7 +31,7 @@ cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) cbar.ax.set_yticklabels(['< -1', '0', '> 1']) # vertically oriented colorbar -############################################################################### +# %% # Make plot with horizontal colorbar fig, ax = plt.subplots() diff --git a/examples/ticks/custom_ticker1.py b/examples/ticks/custom_ticker1.py index 53b6c32e0789..2e6a86a8fc1c 100644 --- a/examples/ticks/custom_ticker1.py +++ b/examples/ticks/custom_ticker1.py @@ -25,7 +25,7 @@ def millions(x, pos): ax.bar(['Bill', 'Fred', 'Mary', 'Sue'], money) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/ticks/date_concise_formatter.py b/examples/ticks/date_concise_formatter.py index 979214b3b406..8b61fb13874b 100644 --- a/examples/ticks/date_concise_formatter.py +++ b/examples/ticks/date_concise_formatter.py @@ -20,7 +20,7 @@ import matplotlib.dates as mdates import numpy as np -############################################################################# +# %% # First, the default formatter. base = datetime.datetime(2005, 2, 1) @@ -43,7 +43,7 @@ axs[0].set_title('Default Date Formatter') plt.show() -############################################################################# +# %% # The default date formatter is quite verbose, so we have the option of # using `~.dates.ConciseDateFormatter`, as shown below. Note that # for this example the labels do not need to be rotated as they do for the @@ -62,7 +62,7 @@ plt.show() -############################################################################# +# %% # If all calls to axes that have dates are to be made using this converter, # it is probably most convenient to use the units registry where you do # imports: @@ -81,7 +81,7 @@ plt.show() -############################################################################# +# %% # Localization of date formats # ============================ # @@ -138,7 +138,7 @@ plt.show() -############################################################################# +# %% # Registering a converter with localization # ========================================= # diff --git a/examples/ticks/date_formatters_locators.py b/examples/ticks/date_formatters_locators.py index 9d765c238470..2adad036a034 100644 --- a/examples/ticks/date_formatters_locators.py +++ b/examples/ticks/date_formatters_locators.py @@ -69,7 +69,7 @@ def plot_axis(ax, locator=None, xmax='2002-02-01', fmt=None, formatter=None): plot_axis(ax[i], formatter=fmt) -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/ticks/date_index_formatter.py b/examples/ticks/date_index_formatter.py index a2bf4b8796f9..4eb9556f1cdf 100644 --- a/examples/ticks/date_index_formatter.py +++ b/examples/ticks/date_index_formatter.py @@ -62,7 +62,7 @@ def format_date(x, _): ax2.set_title("Plot y at Index Coordinates Using Custom Formatter") ax2.xaxis.set_major_formatter(format_date) # internally creates FuncFormatter -############################################################################# +# %% # Instead of passing a function into `.Axis.set_major_formatter` you can use # any other callable, e.g. an instance of a class that implements __call__: diff --git a/examples/ticks/date_precision_and_epochs.py b/examples/ticks/date_precision_and_epochs.py index c50bbd234331..8afe86af92c0 100644 --- a/examples/ticks/date_precision_and_epochs.py +++ b/examples/ticks/date_precision_and_epochs.py @@ -32,7 +32,7 @@ def _reset_epoch_for_tutorial(): mdates._reset_epoch_test_example() -############################################################################# +# %% # Datetime # -------- # @@ -53,7 +53,7 @@ def _reset_epoch_for_tutorial(): date2 = mdates.num2date(mdate1) print('After Roundtrip: ', date2) -############################################################################# +# %% # Note this is only a round-off error, and there is no problem for # dates closer to the old epoch: @@ -64,7 +64,7 @@ def _reset_epoch_for_tutorial(): date2 = mdates.num2date(mdate1) print('After Roundtrip: ', date2) -############################################################################# +# %% # If a user wants to use modern dates at microsecond precision, they # can change the epoch using `.set_epoch`. However, the epoch has to be # set before any date operations to prevent confusion between different @@ -75,7 +75,7 @@ def _reset_epoch_for_tutorial(): except RuntimeError as e: print('RuntimeError:', str(e)) -############################################################################# +# %% # For this tutorial, we reset the sentinel using a private method, but users # should just set the epoch once, if at all. @@ -89,7 +89,7 @@ def _reset_epoch_for_tutorial(): date2 = mdates.num2date(mdate1) print('After Roundtrip: ', date2) -############################################################################# +# %% # datetime64 # ---------- # @@ -107,7 +107,7 @@ def _reset_epoch_for_tutorial(): date2 = mdates.num2date(mdate1) print('After Roundtrip: ', date2) -############################################################################# +# %% # Plotting # -------- # @@ -134,7 +134,7 @@ def _reset_epoch_for_tutorial(): ax.xaxis.set_tick_params(rotation=40) plt.show() -############################################################################# +# %% # For dates plotted using the more recent epoch, the plot is smooth: fig, ax = plt.subplots(constrained_layout=True) @@ -145,7 +145,7 @@ def _reset_epoch_for_tutorial(): _reset_epoch_for_tutorial() # Don't do this. Just for this tutorial. -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/ticks/dollar_ticks.py b/examples/ticks/dollar_ticks.py index b8fe95e7acd1..21cb26928caa 100644 --- a/examples/ticks/dollar_ticks.py +++ b/examples/ticks/dollar_ticks.py @@ -25,7 +25,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/ticks/fig_axes_customize_simple.py b/examples/ticks/fig_axes_customize_simple.py index 74742f718939..510ec8e77b6a 100644 --- a/examples/ticks/fig_axes_customize_simple.py +++ b/examples/ticks/fig_axes_customize_simple.py @@ -10,7 +10,7 @@ import matplotlib.pyplot as plt -############################################################################### +# %% # `.pyplot.figure` creates a `matplotlib.figure.Figure` instance. fig = plt.figure() @@ -26,7 +26,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/ticks/major_minor_demo.py b/examples/ticks/major_minor_demo.py index c139ff4741e4..c5234225b796 100644 --- a/examples/ticks/major_minor_demo.py +++ b/examples/ticks/major_minor_demo.py @@ -54,7 +54,7 @@ plt.show() -############################################################################### +# %% # Automatic tick selection for major and minor ticks. # # Use interactive pan and zoom to see how the tick intervals change. There will @@ -80,7 +80,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/ticks/scalarformatter.py b/examples/ticks/scalarformatter.py index 061076ef630e..7dfae026c038 100644 --- a/examples/ticks/scalarformatter.py +++ b/examples/ticks/scalarformatter.py @@ -16,7 +16,7 @@ import matplotlib.pyplot as plt import numpy as np -############################################################################### +# %% # Example 1 x = np.arange(0, 1, .01) @@ -35,7 +35,7 @@ fig.subplots_adjust(wspace=0.7, hspace=0.6) -############################################################################### +# %% # Example 2 x = np.arange(0, 1, .01) @@ -58,7 +58,7 @@ fig.subplots_adjust(wspace=0.7, hspace=0.6) -############################################################################### +# %% # Example 3 x = np.arange(0, 1, .01) diff --git a/examples/ticks/tick-formatters.py b/examples/ticks/tick-formatters.py index 0f5c8f38d411..e0a4005ee93b 100644 --- a/examples/ticks/tick-formatters.py +++ b/examples/ticks/tick-formatters.py @@ -33,7 +33,7 @@ def setup(ax, title): fontsize=14, fontname='Monospace', color='tab:blue') -############################################################################# +# %% # Tick formatters can be set in one of two ways, either by passing a ``str`` # or function to `~.Axis.set_major_formatter` or `~.Axis.set_minor_formatter`, # or by creating an instance of one of the various `~.ticker.Formatter` classes @@ -60,7 +60,7 @@ def setup(ax, title): fig0.tight_layout() -############################################################################# +# %% # The remaining examples use `.Formatter` objects. fig1, axs1 = plt.subplots(7, 1, figsize=(8, 6)) @@ -109,7 +109,7 @@ def major_formatter(x, pos): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/ticks/tick_labels_from_values.py b/examples/ticks/tick_labels_from_values.py index e03a2be87198..247fc817eace 100644 --- a/examples/ticks/tick_labels_from_values.py +++ b/examples/ticks/tick_labels_from_values.py @@ -39,7 +39,7 @@ def format_fn(tick_val, tick_pos): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/ticks/ticks_too_many.py b/examples/ticks/ticks_too_many.py index c1f05bf4c17e..11b6ed8d4707 100644 --- a/examples/ticks/ticks_too_many.py +++ b/examples/ticks/ticks_too_many.py @@ -14,7 +14,7 @@ """ -############################################################################ +# %% # Example 1: Strings can lead to an unexpected order of number ticks # ------------------------------------------------------------------ @@ -35,7 +35,7 @@ ax[1].set_xlabel('Floats') ax[1].set_title('Ticks as expected') -############################################################################ +# %% # Example 2: Strings can lead to very many ticks # ---------------------------------------------- # If *x* has 100 elements, all strings, then we would have 100 (unreadable) @@ -53,7 +53,7 @@ ax[1].set_title('x converted to numbers') ax[1].set_xlabel('Floats') -############################################################################ +# %% # Example 3: Strings can lead to an unexpected order of datetime ticks # -------------------------------------------------------------------- # A common case is when dates are read from a CSV file, they need to be diff --git a/examples/units/ellipse_with_units.py b/examples/units/ellipse_with_units.py index 369ad5cf4e68..86ac6cebf8ee 100644 --- a/examples/units/ellipse_with_units.py +++ b/examples/units/ellipse_with_units.py @@ -35,7 +35,7 @@ x += xcenter y += ycenter -############################################################################### +# %% fig = plt.figure() ax = fig.add_subplot(211, aspect='auto') @@ -56,7 +56,7 @@ ax.add_patch(e2) fig.savefig('ellipse_compare') -############################################################################### +# %% fig = plt.figure() ax = fig.add_subplot(211, aspect='auto') diff --git a/examples/user_interfaces/canvasagg.py b/examples/user_interfaces/canvasagg.py index afb1c3acbf7f..b72d9bc1ee6e 100644 --- a/examples/user_interfaces/canvasagg.py +++ b/examples/user_interfaces/canvasagg.py @@ -56,7 +56,7 @@ # Uncomment this line to display the image using ImageMagick's `display` tool. # im.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/user_interfaces/web_application_server_sgskip.py b/examples/user_interfaces/web_application_server_sgskip.py index c430c24b70ed..30196d419317 100644 --- a/examples/user_interfaces/web_application_server_sgskip.py +++ b/examples/user_interfaces/web_application_server_sgskip.py @@ -41,7 +41,7 @@ def hello(): data = base64.b64encode(buf.getbuffer()).decode("ascii") return f"" -############################################################################# +# %% # # Since the above code is a Flask application, it should be run using the # `flask command-line tool `_ diff --git a/examples/userdemo/connectionstyle_demo.py b/examples/userdemo/connectionstyle_demo.py index f9def1d94f24..966283331e94 100644 --- a/examples/userdemo/connectionstyle_demo.py +++ b/examples/userdemo/connectionstyle_demo.py @@ -52,7 +52,7 @@ def demo_con_style(ax, connectionstyle): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/userdemo/custom_boxstyle01.py b/examples/userdemo/custom_boxstyle01.py index 5ca0a21b59fb..54fc19b16fef 100644 --- a/examples/userdemo/custom_boxstyle01.py +++ b/examples/userdemo/custom_boxstyle01.py @@ -12,7 +12,7 @@ import matplotlib.pyplot as plt -############################################################################### +# %% # Custom box styles can be implemented as a function that takes arguments # specifying both a rectangular box and the amount of "mutation", and # returns the "mutated" path. The specific signature is the one of @@ -61,7 +61,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): bbox=dict(boxstyle=custom_box_style, alpha=0.2)) -############################################################################### +# %% # Likewise, custom box styles can be implemented as classes that implement # ``__call__``. # diff --git a/examples/userdemo/demo_gridspec03.py b/examples/userdemo/demo_gridspec03.py index 55f424a808f8..368576d85b59 100644 --- a/examples/userdemo/demo_gridspec03.py +++ b/examples/userdemo/demo_gridspec03.py @@ -31,7 +31,7 @@ def annotate_axes(fig): annotate_axes(fig) -############################################################################# +# %% fig = plt.figure() fig.suptitle("Controlling spacing around and between subplots") diff --git a/examples/widgets/annotated_cursor.py b/examples/widgets/annotated_cursor.py index 3601a37fe54a..eabec859fecb 100644 --- a/examples/widgets/annotated_cursor.py +++ b/examples/widgets/annotated_cursor.py @@ -314,7 +314,7 @@ def _update(self): plt.show() -############################################################################### +# %% # Trouble with non-biunique functions # ----------------------------------- # A call demonstrating problems with the *dataaxis=y* parameter. diff --git a/examples/widgets/buttons.py b/examples/widgets/buttons.py index 24331a4acd00..8ea5deb1870e 100644 --- a/examples/widgets/buttons.py +++ b/examples/widgets/buttons.py @@ -49,7 +49,7 @@ def prev(self, event): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/check_buttons.py b/examples/widgets/check_buttons.py index 493ac4c3e79a..d5894fdad705 100644 --- a/examples/widgets/check_buttons.py +++ b/examples/widgets/check_buttons.py @@ -45,7 +45,7 @@ def callback(label): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/cursor.py b/examples/widgets/cursor.py index 151a8dd08d4c..eb78d152206f 100644 --- a/examples/widgets/cursor.py +++ b/examples/widgets/cursor.py @@ -24,7 +24,7 @@ plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/lasso_selector_demo_sgskip.py b/examples/widgets/lasso_selector_demo_sgskip.py index f1b84316595e..df4c95dde4f4 100644 --- a/examples/widgets/lasso_selector_demo_sgskip.py +++ b/examples/widgets/lasso_selector_demo_sgskip.py @@ -100,7 +100,7 @@ def accept(event): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/mouse_cursor.py b/examples/widgets/mouse_cursor.py index 1b0a1b2c57c3..573fa7da834c 100644 --- a/examples/widgets/mouse_cursor.py +++ b/examples/widgets/mouse_cursor.py @@ -36,7 +36,7 @@ def hover(event): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/multicursor.py b/examples/widgets/multicursor.py index 618fa17c5ad6..a8bb8a1e35a4 100644 --- a/examples/widgets/multicursor.py +++ b/examples/widgets/multicursor.py @@ -28,7 +28,7 @@ multi = MultiCursor(None, (ax1, ax2, ax3), color='r', lw=1) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/polygon_selector_demo.py b/examples/widgets/polygon_selector_demo.py index da9e65c39268..f1161c287afc 100644 --- a/examples/widgets/polygon_selector_demo.py +++ b/examples/widgets/polygon_selector_demo.py @@ -92,7 +92,7 @@ def disconnect(self): print('\nSelected points:') print(selector.xys[selector.ind]) -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/polygon_selector_simple.py b/examples/widgets/polygon_selector_simple.py index cdc84b07eaf6..17fe0d17e60c 100644 --- a/examples/widgets/polygon_selector_simple.py +++ b/examples/widgets/polygon_selector_simple.py @@ -9,7 +9,7 @@ import matplotlib.pyplot as plt from matplotlib.widgets import PolygonSelector -############################################################################### +# %% # # To create the polygon programmatically fig, ax = plt.subplots() @@ -21,7 +21,7 @@ selector.verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)] -############################################################################### +# %% # # To create the polygon interactively @@ -36,7 +36,7 @@ print("Try holding the 'ctrl' key to move a single vertex.") -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/radio_buttons.py b/examples/widgets/radio_buttons.py index 28e446fc5b80..c1600b369be7 100644 --- a/examples/widgets/radio_buttons.py +++ b/examples/widgets/radio_buttons.py @@ -55,7 +55,7 @@ def stylefunc(label): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/range_slider.py b/examples/widgets/range_slider.py index bdb69fa80859..6a1c38400acb 100644 --- a/examples/widgets/range_slider.py +++ b/examples/widgets/range_slider.py @@ -60,7 +60,7 @@ def update(val): slider.on_changed(update) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/rectangle_selector.py b/examples/widgets/rectangle_selector.py index 8ede9ad66fc4..ad03ed76ec6e 100644 --- a/examples/widgets/rectangle_selector.py +++ b/examples/widgets/rectangle_selector.py @@ -62,7 +62,7 @@ def toggle_selector(event): + axs[0].get_title()) plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/slider_demo.py b/examples/widgets/slider_demo.py index 6f849645f9bf..db7dad8e362e 100644 --- a/examples/widgets/slider_demo.py +++ b/examples/widgets/slider_demo.py @@ -80,7 +80,7 @@ def reset(event): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/slider_snap_demo.py b/examples/widgets/slider_snap_demo.py index 5ace232c12c5..98188c9e6aea 100644 --- a/examples/widgets/slider_snap_demo.py +++ b/examples/widgets/slider_snap_demo.py @@ -71,7 +71,7 @@ def reset(event): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/span_selector.py b/examples/widgets/span_selector.py index fa75a70d2863..aea00095ebea 100644 --- a/examples/widgets/span_selector.py +++ b/examples/widgets/span_selector.py @@ -63,7 +63,7 @@ def onselect(xmin, xmax): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/examples/widgets/textbox.py b/examples/widgets/textbox.py index 33a996ae73c2..1cd926e5f160 100644 --- a/examples/widgets/textbox.py +++ b/examples/widgets/textbox.py @@ -46,7 +46,7 @@ def submit(expression): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/tutorials/advanced/blitting.py b/tutorials/advanced/blitting.py index 54aeddecc6ef..d0a939d18541 100644 --- a/tutorials/advanced/blitting.py +++ b/tutorials/advanced/blitting.py @@ -100,7 +100,7 @@ # you can put a pause in if you want to slow things down # plt.pause(.1) -############################################################################### +# %% # This example works and shows a simple animation, however because we # are only grabbing the background once, if the size of the figure in # pixels changes (due to either the size or dpi of the figure @@ -192,7 +192,7 @@ def update(self): cv.flush_events() -############################################################################### +# %% # Here is how we would use our class. This is a slightly more complicated # example than the first case as we add a text frame counter as well. @@ -223,6 +223,6 @@ def update(self): # tell the blitting manager to do its thing bm.update() -############################################################################### +# %% # This class does not depend on `.pyplot` and is suitable to embed # into larger GUI application. diff --git a/tutorials/advanced/path_tutorial.py b/tutorials/advanced/path_tutorial.py index caf5f04b5a1e..3cdddb76c094 100644 --- a/tutorials/advanced/path_tutorial.py +++ b/tutorials/advanced/path_tutorial.py @@ -44,7 +44,7 @@ plt.show() -############################################################################### +# %% # The following path codes are recognized # # ============= ======================== ====================================== @@ -116,7 +116,7 @@ ax.set_ylim(-0.1, 1.1) plt.show() -############################################################################### +# %% # .. compound_paths: # # Compound paths diff --git a/tutorials/advanced/patheffects_guide.py b/tutorials/advanced/patheffects_guide.py index 85e214c97b5c..1d89ab6dd6f0 100644 --- a/tutorials/advanced/patheffects_guide.py +++ b/tutorials/advanced/patheffects_guide.py @@ -29,7 +29,7 @@ text.set_path_effects([path_effects.Normal()]) plt.show() -############################################################################### +# %% # Whilst the plot doesn't look any different to what you would expect without # any path effects, the drawing of the text has now been changed to use the # path effects framework, opening up the possibilities for more interesting @@ -53,7 +53,7 @@ path_effects.Normal()]) plt.show() -############################################################################### +# %% # Notice the two approaches to setting the path effects in this example. The # first uses the ``with*`` classes to include the desired functionality # automatically followed with the "normal" effect, whereas the latter @@ -74,7 +74,7 @@ path_effects.Normal()]) plt.show() -############################################################################### +# %% # It is important to note that this effect only works because we have drawn # the text path twice; once with a thick black line, and then once with the # original text path on top. @@ -107,7 +107,7 @@ edgecolor='white', linewidth=1.1, facecolor='black')]) plt.show() -############################################################################### +# %% # .. # Headings for future consideration: # diff --git a/tutorials/advanced/transforms_tutorial.py b/tutorials/advanced/transforms_tutorial.py index 26b936ef5b95..3d510d774c0b 100644 --- a/tutorials/advanced/transforms_tutorial.py +++ b/tutorials/advanced/transforms_tutorial.py @@ -126,7 +126,7 @@ plt.show() -############################################################################### +# %% # You can use the ``ax.transData`` instance to transform from your # *data* to your *display* coordinate system, either a single point or a # sequence of points as shown below: @@ -196,7 +196,7 @@ plt.show() -############################################################################### +# %% # .. warning:: # # If you run the source code in the example above in a GUI backend, @@ -259,7 +259,7 @@ plt.show() -############################################################################### +# %% # You can also make lines or patches in the *axes* coordinate system, but # this is less useful in my experience than using ``ax.transAxes`` for # placing text. Nonetheless, here is a silly example which plots some @@ -281,7 +281,7 @@ ax.add_patch(circ) plt.show() -############################################################################### +# %% # .. _blended_transformations: # # Blended transformations @@ -322,7 +322,7 @@ plt.show() -############################################################################### +# %% # .. note:: # # The blended transformations where x is in *data* coords and y in *axes* @@ -357,7 +357,7 @@ ax.add_patch(circ) plt.show() -############################################################################### +# %% # If we change the figure size, the circle does not change its absolute # position and is cropped. @@ -370,7 +370,7 @@ ax.add_patch(circ) plt.show() -############################################################################### +# %% # Another use is putting a patch with a set physical dimension around a # data point on the axes. Here we add together two transforms. The # first sets the scaling of how large the ellipse should be and the second @@ -409,7 +409,7 @@ ax.add_patch(circle) plt.show() -############################################################################### +# %% # .. note:: # # The order of transformation matters. Here the ellipse @@ -470,7 +470,7 @@ plt.show() -############################################################################### +# %% # .. note:: # # The dpi and inches offset is a diff --git a/tutorials/colors/colorbar_only.py b/tutorials/colors/colorbar_only.py index ce48ec50c26b..a4361fb94e3d 100644 --- a/tutorials/colors/colorbar_only.py +++ b/tutorials/colors/colorbar_only.py @@ -39,7 +39,7 @@ cax=ax, orientation='horizontal', label='Some Units') -############################################################################### +# %% # Extended colorbar with continuous colorscale # -------------------------------------------- # @@ -57,7 +57,7 @@ cax=ax, orientation='horizontal', label="Discrete intervals with extend='both' keyword") -############################################################################### +# %% # Discrete intervals colorbar # --------------------------- # @@ -100,7 +100,7 @@ label='Discrete intervals, some other units', ) -############################################################################### +# %% # Colorbar with custom extension lengths # -------------------------------------- # diff --git a/tutorials/colors/colormap-manipulation.py b/tutorials/colors/colormap-manipulation.py index 8b2cbc784bc0..ee2a05f0e474 100644 --- a/tutorials/colors/colormap-manipulation.py +++ b/tutorials/colors/colormap-manipulation.py @@ -38,13 +38,13 @@ viridis = mpl.colormaps['viridis'].resampled(8) -############################################################################## +# %% # The object ``viridis`` is a callable, that when passed a float between # 0 and 1 returns an RGBA value from the colormap: print(viridis(0.56)) -############################################################################## +# %% # ListedColormap # -------------- # @@ -59,13 +59,13 @@ print('viridis(range(8))', viridis(range(8))) print('viridis(np.linspace(0, 1, 8))', viridis(np.linspace(0, 1, 8))) -############################################################################## +# %% # The colormap is a lookup table, so "oversampling" the colormap returns # nearest-neighbor interpolation (note the repeated colors in the list below) print('viridis(np.linspace(0, 1, 12))', viridis(np.linspace(0, 1, 12))) -############################################################################## +# %% # LinearSegmentedColormap # ----------------------- # `.LinearSegmentedColormap`\s do not have a ``.colors`` attribute. @@ -77,7 +77,7 @@ print('copper(range(8))', copper(range(8))) print('copper(np.linspace(0, 1, 8))', copper(np.linspace(0, 1, 8))) -############################################################################## +# %% # Creating listed colormaps # ========================= # @@ -105,14 +105,14 @@ def plot_examples(colormaps): plt.show() -############################################################################## +# %% # In the simplest case we might type in a list of color names to create a # colormap from those. cmap = ListedColormap(["darkorange", "gold", "lawngreen", "lightseagreen"]) plot_examples([cmap]) -############################################################################## +# %% # In fact, that list may contain any valid # :doc:`Matplotlib color specification `. # Particularly useful for creating custom colormaps are Nx4 numpy arrays. @@ -131,7 +131,7 @@ def plot_examples(colormaps): plot_examples([viridis, newcmp]) -############################################################################## +# %% # We can reduce the dynamic range of a colormap; here we choose the # middle half of the colormap. Note, however, that because viridis is a # listed colormap, we will end up with 128 discrete values instead of the 256 @@ -142,7 +142,7 @@ def plot_examples(colormaps): newcmp = ListedColormap(viridis_big(np.linspace(0.25, 0.75, 128))) plot_examples([viridis, newcmp]) -############################################################################## +# %% # and we can easily concatenate two colormaps: top = mpl.colormaps['Oranges_r'].resampled(128) @@ -153,7 +153,7 @@ def plot_examples(colormaps): newcmp = ListedColormap(newcolors, name='OrangeBlue') plot_examples([viridis, newcmp]) -############################################################################## +# %% # Of course we need not start from a named colormap, we just need to create # the Nx4 array to pass to `.ListedColormap`. Here we create a colormap that # goes from brown (RGB: 90, 40, 40) to white (RGB: 255, 255, 255). @@ -166,7 +166,7 @@ def plot_examples(colormaps): newcmp = ListedColormap(vals) plot_examples([viridis, newcmp]) -############################################################################## +# %% # Creating linear segmented colormaps # =================================== # @@ -208,7 +208,7 @@ def plot_linearmap(cdict): plot_linearmap(cdict) -############################################################################# +# %% # In order to make a discontinuity at an anchor point, the third column is # different than the second. The matrix for each of "red", "green", "blue", # and optionally "alpha" is set up as:: @@ -233,7 +233,7 @@ def plot_linearmap(cdict): [1.0, 1.0, 1.0]] plot_linearmap(cdict) -############################################################################# +# %% # Directly creating a segmented colormap from a list # -------------------------------------------------- # @@ -245,7 +245,7 @@ def plot_linearmap(cdict): colors = ["darkorange", "gold", "lawngreen", "lightseagreen"] cmap1 = LinearSegmentedColormap.from_list("mycmap", colors) -############################################################################# +# %% # If desired, the nodes of the colormap can be given as numbers between 0 and # 1. For example, one could have the reddish part take more space in the # colormap. @@ -255,7 +255,7 @@ def plot_linearmap(cdict): plot_examples([cmap1, cmap2]) -############################################################################# +# %% # .. _reversing-colormap: # # Reversing a colormap @@ -275,7 +275,7 @@ def plot_linearmap(cdict): # :ref:`appending '_r' ` to the original colormap's # name. -############################################################################## +# %% # .. _registering-colormap: # # Registering a colormap @@ -297,7 +297,7 @@ def plot_linearmap(cdict): plt.show() -############################################################################# +# %% # # .. admonition:: References # diff --git a/tutorials/colors/colormapnorms.py b/tutorials/colors/colormapnorms.py index e7ca0e61bfc7..d6fa41c98a1b 100644 --- a/tutorials/colors/colormapnorms.py +++ b/tutorials/colors/colormapnorms.py @@ -68,7 +68,7 @@ fig.colorbar(pcm, ax=ax[1], extend='max') plt.show() -############################################################################### +# %% # Centered # -------- # @@ -108,7 +108,7 @@ plt.show() -############################################################################### +# %% # Symmetric logarithmic # --------------------- # @@ -145,7 +145,7 @@ fig.colorbar(pcm, ax=ax[1], extend='both') plt.show() -############################################################################### +# %% # Power-law # --------- # @@ -179,7 +179,7 @@ ax[1].set_title('Normalize()') plt.show() -############################################################################### +# %% # Discrete bounds # --------------- # @@ -237,7 +237,7 @@ ax[3].set_title('BoundaryNorm: extend="both"') plt.show() -############################################################################### +# %% # TwoSlopeNorm: Different mapping on either side of a center # ---------------------------------------------------------- # @@ -277,7 +277,7 @@ plt.show() -############################################################################### +# %% # FuncNorm: Arbitrary function normalization # ------------------------------------------ # @@ -303,7 +303,7 @@ def _inverse(x): fig.colorbar(pcm, shrink=0.6) plt.show() -############################################################################### +# %% # Custom normalization: Manually implement two linear ranges # ---------------------------------------------------------- # diff --git a/tutorials/colors/colormaps.py b/tutorials/colors/colormaps.py index 68862d834f68..46f89100f818 100644 --- a/tutorials/colors/colormaps.py +++ b/tutorials/colors/colormaps.py @@ -83,7 +83,7 @@ from colorspacious import cspace_converter -############################################################################### +# %% # # First, we'll show the range of each colormap. Note that some seem # to change more "quickly" than others. @@ -116,7 +116,7 @@ def plot_color_gradients(category, cmap_list): cmaps[category] = cmap_list -############################################################################### +# %% # Sequential # ---------- # @@ -131,14 +131,14 @@ def plot_color_gradients(category, cmap_list): plot_color_gradients('Perceptually Uniform Sequential', ['viridis', 'plasma', 'inferno', 'magma', 'cividis']) -############################################################################### +# %% plot_color_gradients('Sequential', ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds', 'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu', 'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']) -############################################################################### +# %% # Sequential2 # ----------- # @@ -155,7 +155,7 @@ def plot_color_gradients(category, cmap_list): 'pink', 'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia', 'hot', 'afmhot', 'gist_heat', 'copper']) -############################################################################### +# %% # Diverging # --------- # @@ -170,7 +170,7 @@ def plot_color_gradients(category, cmap_list): ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic']) -############################################################################### +# %% # Cyclic # ------ # @@ -190,7 +190,7 @@ def plot_color_gradients(category, cmap_list): plot_color_gradients('Cyclic', ['twilight', 'twilight_shifted', 'hsv']) -############################################################################### +# %% # Qualitative # ----------- # @@ -204,7 +204,7 @@ def plot_color_gradients(category, cmap_list): 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c']) -############################################################################### +# %% # Miscellaneous # ------------- # @@ -233,7 +233,7 @@ def plot_color_gradients(category, cmap_list): plt.show() -############################################################################### +# %% # Lightness of Matplotlib colormaps # ================================= # @@ -325,7 +325,7 @@ def plot_color_gradients(category, cmap_list): plt.show() -############################################################################### +# %% # Grayscale conversion # ==================== # @@ -404,7 +404,7 @@ def plot_color_gradients(cmap_category, cmap_list): plot_color_gradients(cmap_category, cmap_list) -############################################################################### +# %% # Color vision deficiencies # ========================= # diff --git a/tutorials/colors/colors.py b/tutorials/colors/colors.py index 224886c20483..b3f8e87beaac 100644 --- a/tutorials/colors/colors.py +++ b/tutorials/colors/colors.py @@ -113,7 +113,7 @@ ax.axis('off') -############################################################################### +# %% # # The orange rectangle is semi-transparent with *alpha* = 0.8. The top row of # blue squares is drawn below and the bottom row of blue squares is drawn on @@ -151,7 +151,7 @@ def demo(sty): demo('default') demo('seaborn-v0_8') -############################################################################### +# %% # The first color ``'C0'`` is the title. Each plot uses the second and third # colors of each style's :rc:`axes.prop_cycle`. They are ``'C1'`` and ``'C2'``, # respectively. diff --git a/tutorials/intermediate/arranging_axes.py b/tutorials/intermediate/arranging_axes.py index 3fbfb7b6e239..ed07de20dc7e 100644 --- a/tutorials/intermediate/arranging_axes.py +++ b/tutorials/intermediate/arranging_axes.py @@ -83,7 +83,7 @@ .. redirect-from:: /tutorials/intermediate/gridspec """ -############################################################################ +# %% # High-level methods for making grids # =================================== # @@ -111,7 +111,7 @@ color='darkgrey') fig.suptitle('plt.subplots()') -############################################################################## +# %% # We will annotate a lot of Axes, so let's encapsulate the annotation, rather # than having that large piece of annotation code every time we need it: @@ -121,7 +121,7 @@ def annotate_axes(ax, text, fontsize=18): ha="center", va="center", fontsize=fontsize, color="darkgrey") -############################################################################## +# %% # The same effect can be achieved with `~.pyplot.subplot_mosaic`, # but the return type is a dictionary instead of an array, where the user # can give the keys useful meanings. Here we provide two lists, each list @@ -135,7 +135,7 @@ def annotate_axes(ax, text, fontsize=18): annotate_axes(axd[k], f'axd["{k}"]', fontsize=14) fig.suptitle('plt.subplot_mosaic()') -############################################################################# +# %% # # Grids of fixed-aspect ratio Axes # -------------------------------- @@ -151,7 +151,7 @@ def annotate_axes(ax, text, fontsize=18): ax.set_aspect(1) fig.suptitle('Fixed aspect Axes') -############################################################################ +# %% # One way to address this is to change the aspect of the figure to be close # to the aspect ratio of the Axes, however that requires trial and error. # Matplotlib also supplies ``layout="compressed"``, which will work with @@ -165,7 +165,7 @@ def annotate_axes(ax, text, fontsize=18): fig.suptitle('Fixed aspect Axes: compressed') -############################################################################ +# %% # Axes spanning rows or columns in a grid # --------------------------------------- # @@ -181,7 +181,7 @@ def annotate_axes(ax, text, fontsize=18): annotate_axes(axd[k], f'axd["{k}"]', fontsize=14) fig.suptitle('plt.subplot_mosaic()') -############################################################################ +# %% # See below for the description of how to do the same thing using # `~matplotlib.gridspec.GridSpec` or `~matplotlib.pyplot.subplot2grid`. # @@ -204,7 +204,7 @@ def annotate_axes(ax, text, fontsize=18): annotate_axes(axd[k], f'axd["{k}"]', fontsize=14) fig.suptitle('plt.subplot_mosaic()') -############################################################################ +# %% # Nested Axes layouts # ------------------- # @@ -226,7 +226,7 @@ def annotate_axes(ax, text, fontsize=18): subfigs[1].suptitle('subfigs[1]') subfigs[1].supylabel('ylabel for subfigs[1]') -############################################################################ +# %% # It is also possible to nest Axes using `~.pyplot.subplot_mosaic` using # nested lists. This method does not use subfigures, like above, so lacks # the ability to add per-subfigure ``suptitle`` and ``supxlabel``, etc. @@ -242,7 +242,7 @@ def annotate_axes(ax, text, fontsize=18): for k in axd: annotate_axes(axd[k], f'axd["{k}"]') -############################################################################ +# %% # Low-level and advanced grid methods # =================================== # @@ -278,7 +278,7 @@ def annotate_axes(ax, text, fontsize=18): fig.suptitle('Manually added subplots using add_gridspec') -############################################################################## +# %% # Axes spanning rows or grids in a grid # ------------------------------------- # @@ -301,7 +301,7 @@ def annotate_axes(ax, text, fontsize=18): fig.suptitle('Manually added subplots, spanning a column') -############################################################################### +# %% # Manual adjustments to a *GridSpec* layout # ----------------------------------------- # @@ -326,7 +326,7 @@ def annotate_axes(ax, text, fontsize=18): annotate_axes(ax2, 'ax2') fig.suptitle('Manual gridspec with right=0.75') -############################################################################### +# %% # Nested layouts with SubplotSpec # ------------------------------- # @@ -357,7 +357,7 @@ def annotate_axes(ax, text, fontsize=18): fig.suptitle('nested gridspecs') -############################################################################### +# %% # Here's a more sophisticated example of nested *GridSpec*: We create an outer # 4x4 grid with each cell containing an inner 3x3 grid of Axes. We outline # the outer 4x4 grid by hiding appropriate spines in each of the inner 3x3 @@ -389,7 +389,7 @@ def squiggle_xy(a, b, c, d, i=np.arange(0.0, 2*np.pi, 0.05)): plt.show() -############################################################################# +# %% # # More reading # ============ diff --git a/tutorials/intermediate/artists.py b/tutorials/intermediate/artists.py index 1a186ccb4222..91b17105cdcb 100644 --- a/tutorials/intermediate/artists.py +++ b/tutorials/intermediate/artists.py @@ -137,7 +137,7 @@ class in the Matplotlib API, and the one you will be working with most plt.show() -############################################################################### +# %% # .. _customizing-artists: # # Customizing your objects @@ -340,7 +340,7 @@ class in the Matplotlib API, and the one you will be working with most plt.show() -############################################################################### +# %% # Here is a summary of the Artists the Figure contains # # ================ ============================================================ @@ -611,25 +611,25 @@ class in the Matplotlib API, and the one you will be working with most axis = ax.xaxis axis.get_ticklocs() -############################################################################### +# %% axis.get_ticklabels() -############################################################################### +# %% # note there are twice as many ticklines as labels because by default there are # tick lines at the top and bottom but only tick labels below the xaxis; # however, this can be customized. axis.get_ticklines() -############################################################################### +# %% # And with the above methods, you only get lists of major ticks back by # default, but you can also ask for the minor ticks: axis.get_ticklabels(minor=True) axis.get_ticklines(minor=True) -############################################################################### +# %% # Here is a summary of some of the useful accessor methods of the ``Axis`` # (these have corresponding setters where useful, such as # :meth:`~matplotlib.axis.Axis.set_major_formatter`.) @@ -688,7 +688,7 @@ class in the Matplotlib API, and the one you will be working with most plt.show() -############################################################################### +# %% # .. _tick-container: # # Tick containers diff --git a/tutorials/intermediate/autoscale.py b/tutorials/intermediate/autoscale.py index 3b563510aa1f..7bd5667e1769 100644 --- a/tutorials/intermediate/autoscale.py +++ b/tutorials/intermediate/autoscale.py @@ -7,7 +7,7 @@ There are a number of options to this autoscaling behaviour, discussed below. """ -############################################################################### +# %% # We will start with a simple line plot showing that autoscaling # extends the axis limits 5% beyond the data limits (-2π, 2π). @@ -21,21 +21,21 @@ fig, ax = plt.subplots() ax.plot(x, y) -############################################################################### +# %% # Margins # ------- # The default margin around the data limits is 5%: print(ax.margins()) -############################################################################### +# %% # The margins can be made larger using `~matplotlib.axes.Axes.margins`: fig, ax = plt.subplots() ax.plot(x, y) ax.margins(0.2, 0.2) -############################################################################### +# %% # In general, margins can be in the range (-0.5, ∞), where negative margins set # the axes limits to a subrange of the data range, i.e. they clip data. # Using a single number for margins affects both axes, a single margin can be @@ -46,7 +46,7 @@ ax.plot(x, y) ax.margins(y=-0.2) -############################################################################### +# %% # Sticky edges # ------------ # There are plot elements (`.Artist`\s) that are usually used without margins. @@ -64,7 +64,7 @@ ax[1].margins(0.2) ax[1].set_title("margins(0.2)") -############################################################################### +# %% # This override of margins is determined by "sticky edges", a # property of `.Artist` class that can suppress adding margins to axis # limits. The effect of sticky edges can be disabled on an Axes by changing @@ -87,7 +87,7 @@ ax[2].margins(-0.2) ax[2].set_title("default use_sticky_edges\nmargins(-0.2)") -############################################################################### +# %% # We can see that setting ``use_sticky_edges`` to *False* renders the image # with requested margins. # @@ -108,7 +108,7 @@ ax[1].plot(x * 2.0, y) ax[1].set_title("Two curves") -############################################################################### +# %% # However, there are cases when you don't want to automatically adjust the # viewport to new data. # @@ -129,14 +129,14 @@ ax[1].autoscale() ax[1].set_title("set_xlim(left=-1, right=1)\nautoscale()") -############################################################################### +# %% # We can check that the first plot has autoscale disabled and that the second # plot has it enabled again by using `.Axes.get_autoscale_on()`: print(ax[0].get_autoscale_on()) # False means disabled print(ax[1].get_autoscale_on()) # True means enabled -> recalculated -############################################################################### +# %% # Arguments of the autoscale function give us precise control over the process # of autoscaling. A combination of arguments ``enable``, and ``axis`` sets the # autoscaling feature for the selected axis (or both). The argument ``tight`` @@ -152,7 +152,7 @@ print(ax.margins()) -############################################################################### +# %% # Working with collections # ------------------------ # diff --git a/tutorials/intermediate/color_cycle.py b/tutorials/intermediate/color_cycle.py index 16c713f85d22..fd782ae0e111 100644 --- a/tutorials/intermediate/color_cycle.py +++ b/tutorials/intermediate/color_cycle.py @@ -22,18 +22,18 @@ import numpy as np import matplotlib.pyplot as plt -############################################################################### +# %% # First we'll generate some sample data, in this case, four offset sine # curves. x = np.linspace(0, 2 * np.pi, 50) offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False) yy = np.transpose([np.sin(x + phi) for phi in offsets]) -############################################################################### +# %% # Now ``yy`` has shape print(yy.shape) -############################################################################### +# %% # So ``yy[:, i]`` will give you the ``i``-th offset sine curve. Let's set the # default ``prop_cycle`` using :func:`matplotlib.pyplot.rc`. We'll combine a # color cycler and a linestyle cycler by adding (``+``) two ``cycler``'s @@ -45,7 +45,7 @@ plt.rc('lines', linewidth=4) plt.rc('axes', prop_cycle=default_cycler) -############################################################################### +# %% # Now we'll generate a figure with two axes, one on top of the other. On the # first axis, we'll plot with the default cycler. On the second axis, we'll # set the ``prop_cycle`` using :func:`matplotlib.axes.Axes.set_prop_cycle`, @@ -66,7 +66,7 @@ fig.subplots_adjust(hspace=0.3) plt.show() -############################################################################### +# %% # Setting ``prop_cycle`` in the :file:`matplotlibrc` file or style files # ---------------------------------------------------------------------- # diff --git a/tutorials/intermediate/constrainedlayout_guide.py b/tutorials/intermediate/constrainedlayout_guide.py index ebec5478cfda..c89f0dcfaf74 100644 --- a/tutorials/intermediate/constrainedlayout_guide.py +++ b/tutorials/intermediate/constrainedlayout_guide.py @@ -66,7 +66,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig, ax = plt.subplots(layout=None) example_plot(ax, fontsize=24) -############################################################################### +# %% # To prevent this, the location of axes needs to be adjusted. For # subplots, this can be done manually by adjusting the subplot parameters # using `.Figure.subplots_adjust`. However, specifying your figure with the @@ -76,7 +76,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig, ax = plt.subplots(layout="constrained") example_plot(ax, fontsize=24) -############################################################################### +# %% # When you have multiple subplots, often you see labels of different # axes overlapping each other. @@ -84,7 +84,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): for ax in axs.flat: example_plot(ax) -############################################################################### +# %% # Specifying ``layout="constrained"`` in the call to ``plt.subplots`` # causes the layout to be properly constrained. @@ -92,7 +92,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): for ax in axs.flat: example_plot(ax) -############################################################################### +# %% # Colorbars # ========= # @@ -117,7 +117,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): im = ax.pcolormesh(arr, **pc_kwargs) fig.colorbar(im, ax=ax, shrink=0.6) -############################################################################ +# %% # If you specify a list of axes (or other iterable container) to the # ``ax`` argument of ``colorbar``, constrained_layout will take space from # the specified axes. @@ -127,7 +127,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): im = ax.pcolormesh(arr, **pc_kwargs) fig.colorbar(im, ax=axs, shrink=0.6) -############################################################################ +# %% # If you specify a list of axes from inside a grid of axes, the colorbar # will steal space appropriately, and leave a gap, but all subplots will # still be the same size. @@ -138,7 +138,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.colorbar(im, ax=axs[1:, 1], shrink=0.8) fig.colorbar(im, ax=axs[:, -1], shrink=0.6) -#################################################### +# %% # Suptitle # ========= # @@ -150,7 +150,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.colorbar(im, ax=axs, shrink=0.6) fig.suptitle('Big Suptitle') -#################################################### +# %% # Legends # ======= # @@ -163,7 +163,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): ax.plot(np.arange(10), label='This is a plot') ax.legend(loc='center left', bbox_to_anchor=(0.8, 0.5)) -############################################# +# %% # However, this will steal space from a subplot layout: fig, axs = plt.subplots(1, 2, figsize=(4, 2), layout="constrained") @@ -171,7 +171,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): axs[1].plot(np.arange(10), label='This is a plot') axs[1].legend(loc='center left', bbox_to_anchor=(0.8, 0.5)) -############################################# +# %% # In order for a legend or other artist to *not* steal space # from the subplot layout, we can ``leg.set_in_layout(False)``. # Of course this can mean the legend ends up @@ -203,7 +203,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): # the directory above doesn't exist pass -############################################# +# %% # The saved file looks like: # # .. image:: /_static/constrained_layout_1b.png @@ -226,14 +226,14 @@ def example_plot(ax, fontsize=12, hide_labels=False): pass -############################################# +# %% # The saved file looks like: # # .. image:: /_static/constrained_layout_2b.png # :align: center # -############################################################################### +# %% # Padding and Spacing # =================== # @@ -248,7 +248,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0, wspace=0) -########################################## +# %% # Spacing between subplots is further set by *wspace* and *hspace*. These # are specified as a fraction of the size of the subplot group as a whole. # If these values are smaller than *w_pad* or *h_pad*, then the fixed pads are @@ -261,7 +261,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.2, wspace=0.2) -########################################## +# %% # If there are more than two columns, the *wspace* is shared between them, # so here the wspace is divided in two, with a *wspace* of 0.1 between each # column: @@ -272,7 +272,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.2, wspace=0.2) -########################################## +# %% # GridSpecs also have optional *hspace* and *wspace* keyword arguments, # that will be used instead of the pads set by ``constrained_layout``: @@ -285,7 +285,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.0, wspace=0.0) -########################################## +# %% # Spacing with colorbars # ----------------------- # @@ -304,7 +304,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.get_layout_engine().set(w_pad=2 / 72, h_pad=2 / 72, hspace=0.2, wspace=0.2) -########################################## +# %% # rcParams # ======== # @@ -324,7 +324,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): for ax in axs.flat: example_plot(ax) -############################# +# %% # Use with GridSpec # ================= # @@ -346,7 +346,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): example_plot(ax1) example_plot(ax2) -############################################################################### +# %% # More complicated gridspec layouts are possible. Note here we use the # convenience functions `~.Figure.add_gridspec` and # `~.SubplotSpec.subgridspec`. @@ -372,7 +372,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): ax.set_xlabel("x-label", fontsize=12) -############################################################################ +# %% # Note that in the above the left and right columns don't have the same # vertical extent. If we want the top and bottom of the two grids to line up # then they need to be in the same gridspec. We need to make this figure @@ -396,7 +396,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): example_plot(ax, hide_labels=True) fig.suptitle('Overlapping Gridspecs') -############################################################################ +# %% # This example uses two gridspecs to have the colorbar only pertain to # one set of pcolors. Note how the left column is wider than the # two right-hand columns because of this. Of course, if you wanted the @@ -422,7 +422,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.suptitle('Nested plots using subgridspec') fig.colorbar(pcm, ax=axs) -############################################################################### +# %% # Rather than using subgridspecs, Matplotlib now provides `~.Figure.subfigures` # which also work with ``constrained_layout``: @@ -442,7 +442,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.colorbar(pcm, ax=axs_right) fig.suptitle('Nested plots using subfigures') -############################################################################### +# %% # Manually setting axes positions # ================================ # @@ -455,7 +455,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): example_plot(axs[0], fontsize=12) axs[1].set_position([0.2, 0.2, 0.4, 0.4]) -############################################################################### +# %% # .. _compressed_layout: # # Grids of fixed aspect-ratio Axes: "compressed" layout @@ -472,7 +472,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): ax.imshow(arr) fig.suptitle("fixed-aspect plots, layout='constrained'") -############################################################################### +# %% # One obvious way of fixing this is to make the figure size more square, # however, closing the gaps exactly requires trial and error. For simple grids # of Axes we can use ``layout="compressed"`` to do the job for us: @@ -484,7 +484,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.suptitle("fixed-aspect plots, layout='compressed'") -############################################################################### +# %% # Manually turning off ``constrained_layout`` # =========================================== # @@ -524,7 +524,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): example_plot(ax3) plt.suptitle('Homogenous nrows, ncols') -############################################################################### +# %% # but the following leads to a poor layout: fig = plt.figure(layout="constrained") @@ -538,7 +538,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): example_plot(ax3) plt.suptitle('Mixed nrows, ncols') -############################################################################### +# %% # Similarly, # `~matplotlib.pyplot.subplot2grid` works with the same limitation # that nrows and ncols cannot change for the layout to look good. @@ -556,7 +556,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): example_plot(ax4) fig.suptitle('subplot2grid') -############################################################################### +# %% # Other Caveats # ------------- # @@ -577,7 +577,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): # :meth:`~matplotlib.figure.Figure.add_artist`. See # :class:`~matplotlib.patches.ConnectionPatch` for an example. -########################################################### +# %% # Debugging # ========= # @@ -594,7 +594,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): # If there is a bug, please report with a self-contained example that does # not require outside data or dependencies (other than numpy). -########################################################### +# %% # Notes on the algorithm # ====================== # @@ -637,7 +637,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): example_plot(ax, fontsize=24) plot_children(fig) -####################################################################### +# %% # Simple case: two Axes # --------------------- # When there are multiple axes they have their layouts bound in @@ -652,7 +652,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): example_plot(ax[1], fontsize=8) plot_children(fig) -####################################################################### +# %% # Two Axes and colorbar # --------------------- # @@ -665,7 +665,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): im = ax[1].pcolormesh(arr, **pc_kwargs) plot_children(fig) -####################################################################### +# %% # Colorbar associated with a Gridspec # ----------------------------------- # @@ -678,7 +678,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): fig.colorbar(im, ax=axs, shrink=0.6) plot_children(fig) -####################################################################### +# %% # Uneven sized Axes # ----------------- # @@ -703,7 +703,7 @@ def example_plot(ax, fontsize=12, hide_labels=False): im = ax.pcolormesh(arr, **pc_kwargs) plot_children(fig) -####################################################################### +# %% # One case that requires finessing is if margins do not have any artists # constraining their width. In the case below, the right margin for column 0 # and the left margin for column 3 have no margin artists to set their width, diff --git a/tutorials/intermediate/imshow_extent.py b/tutorials/intermediate/imshow_extent.py index 8065a06714b3..20c50c32333d 100644 --- a/tutorials/intermediate/imshow_extent.py +++ b/tutorials/intermediate/imshow_extent.py @@ -161,7 +161,7 @@ def generate_imshow_demo_grid(extents, xlim=None, ylim=None): return columns -############################################################################### +# %% # # Default extent # -------------- @@ -170,7 +170,7 @@ def generate_imshow_demo_grid(extents, xlim=None, ylim=None): generate_imshow_demo_grid(extents=[None]) -############################################################################### +# %% # # Generally, for an array of shape (M, N), the first index runs along the # vertical, the second index runs along the horizontal. @@ -229,7 +229,7 @@ def generate_imshow_demo_grid(extents, xlim=None, ylim=None): set_extent_None_text(columns['lower'][0]) -############################################################################### +# %% # # Explicit extent and axes limits # ------------------------------- diff --git a/tutorials/intermediate/legend_guide.py b/tutorials/intermediate/legend_guide.py index 338fca72fbf1..29ace420a14f 100644 --- a/tutorials/intermediate/legend_guide.py +++ b/tutorials/intermediate/legend_guide.py @@ -90,7 +90,7 @@ plt.show() -############################################################################### +# %% # There are many supported legend handles. Instead of creating a patch of color # we could have created a line with a marker: @@ -103,7 +103,7 @@ plt.show() -############################################################################### +# %% # Legend location # =============== # @@ -135,7 +135,7 @@ ax_dict['bottom'].legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.) -############################################################################## +# %% # Figure legends # -------------- # @@ -154,7 +154,7 @@ # Place a legend to the right of this smaller subplot. fig.legend(loc='outside upper right') -############################################################################## +# %% # This accepts a slightly different grammar than the normal *loc* keyword, # where "outside right upper" is different from "outside upper right". # @@ -184,7 +184,7 @@ fig.legend(loc=loc, title=loc) -############################################################################### +# %% # Multiple legends on the same Axes # ================================= # @@ -211,7 +211,7 @@ plt.show() -############################################################################### +# %% # Legend Handlers # =============== # @@ -247,7 +247,7 @@ ax.legend(handler_map={line1: HandlerLine2D(numpoints=4)}) -############################################################################### +# %% # As you can see, "Line 1" now has 4 marker points, where "Line 2" has 2 (the # default). Try the above code, only change the map's key from ``line1`` to # ``type(line1)``. Notice how now both `.Line2D` instances get 4 markers. @@ -269,7 +269,7 @@ ax.legend([red_dot, (red_dot, white_cross)], ["Attr A", "Attr A+B"]) -############################################################################### +# %% # The `.legend_handler.HandlerTuple` class can also be used to # assign several legend keys to the same entry: @@ -282,7 +282,7 @@ l = ax.legend([(p1, p2)], ['Two keys'], numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}) -############################################################################### +# %% # Implementing a custom legend handler # ------------------------------------ # @@ -314,7 +314,7 @@ def legend_artist(self, legend, orig_handle, fontsize, handlebox): ax.legend([AnyObject()], ['My first handler'], handler_map={AnyObject: AnyObjectHandler()}) -############################################################################### +# %% # Alternatively, had we wanted to globally accept ``AnyObject`` instances # without needing to manually set the *handler_map* keyword all the time, we # could have registered the new handler with:: diff --git a/tutorials/intermediate/tight_layout_guide.py b/tutorials/intermediate/tight_layout_guide.py index 27b7d0777126..60c3720b52a7 100644 --- a/tutorials/intermediate/tight_layout_guide.py +++ b/tutorials/intermediate/tight_layout_guide.py @@ -44,7 +44,7 @@ def example_plot(ax, fontsize=12): fig, ax = plt.subplots() example_plot(ax, fontsize=24) -############################################################################### +# %% # To prevent this, the location of axes needs to be adjusted. For # subplots, this can be done manually by adjusting the subplot parameters # using `.Figure.subplots_adjust`. `.Figure.tight_layout` does this @@ -54,7 +54,7 @@ def example_plot(ax, fontsize=12): example_plot(ax, fontsize=24) plt.tight_layout() -############################################################################### +# %% # Note that :func:`matplotlib.pyplot.tight_layout` will only adjust the # subplot params when it is called. In order to perform this adjustment each # time the figure is redrawn, you can call ``fig.set_tight_layout(True)``, or, @@ -71,7 +71,7 @@ def example_plot(ax, fontsize=12): example_plot(ax3) example_plot(ax4) -############################################################################### +# %% # :func:`~matplotlib.pyplot.tight_layout` will also adjust spacing between # subplots to minimize the overlaps. @@ -82,7 +82,7 @@ def example_plot(ax, fontsize=12): example_plot(ax4) plt.tight_layout() -############################################################################### +# %% # :func:`~matplotlib.pyplot.tight_layout` can take keyword arguments of # *pad*, *w_pad* and *h_pad*. These control the extra padding around the # figure border and between subplots. The pads are specified in fraction @@ -95,7 +95,7 @@ def example_plot(ax, fontsize=12): example_plot(ax4) plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) -############################################################################### +# %% # :func:`~matplotlib.pyplot.tight_layout` will work even if the sizes of # subplots are different as far as their grid specification is # compatible. In the example below, *ax1* and *ax2* are subplots of a 2x2 @@ -114,7 +114,7 @@ def example_plot(ax, fontsize=12): plt.tight_layout() -############################################################################### +# %% # It works with subplots created with # :func:`~matplotlib.pyplot.subplot2grid`. In general, subplots created # from the gridspec (:doc:`/tutorials/intermediate/arranging_axes`) will work. @@ -134,7 +134,7 @@ def example_plot(ax, fontsize=12): plt.tight_layout() -############################################################################### +# %% # Although not thoroughly tested, it seems to work for subplots with # aspect != "auto" (e.g., axes with images). @@ -148,7 +148,7 @@ def example_plot(ax, fontsize=12): plt.tight_layout() -############################################################################### +# %% # Caveats # ======= # @@ -184,7 +184,7 @@ def example_plot(ax, fontsize=12): gs1.tight_layout(fig) -############################################################################### +# %% # You may provide an optional *rect* parameter, which specifies the bounding # box that the subplots will be fit inside. The coordinates must be in # normalized figure coordinates and the default is (0, 0, 1, 1). @@ -200,7 +200,7 @@ def example_plot(ax, fontsize=12): gs1.tight_layout(fig, rect=[0, 0, 0.5, 1.0]) -############################################################################### +# %% # However, we do not recommend that this be used to manually construct more # complicated layouts, like having one GridSpec in the left and one in the # right side of the figure. For these use cases, one should instead take @@ -208,7 +208,7 @@ def example_plot(ax, fontsize=12): # the :doc:`/gallery/subplots_axes_and_figures/subfigures`. -############################################################################### +# %% # Legends and Annotations # ======================= # @@ -224,7 +224,7 @@ def example_plot(ax, fontsize=12): fig.tight_layout() plt.show() -############################################################################### +# %% # However, sometimes this is not desired (quite often when using # ``fig.savefig('outname.png', bbox_inches='tight')``). In order to # remove the legend from the bounding box calculation, we simply set its @@ -237,7 +237,7 @@ def example_plot(ax, fontsize=12): fig.tight_layout() plt.show() -############################################################################### +# %% # Use with AxesGrid1 # ================== # @@ -257,7 +257,7 @@ def example_plot(ax, fontsize=12): plt.tight_layout() -############################################################################### +# %% # Colorbar # ======== # @@ -274,7 +274,7 @@ def example_plot(ax, fontsize=12): plt.tight_layout() -############################################################################### +# %% # Another option is to use the AxesGrid1 toolkit to # explicitly create an Axes for the colorbar. diff --git a/tutorials/introductory/animation_tutorial.py b/tutorials/introductory/animation_tutorial.py index a736580a36e4..53756eb37a94 100644 --- a/tutorials/introductory/animation_tutorial.py +++ b/tutorials/introductory/animation_tutorial.py @@ -14,7 +14,7 @@ import matplotlib.animation as animation import numpy as np -############################################################################### +# %% # Animation Classes # ================= # @@ -121,7 +121,7 @@ def update(frame): plt.show() -############################################################################### +# %% # ``ArtistAnimation`` # ------------------- # @@ -152,7 +152,7 @@ def update(frame): ani = animation.ArtistAnimation(fig=fig, artists=artists, interval=400) plt.show() -############################################################################### +# %% # Animation Writers # ================= # diff --git a/tutorials/introductory/customizing.py b/tutorials/introductory/customizing.py index 10fc21d2187b..0048e517a63b 100644 --- a/tutorials/introductory/customizing.py +++ b/tutorials/introductory/customizing.py @@ -38,14 +38,14 @@ data = np.random.randn(50) plt.plot(data) -############################################################################### +# %% # Note, that in order to change the usual `~.Axes.plot` color you have to # change the *prop_cycle* property of *axes*: mpl.rcParams['axes.prop_cycle'] = cycler(color=['r', 'g', 'b', 'y']) plt.plot(data) # first color is red -############################################################################### +# %% # Matplotlib also provides a couple of convenience functions for modifying rc # settings. `matplotlib.rc` can be used to modify multiple # settings in a single group at once, using keyword arguments: @@ -53,7 +53,7 @@ mpl.rc('lines', linewidth=4, linestyle='-.') plt.plot(data) -############################################################################### +# %% # Temporary rc settings # --------------------- # @@ -63,7 +63,7 @@ with mpl.rc_context({'lines.linewidth': 2, 'lines.linestyle': ':'}): plt.plot(data) -############################################################################### +# %% # `matplotlib.rc_context` can also be used as a decorator to modify the # defaults within a function: @@ -74,14 +74,14 @@ def plotting_function(): plotting_function() -############################################################################### +# %% # `matplotlib.rcdefaults` will restore the standard Matplotlib # default settings. # # There is some degree of validation when setting the values of rcParams, see # :mod:`matplotlib.rcsetup` for details. -############################################################################### +# %% # .. _customizing-with-style-sheets: # # Using style sheets @@ -109,12 +109,12 @@ def plotting_function(): plt.style.use('ggplot') -############################################################################### +# %% # To list all available styles, use: print(plt.style.available) -############################################################################### +# %% # Defining your own style # ----------------------- # @@ -195,7 +195,7 @@ def plotting_function(): plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o') plt.show() -############################################################################### +# %% # .. _customizing-with-matplotlibrc-files: # # The :file:`matplotlibrc` file diff --git a/tutorials/introductory/images.py b/tutorials/introductory/images.py index 7673037c4a9c..f2d9fbc20191 100644 --- a/tutorials/introductory/images.py +++ b/tutorials/introductory/images.py @@ -52,7 +52,7 @@ import numpy as np from PIL import Image -############################################################################### +# %% # .. _importing_data: # # Importing image data into Numpy arrays @@ -80,7 +80,7 @@ img = np.asarray(Image.open('../../doc/_static/stinkbug.png')) print(repr(img)) -############################################################################### +# %% # Each inner list represents a pixel. Here, with an RGB image, there # are 3 values. Since it's a black and white image, R, G, and B are all # similar. An RGBA (where A is alpha, or transparency) has 4 values @@ -103,7 +103,7 @@ imgplot = plt.imshow(img) -############################################################################### +# %% # You can also plot any numpy array. # # .. _Pseudocolor: @@ -126,21 +126,21 @@ lum_img = img[:, :, 0] plt.imshow(lum_img) -############################################################################### +# %% # Now, with a luminosity (2D, no color) image, the default colormap (aka lookup table, # LUT), is applied. The default is called viridis. There are plenty of # others to choose from. plt.imshow(lum_img, cmap="hot") -############################################################################### +# %% # Note that you can also change colormaps on existing plot objects using the # :meth:`~matplotlib.cm.ScalarMappable.set_cmap` method: imgplot = plt.imshow(lum_img) imgplot.set_cmap('nipy_spectral') -############################################################################### +# %% # # .. note:: # @@ -166,7 +166,7 @@ imgplot = plt.imshow(lum_img) plt.colorbar() -############################################################################### +# %% # .. _`Data ranges`: # # Examining a specific data range @@ -180,7 +180,7 @@ plt.hist(lum_img.ravel(), bins=range(256), fc='k', ec='k') -############################################################################### +# %% # Most often, the "interesting" part of the image is around the peak, # and you can get extra contrast by clipping the regions above and/or # below the peak. In our histogram, it looks like there's not much @@ -194,7 +194,7 @@ plt.imshow(lum_img, clim=(0, 175)) -############################################################################### +# %% # This can also be done by calling the # :meth:`~matplotlib.cm.ScalarMappable.set_clim` method of the returned image # plot object, but make sure that you do so in the same cell as your plot @@ -204,7 +204,7 @@ imgplot = plt.imshow(lum_img) imgplot.set_clim(0, 175) -############################################################################### +# %% # .. _Interpolation: # # Array Interpolation schemes @@ -230,7 +230,7 @@ img.thumbnail((64, 64)) # resizes image in-place imgplot = plt.imshow(img) -############################################################################### +# %% # Here we use the default interpolation ("nearest"), since we did not # give :func:`~matplotlib.pyplot.imshow` any interpolation argument. # @@ -238,11 +238,11 @@ imgplot = plt.imshow(img, interpolation="bilinear") -############################################################################### +# %% # and bicubic: imgplot = plt.imshow(img, interpolation="bicubic") -############################################################################### +# %% # Bicubic interpolation is often used when blowing up photos - people # tend to prefer blurry over pixelated. diff --git a/tutorials/introductory/lifecycle.py b/tutorials/introductory/lifecycle.py index 3d3a1036ff2b..cf1b4821f525 100644 --- a/tutorials/introductory/lifecycle.py +++ b/tutorials/introductory/lifecycle.py @@ -73,7 +73,7 @@ group_names = list(data.keys()) group_mean = np.mean(group_data) -############################################################################### +# %% # Getting started # =============== # @@ -91,13 +91,13 @@ fig, ax = plt.subplots() -############################################################################### +# %% # Now that we have an Axes instance, we can plot on top of it. fig, ax = plt.subplots() ax.barh(group_names, group_data) -############################################################################### +# %% # Controlling the style # ===================== # @@ -107,18 +107,18 @@ print(plt.style.available) -############################################################################### +# %% # You can activate a style with the following: plt.style.use('fivethirtyeight') -############################################################################### +# %% # Now let's remake the above plot to see how it looks: fig, ax = plt.subplots() ax.barh(group_names, group_data) -############################################################################### +# %% # The style controls many things, such as color, linewidths, backgrounds, # etc. # @@ -134,7 +134,7 @@ ax.barh(group_names, group_data) labels = ax.get_xticklabels() -############################################################################### +# %% # If we'd like to set the property of many items at once, it's useful to use # the :func:`pyplot.setp` function. This will take a list (or many lists) of # Matplotlib objects, and attempt to set some style element of each one. @@ -144,7 +144,7 @@ labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') -############################################################################### +# %% # It looks like this cut off some of the labels on the bottom. We can # tell Matplotlib to automatically make room for elements in the figures # that we create. To do this we set the ``autolayout`` value of our @@ -159,7 +159,7 @@ labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') -############################################################################### +# %% # Next, we add labels to the plot. To do this with the OO interface, # we can use the :meth:`.Artist.set` method to set properties of this # Axes object. @@ -171,7 +171,7 @@ ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', title='Company Revenue') -############################################################################### +# %% # We can also adjust the size of this plot using the :func:`pyplot.subplots` # function. We can do this with the *figsize* keyword argument. # @@ -189,7 +189,7 @@ ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', title='Company Revenue') -############################################################################### +# %% # For labels, we can specify custom formatting guidelines in the form of # functions. Below we define a function that takes an integer as input, and # returns a string as an output. When used with `.Axis.set_major_formatter` or @@ -209,7 +209,7 @@ def currency(x, pos): s = '${:1.0f}K'.format(x*1e-3) return s -############################################################################### +# %% # We can then apply this function to the labels on our plot. To do this, # we use the ``xaxis`` attribute of our axes. This lets you perform # actions on a specific axis on our plot. @@ -223,7 +223,7 @@ def currency(x, pos): title='Company Revenue') ax.xaxis.set_major_formatter(currency) -############################################################################### +# %% # Combining multiple visualizations # ================================= # @@ -255,7 +255,7 @@ def currency(x, pos): plt.show() -############################################################################### +# %% # Saving our plot # =============== # @@ -265,7 +265,7 @@ def currency(x, pos): print(fig.canvas.get_supported_filetypes()) -############################################################################### +# %% # We can then use the :meth:`figure.Figure.savefig` in order to save the figure # to disk. Note that there are several useful flags we show below: # diff --git a/tutorials/introductory/pyplot.py b/tutorials/introductory/pyplot.py index 163c74b5b31c..67e3314b8ade 100644 --- a/tutorials/introductory/pyplot.py +++ b/tutorials/introductory/pyplot.py @@ -10,7 +10,7 @@ """ -############################################################################### +# %% # Introduction to pyplot # ====================== # @@ -42,7 +42,7 @@ plt.ylabel('some numbers') plt.show() -############################################################################### +# %% # You may be wondering why the x-axis ranges from 0-3 and the y-axis # from 1-4. If you provide a single list or array to # `~.pyplot.plot`, matplotlib assumes it is a @@ -56,7 +56,7 @@ plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) -############################################################################### +# %% # Formatting the style of your plot # --------------------------------- # @@ -71,7 +71,7 @@ plt.axis([0, 6, 0, 20]) plt.show() -############################################################################### +# %% # See the `~.pyplot.plot` documentation for a complete # list of line styles and format strings. The # `~.pyplot.axis` function in the example above takes a @@ -94,7 +94,7 @@ plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') plt.show() -############################################################################### +# %% # .. _plotting-with-keywords: # # Plotting with keyword strings @@ -119,7 +119,7 @@ plt.ylabel('entry b') plt.show() -############################################################################### +# %% # .. _plotting-with-categorical-vars: # # Plotting with categorical variables @@ -143,7 +143,7 @@ plt.suptitle('Categorical Plotting') plt.show() -############################################################################### +# %% # .. _controlling-line-properties: # # Controlling line properties @@ -260,7 +260,7 @@ def f(t): plt.plot(t2, np.cos(2*np.pi*t2), 'r--') plt.show() -############################################################################### +# %% # The `~.pyplot.figure` call here is optional because a figure will be created # if none exists, just as an Axes will be created (equivalent to an explicit # ``subplot()`` call) if none exists. @@ -342,7 +342,7 @@ def f(t): plt.grid(True) plt.show() -############################################################################### +# %% # All of the `~.pyplot.text` functions return a `matplotlib.text.Text` # instance. Just as with lines above, you can customize the properties by # passing keyword arguments into the text functions or using `~.pyplot.setp`:: @@ -397,7 +397,7 @@ def f(t): plt.ylim(-2, 2) plt.show() -############################################################################### +# %% # In this basic example, both the ``xy`` (arrow tip) and ``xytext`` # locations (text location) are in data coordinates. There are a # variety of other coordinate systems one can choose -- see @@ -464,6 +464,6 @@ def f(t): plt.show() -############################################################################### +# %% # It is also possible to add your own scale, see `matplotlib.scale` for # details. diff --git a/tutorials/introductory/quick_start.py b/tutorials/introductory/quick_start.py index 2caacc5aee22..d398b2314187 100644 --- a/tutorials/introductory/quick_start.py +++ b/tutorials/introductory/quick_start.py @@ -15,7 +15,7 @@ import matplotlib.pyplot as plt import numpy as np -############################################################################## +# %% # # A simple example # ================ @@ -30,7 +30,7 @@ fig, ax = plt.subplots() # Create a figure containing a single axes. ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plot some data on the axes. -############################################################################### +# %% # .. _figure_parts: # # Parts of a Figure @@ -128,7 +128,7 @@ ax.set_xlabel('entry a') ax.set_ylabel('entry b') -############################################################################## +# %% # .. _coding_styles: # # Coding styles @@ -161,7 +161,7 @@ ax.set_title("Simple Plot") # Add a title to the axes. ax.legend() # Add a legend. -############################################################################### +# %% # or the pyplot-style: x = np.linspace(0, 2, 100) # Sample data. @@ -175,7 +175,7 @@ plt.title("Simple Plot") plt.legend() -############################################################################### +# %% # (In addition, there is a third approach, for the case when embedding # Matplotlib in a GUI application, which completely drops pyplot, even for # figure creation. See the corresponding section in the gallery for more info: @@ -207,7 +207,7 @@ def my_plotter(ax, data1, data2, param_dict): out = ax.plot(data1, data2, **param_dict) return out -############################################################################### +# %% # which you would then use twice to populate two subplots: data1, data2, data3, data4 = np.random.randn(4, 100) # make 4 random data sets @@ -215,7 +215,7 @@ def my_plotter(ax, data1, data2, param_dict): my_plotter(ax1, data1, data2, {'marker': 'x'}) my_plotter(ax2, data3, data4, {'marker': 'o'}) -############################################################################### +# %% # Note that if you want to install these as a python package, or any other # customizations you could use one of the many templates on the web; # Matplotlib has one at `mpl-cookiecutter @@ -237,7 +237,7 @@ def my_plotter(ax, data1, data2, param_dict): l, = ax.plot(x, np.cumsum(data2), color='orange', linewidth=2) l.set_linestyle(':') -############################################################################### +# %% # Colors # ------ # @@ -250,7 +250,7 @@ def my_plotter(ax, data1, data2, param_dict): fig, ax = plt.subplots(figsize=(5, 2.7)) ax.scatter(data1, data2, s=50, facecolor='C0', edgecolor='k') -############################################################################### +# %% # Linewidths, linestyles, and markersizes # --------------------------------------- # @@ -274,7 +274,7 @@ def my_plotter(ax, data1, data2, param_dict): ax.plot(data4, 's', label='data4') ax.legend() -############################################################################### +# %% # # Labelling plots # =============== @@ -300,7 +300,7 @@ def my_plotter(ax, data1, data2, param_dict): ax.axis([55, 175, 0, 0.03]) ax.grid(True) -############################################################################### +# %% # All of the `~.Axes.text` functions return a `matplotlib.text.Text` # instance. Just as with lines above, you can customize the properties by # passing keyword arguments into the text functions:: @@ -344,7 +344,7 @@ def my_plotter(ax, data1, data2, param_dict): ax.set_ylim(-2, 2) -############################################################################### +# %% # In this basic example, both *xy* and *xytext* are in data coordinates. # There are a variety of other coordinate systems one can choose -- see # :ref:`annotations-tutorial` and :ref:`plotting-guide-annotation` for @@ -362,7 +362,7 @@ def my_plotter(ax, data1, data2, param_dict): ax.plot(np.arange(len(data3)), data3, 'd', label='data3') ax.legend() -############################################################################## +# %% # Legends in Matplotlib are quite flexible in layout, placement, and what # Artists they can represent. They are discussed in detail in # :doc:`/tutorials/intermediate/legend_guide`. @@ -393,7 +393,7 @@ def my_plotter(ax, data1, data2, param_dict): axs[1].set_yscale('log') axs[1].plot(xdata, data) -############################################################################## +# %% # The scale sets the mapping from data values to spacing along the Axis. This # happens in both directions, and gets combined into a *transform*, which # is the way that Matplotlib maps from data coordinates to Axes, Figure, or @@ -415,7 +415,7 @@ def my_plotter(ax, data1, data2, param_dict): axs[1].set_yticks([-1.5, 0, 1.5]) # note that we don't need to specify labels axs[1].set_title('Manual ticks') -############################################################################## +# %% # Different scales can have different locators and formatters; for instance # the log-scale above uses `~.LogLocator` and `~.LogFormatter`. See # :doc:`/gallery/ticks/tick-locators` and @@ -437,7 +437,7 @@ def my_plotter(ax, data1, data2, param_dict): cdf = mpl.dates.ConciseDateFormatter(ax.xaxis.get_major_locator()) ax.xaxis.set_major_formatter(cdf) -############################################################################## +# %% # For more information see the date examples # (e.g. :doc:`/gallery/text_labels_and_annotations/date`) # @@ -449,7 +449,7 @@ def my_plotter(ax, data1, data2, param_dict): ax.bar(categories, np.random.rand(len(categories))) -############################################################################## +# %% # One caveat about categorical plotting is that some methods of parsing # text files return a list of strings, even if the strings all represent # numbers or dates. If you pass 1000 strings, Matplotlib will think you @@ -482,7 +482,7 @@ def my_plotter(ax, data1, data2, param_dict): ax4 = ax3.secondary_xaxis('top', functions=(np.rad2deg, np.deg2rad)) ax4.set_xlabel('Angle [°]') -############################################################################## +# %% # Color mapped data # ================= # @@ -510,7 +510,7 @@ def my_plotter(ax, data1, data2, param_dict): fig.colorbar(pc, ax=axs[1, 1], extend='both') axs[1, 1].set_title('scatter()') -############################################################################## +# %% # Colormaps # --------- # @@ -563,7 +563,7 @@ def my_plotter(ax, data1, data2, param_dict): axd['lowleft'].set_title('lowleft') axd['right'].set_title('right') -############################################################################### +# %% # Matplotlib has quite sophisticated tools for arranging Axes: See # :doc:`/tutorials/intermediate/arranging_axes` and # :doc:`/gallery/subplots_axes_and_figures/mosaic`. diff --git a/tutorials/text/annotations.py b/tutorials/text/annotations.py index bee2e244238d..06f694d96260 100644 --- a/tutorials/text/annotations.py +++ b/tutorials/text/annotations.py @@ -14,7 +14,7 @@ .. contents:: Table of Contents :depth: 3 """ -############################################################################### +# %% # .. _annotations-tutorial: # # Basic annotation @@ -37,7 +37,7 @@ arrowprops=dict(facecolor='black', shrink=0.05)) ax.set_ylim(-2, 2) -############################################################################### +# %% # In this example, both the *xy* (arrow tip) and *xytext* locations # (text location) are in data coordinates. There are a variety of other # coordinate systems one can choose -- you can specify the coordinate @@ -90,7 +90,7 @@ arrowprops=dict(facecolor='black', shrink=0.05)) ax.set_ylim(-2, 2) -################################################################### +# %% # # .. _annotation-with-arrow: # @@ -139,7 +139,7 @@ horizontalalignment='left', verticalalignment='bottom') -############################################################################### +# %% # For more on plotting with arrows, see :ref:`annotation_with_custom_arrow` # # .. _annotations-offset-text: @@ -161,7 +161,7 @@ xy=(xi, yi), xycoords='data', xytext=(1.5, 1.5), textcoords='offset points') -############################################################################### +# %% # The annotations are offset 1.5 points (1.5*1/72 inches) from the *xy* values. # # .. _plotting-guide-annotation: @@ -184,7 +184,7 @@ bbox=dict(boxstyle="rarrow,pad=0.3", fc="lightblue", ec="steelblue", lw=2)) -############################################################################### +# %% # The arguments are the name of the box style with its attributes as # keyword arguments. Currently, following box styles are implemented. # @@ -262,7 +262,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): ax.text(0.5, 0.5, "Test", size=30, va="center", ha="center", rotation=30, bbox=dict(boxstyle=custom_box_style, alpha=0.2)) -############################################################################### +# %% # See also :doc:`/gallery/userdemo/custom_boxstyle01`. Similarly, you can define a # custom `.ConnectionStyle` and a custom `.ArrowStyle`. View the source code at # `.patches` to learn how each class is defined. @@ -282,7 +282,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): xytext=(0.8, 0.8), textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3")) -############################################################################### +# %% # The arrow is drawn as follows: # # 1. A path connecting the two points is created, as specified by the @@ -364,7 +364,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): arrowprops=dict(arrowstyle="simple", connectionstyle="arc3,rad=-0.2")) -############################################################################## +# %% # As with `~.Axes.text`, a box around the text can be drawn using the *bbox* # argument. @@ -379,7 +379,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): connectionstyle="arc3,rad=-0.2", fc="w")) -############################################################################## +# %% # By default, the starting point is set to the center of the text # extent. This can be adjusted with ``relpos`` key value. The values # are normalized to the extent of the text. For example, (0, 0) means @@ -407,7 +407,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): relpos=(1., 0.), fc="w")) -############################################################################## +# %% # Placing Artist at anchored Axes locations # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # @@ -425,7 +425,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) -############################################################################### +# %% # The *loc* keyword has same meaning as in the legend command. # # A simple application is when the size of the artist (or collection of @@ -455,7 +455,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): ada.drawing_area.add_artist(p2) ax.add_artist(ada) -############################################################################### +# %% # Sometimes, you want your artists to scale with the data coordinate (or # coordinates other than canvas pixels). You can use # `~mpl_toolkits.axes_grid1.anchored_artists.AnchoredAuxTransformBox` class. @@ -477,7 +477,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): box.drawing_area.add_artist(el) ax.add_artist(box) -############################################################################### +# %% # Another method of anchoring an artist relative to a parent axes or anchor # point is via the *bbox_to_anchor* argument of `.AnchoredOffsetbox`. This # artist can then be automatically positioned relative to another artist using @@ -512,7 +512,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): ax.add_artist(anchored_box) fig.subplots_adjust(top=0.8) -############################################################################### +# %% # Note that, unlike in `.Legend`, the ``bbox_transform`` is set to # `.IdentityTransform` by default # @@ -535,7 +535,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): ax1.annotate("Test", xy=(0.5, 0.5), xycoords=ax1.transAxes) ax2.annotate("Test", xy=(0.5, 0.5), xycoords="axes fraction") -############################################################################### +# %% # Another commonly used `.Transform` instance is ``Axes.transData``. This # transform is the coordinate system of the data plotted in the axes. In this # example, it is used to draw an arrow from a point in *ax1* to text in *ax2*, @@ -550,7 +550,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): xytext=(0.5, 0.5), textcoords=ax2.transData, arrowprops=dict(arrowstyle="->")) -############################################################################# +# %% # 2. An `.Artist` instance. The *xy* value (or *xytext*) is interpreted as a # fractional coordinate of the bounding box (bbox) of the artist: @@ -567,7 +567,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->")) -############################################################################### +# %% # Note that you must ensure that the extent of the coordinate artist (*an1* in # this example) is determined before *an2* gets drawn. Usually, this means # that *an2* needs to be drawn after *an1*. The base class for all bounding @@ -591,7 +591,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->")) -############################################################################### +# %% # `.Artist.get_window_extent` is the bounding box of the Axes object and is # therefore identical to setting the coordinate system to axes fraction: @@ -600,7 +600,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): an1 = ax1.annotate("Test1", xy=(0.5, 0.5), xycoords="axes fraction") an2 = ax2.annotate("Test 2", xy=(0.5, 0.5), xycoords=ax2.get_window_extent) -############################################################################### +# %% # 4. A blended pair of coordinate specifications -- the first for the # x-coordinate, and the second is for the y-coordinate. For example, x=0.5 is # in data coordinates, and y=1 is in normalized axes coordinates: @@ -610,7 +610,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): ax.axvline(x=.5, color='lightgray') ax.set(xlim=(0, 2), ylim=(1, 2)) -############################################################################### +# %% # 5. Sometimes, you want your annotation with some "offset points", not from the # annotated point but from some other point or artist. `.text.OffsetFrom` is # a helper for such cases. @@ -630,7 +630,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->")) -############################################################################### +# %% # Using ConnectionPatch # ~~~~~~~~~~~~~~~~~~~~~ # @@ -649,7 +649,7 @@ def custom_box_style(x0, y0, width, height, mutation_size): fig.add_artist(con) -############################################################################### +# %% # Here, we added the `.ConnectionPatch` to the *figure* # (with `~.Figure.add_artist`) rather than to either axes. This ensures that # the ConnectionPatch artist is drawn on top of both axes, and is also necessary diff --git a/tutorials/text/text_intro.py b/tutorials/text/text_intro.py index 42539302a730..5200197b25b7 100644 --- a/tutorials/text/text_intro.py +++ b/tutorials/text/text_intro.py @@ -101,7 +101,7 @@ plt.show() -############################################################################### +# %% # Labels for x- and y-axis # ======================== # @@ -123,7 +123,7 @@ plt.show() -############################################################################### +# %% # The x- and y-labels are automatically placed so that they clear the x- and # y-ticklabels. Compare the plot below with that above, and note the y-label # is to the left of the one above. @@ -136,7 +136,7 @@ plt.show() -############################################################################### +# %% # If you want to move the labels, you can specify the *labelpad* keyword # argument, where the value is points (1/72", the same unit used to specify # fontsizes). @@ -149,7 +149,7 @@ plt.show() -############################################################################### +# %% # Or, the labels accept all the `.Text` keyword arguments, including # *position*, via which we can manually specify the label positions. Here we # put the xlabel to the far left of the axis. Note, that the y-coordinate of @@ -164,7 +164,7 @@ plt.show() -############################################################################## +# %% # All the labelling in this tutorial can be changed by manipulating the # `matplotlib.font_manager.FontProperties` method, or by named keyword # arguments to `~matplotlib.axes.Axes.set_xlabel` @@ -184,7 +184,7 @@ plt.show() -############################################################################## +# %% # Finally, we can use native TeX rendering in all text objects and have # multiple lines: @@ -196,7 +196,7 @@ plt.show() -############################################################################## +# %% # Titles # ====== # @@ -211,7 +211,7 @@ ax.set_title('Title with loc at '+loc, loc=loc) plt.show() -############################################################################## +# %% # Vertical spacing for titles is controlled via :rc:`axes.titlepad`. # Setting to a different value moves the title. @@ -222,7 +222,7 @@ plt.show() -############################################################################## +# %% # Ticks and ticklabels # ==================== # @@ -263,7 +263,7 @@ axs[1].xaxis.set_ticks(np.arange(0., 8.1, 2.)) plt.show() -############################################################################# +# %% # We can of course fix this after the fact, but it does highlight a # weakness of hard-coding the ticks. This example also changes the format # of the ticks: @@ -279,7 +279,7 @@ axs[1].set_xlim(axs[0].get_xlim()) plt.show() -############################################################################# +# %% # Tick Locators and Formatters # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # @@ -299,7 +299,7 @@ axs[1].set_xlim(axs[0].get_xlim()) plt.show() -############################################################################# +# %% # And of course we could have used a non-default locator to set the # tick locations. Note we still pass in the tick values, but the # x-limit fix used above is *not* needed. @@ -312,7 +312,7 @@ axs[1].xaxis.set_major_formatter('±{x}°') plt.show() -############################################################################# +# %% # The default formatter is the `matplotlib.ticker.MaxNLocator` called as # ``ticker.MaxNLocator(self, nbins='auto', steps=[1, 2, 2.5, 5, 10])`` # The *steps* keyword contains a list of multiples that can be used for @@ -348,7 +348,7 @@ plt.show() -############################################################################## +# %% # Finally, we can specify functions for the formatter using # `matplotlib.ticker.FuncFormatter`. Further, like # `matplotlib.ticker.StrMethodFormatter`, passing a function will @@ -372,7 +372,7 @@ def formatoddticks(x, pos): plt.show() -############################################################################## +# %% # Dateticks # ~~~~~~~~~ # @@ -395,7 +395,7 @@ def formatoddticks(x, pos): ax.tick_params(axis='x', rotation=70) plt.show() -############################################################################## +# %% # We can pass a format to `matplotlib.dates.DateFormatter`. Also note that the # 29th and the next month are very close together. We can fix this by using # the `.dates.DayLocator` class, which allows us to specify a list of days of @@ -414,7 +414,7 @@ def formatoddticks(x, pos): ax.tick_params(axis='x', rotation=70) plt.show() -############################################################################## +# %% # Legends and Annotations # ======================= # diff --git a/tutorials/text/text_props.py b/tutorials/text/text_props.py index a2acbd0bd27f..4215e3a48d87 100644 --- a/tutorials/text/text_props.py +++ b/tutorials/text/text_props.py @@ -137,7 +137,7 @@ ax.set_axis_off() plt.show() -############################################################################### +# %% # ============== # Default Font # ============== From 6044b307674ce897444e844b7be1bb741f52ac23 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Wed, 18 Jan 2023 11:02:56 -0500 Subject: [PATCH 2/3] DOC: document sg separator preference --- doc/devel/documenting_mpl.rst | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/doc/devel/documenting_mpl.rst b/doc/devel/documenting_mpl.rst index 2dcd33b8c0d6..a766459e10bb 100644 --- a/doc/devel/documenting_mpl.rst +++ b/doc/devel/documenting_mpl.rst @@ -814,7 +814,9 @@ from having an plot generated insert "sgskip" somewhere in the filename. The format of these files is relatively straightforward. Properly formatted comment blocks are treated as ReST_ text, the code is -displayed, and figures are put into the built page. +displayed, and figures are put into the built page. Matplotlib uses the +``# %%`` section separator so that IDEs will identify "code cells" to make +it easy to re-run sub-sections of the example. For instance the example :doc:`/gallery/lines_bars_and_markers/simple_plot` example is generated from @@ -853,7 +855,7 @@ Tutorials are made with the exact same mechanism, except they are longer, and typically have more than one comment block (i.e. :doc:`/tutorials/introductory/quick_start`). The first comment block can be the same as the example above. Subsequent blocks of ReST text -are delimited by a line of ``###`` characters: +are delimited by the line ``# %%`` : .. code-block:: python @@ -868,7 +870,7 @@ are delimited by a line of ``###`` characters: ax.grid() plt.show() - ########################################################################## + # %% # Second plot # =========== # @@ -887,7 +889,7 @@ bottom as follows .. code-block:: python - ############################################################################### + # %% # # .. admonition:: References # From e5f00664f0d5d5dd5777e06a6b1a9aba66b60749 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Thu, 19 Jan 2023 12:27:01 -0500 Subject: [PATCH 3/3] DOC: add a sub-heading --- doc/devel/documenting_mpl.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/doc/devel/documenting_mpl.rst b/doc/devel/documenting_mpl.rst index a766459e10bb..571d664647b3 100644 --- a/doc/devel/documenting_mpl.rst +++ b/doc/devel/documenting_mpl.rst @@ -812,6 +812,10 @@ to create a gallery of images in the :file:`/doc/gallery` and :file:`/doc/tutorials` directories respectively. To exclude an example from having an plot generated insert "sgskip" somewhere in the filename. + +Formatting the example +---------------------- + The format of these files is relatively straightforward. Properly formatted comment blocks are treated as ReST_ text, the code is displayed, and figures are put into the built page. Matplotlib uses the