diff --git a/.appveyor.yml b/.appveyor.yml index a637fe545466..3e3a3b884d18 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -17,7 +17,7 @@ skip_commits: clone_depth: 50 -image: Visual Studio 2019 +image: Visual Studio 2022 environment: @@ -60,6 +60,26 @@ install: - micromamba env create -f environment.yml python=%PYTHON_VERSION% pywin32 - micromamba activate mpl-dev +before_test: + - git config --global user.name 'Matplotlib' + - git config --global user.email 'nobody@matplotlib.org' + - git fetch https://github.com/QuLogic/matplotlib.git text-overhaul-figures:text-overhaul-figures + - git merge --no-commit text-overhaul-figures || true + # If there are any conflicts in baseline images, then pick "ours", + # which should be the updated images in the PR. + - ps: | + $conflicts = git diff --name-only --diff-filter=U ` + lib/matplotlib/tests/baseline_images ` + lib/mpl_toolkits/*/tests/baseline_images + if ($conflicts) { + git checkout --ours -- $conflicts + git add -- $conflicts + } + git status + # If committing fails, there were conflicts other than the baseline images, + # which should not be allowed to happen, and should fail the build. + - git commit -m "Preload test images from branch text-overhaul-figures" + test_script: # Now build the thing.. - set LINK=/LIBPATH:%cd%\lib diff --git a/.github/workflows/cibuildwheel.yml b/.github/workflows/cibuildwheel.yml index 57f1c71c5047..fececb0dfc40 100644 --- a/.github/workflows/cibuildwheel.yml +++ b/.github/workflows/cibuildwheel.yml @@ -140,6 +140,20 @@ jobs: name: cibw-sdist path: dist/ + - name: Build wheels for CPython 3.14 + uses: pypa/cibuildwheel@5f22145df44122af0f5a201f93cf0207171beca7 # v3.0.0 + with: + package-dir: dist/${{ needs.build_sdist.outputs.SDIST_NAME }} + env: + CIBW_BUILD: "cp314-* cp314t-*" + CIBW_ENABLE: "cpython-freethreading cpython-prerelease" + CIBW_ARCHS: ${{ matrix.cibw_archs }} + CIBW_MANYLINUX_X86_64_IMAGE: manylinux_2_28 + CIBW_BEFORE_TEST: >- + python -m pip install + --index-url https://pypi.anaconda.org/scientific-python-nightly-wheels/simple + --upgrade --pre --only-binary=:all: contourpy numpy pillow + - name: Build wheels for CPython 3.13 uses: pypa/cibuildwheel@5f22145df44122af0f5a201f93cf0207171beca7 # v3.0.0 with: @@ -147,8 +161,6 @@ jobs: env: CIBW_BUILD: "cp313-* cp313t-*" CIBW_ENABLE: cpython-freethreading - # No free-threading wheels available for aarch64 on Pillow. - CIBW_TEST_SKIP: "cp313t-manylinux_aarch64" CIBW_ARCHS: ${{ matrix.cibw_archs }} - name: Build wheels for CPython 3.12 @@ -167,7 +179,6 @@ jobs: CIBW_BUILD: "cp311-*" CIBW_ARCHS: ${{ matrix.cibw_archs }} - - name: Build wheels for PyPy uses: pypa/cibuildwheel@5f22145df44122af0f5a201f93cf0207171beca7 # v3.0.0 with: @@ -176,8 +187,6 @@ jobs: CIBW_BUILD: "pp311-*" CIBW_ARCHS: ${{ matrix.cibw_archs }} CIBW_ENABLE: pypy - # No wheels available for Pillow with pp311 yet. - CIBW_TEST_SKIP: "pp311*" if: matrix.cibw_archs != 'aarch64' && matrix.os != 'windows-latest' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index c05454884b55..d6d1eba02560 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -32,7 +32,7 @@ jobs: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@ce28f5bb42b7a9f2c824e633a3f6ee835bab6858 # v3.29.0 + uses: github/codeql-action/init@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2 with: languages: ${{ matrix.language }} @@ -43,4 +43,4 @@ jobs: pip install --user -v . - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@ce28f5bb42b7a9f2c824e633a3f6ee835bab6858 # v3.29.0 + uses: github/codeql-action/analyze@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2a48276707ce..53d47346c6eb 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -95,6 +95,25 @@ jobs: fetch-depth: 0 persist-credentials: false + - name: Preload test images + run: | + git config --global user.name 'Matplotlib' + git config --global user.email 'nobody@matplotlib.org' + git fetch https://github.com/QuLogic/matplotlib.git text-overhaul-figures:text-overhaul-figures + git merge --no-commit text-overhaul-figures || true + # If there are any conflicts in baseline images, then pick "ours", + # which should be the updated images in the PR. + conflicts=$(git diff --name-only --diff-filter=U \ + lib/matplotlib/tests/baseline_images \ + lib/mpl_toolkits/*/tests/baseline_images) + if [ -n "${conflicts}" ]; then + git checkout --ours -- "${conflicts}" + git add -- "${conflicts}" + fi + # If committing fails, there were conflicts other than the baseline images, + # which should not be allowed to happen, and should fail the build. + git commit -m 'Preload test images from branch text-overhaul-figures' + - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: @@ -346,13 +365,15 @@ jobs: run: | function remove_files() { local extension=$1 - find ./result_images -type f -name "*-expected*.$extension" | while read file; do + find ./result_images -name "*-expected*.$extension" | while read file; do if [[ $file == *"-expected_pdf"* ]]; then base=${file%-expected_pdf.$extension}_pdf elif [[ $file == *"-expected_eps"* ]]; then base=${file%-expected_eps.$extension}_eps elif [[ $file == *"-expected_svg"* ]]; then base=${file%-expected_svg.$extension}_svg + elif [[ $file == *"-expected_gif"* ]]; then + base=${file%-expected_gif.$extension}_gif else base=${file%-expected.$extension} fi @@ -369,7 +390,7 @@ jobs: done } - remove_files "png"; remove_files "svg"; remove_files "pdf"; remove_files "eps"; + remove_files "png"; remove_files "svg"; remove_files "pdf"; remove_files "eps"; remove_files "gif"; if [ "$(find ./result_images -mindepth 1 -type d)" ]; then find ./result_images/* -type d -empty -delete diff --git a/azure-pipelines.yml b/azure-pipelines.yml index d68a9d36f0d3..a5a0e965e97b 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -68,6 +68,25 @@ stages: architecture: 'x64' displayName: 'Use Python $(python.version)' + - bash: | + git config --global user.name 'Matplotlib' + git config --global user.email 'nobody@matplotlib.org' + git fetch https://github.com/QuLogic/matplotlib.git text-overhaul-figures:text-overhaul-figures + git merge --no-commit text-overhaul-figures || true + # If there are any conflicts in baseline images, then pick "ours", + # which should be the updated images in the PR. + conflicts=$(git diff --name-only --diff-filter=U \ + lib/matplotlib/tests/baseline_images \ + lib/mpl_toolkits/*/tests/baseline_images) + if [ -n "${conflicts}" ]; then + git checkout --ours -- "${conflicts}" + git add -- "${conflicts}" + fi + # If committing fails, there were conflicts other than the baseline images, + # which should not be allowed to happen, and should fail the build. + git commit -m 'Preload test images from branch text-overhaul-figures' + displayName: Preload test images + - bash: | choco install ninja displayName: 'Install dependencies' diff --git a/doc/api/colors_api.rst b/doc/api/colors_api.rst index 6b02f723d74d..49a42c8f9601 100644 --- a/doc/api/colors_api.rst +++ b/doc/api/colors_api.rst @@ -21,6 +21,7 @@ Color norms :toctree: _as_gen/ :template: autosummary.rst + Norm Normalize NoNorm AsinhNorm diff --git a/doc/api/next_api_changes/deprecations/30163-AL.rst b/doc/api/next_api_changes/deprecations/30163-AL.rst new file mode 100644 index 000000000000..15d0077375f2 --- /dev/null +++ b/doc/api/next_api_changes/deprecations/30163-AL.rst @@ -0,0 +1,9 @@ +``matplotlib.style.core`` +~~~~~~~~~~~~~~~~~~~~~~~~~ +The ``matplotlib.style.core`` module is deprecated. All APIs intended for +public use are now available in `matplotlib.style` directly (including +``USER_LIBRARY_PATHS``, which was previously not reexported). + +The following APIs of ``matplotlib.style.core`` have been deprecated with no +replacement: ``BASE_LIBRARY_PATH``, ``STYLE_EXTENSION``, ``STYLE_BLACKLIST``, +``update_user_library``, ``read_style_directory``, ``update_nested_dict``. diff --git a/doc/api/prev_api_changes/api_changes_3.5.0/deprecations.rst b/doc/api/prev_api_changes/api_changes_3.5.0/deprecations.rst index 05f42035f1ac..04836687f76a 100644 --- a/doc/api/prev_api_changes/api_changes_3.5.0/deprecations.rst +++ b/doc/api/prev_api_changes/api_changes_3.5.0/deprecations.rst @@ -282,7 +282,7 @@ Miscellaneous deprecations - The *format* parameter of ``dviread.find_tex_file`` is deprecated (with no replacement). - ``FancyArrowPatch.get_path_in_displaycoord`` and - ``ConnectionPath.get_path_in_displaycoord`` are deprecated. The path in + ``ConnectionPatch.get_path_in_displaycoord`` are deprecated. The path in display coordinates can still be obtained, as for other patches, using ``patch.get_transform().transform_path(patch.get_path())``. - The ``font_manager.win32InstalledFonts`` and diff --git a/doc/api/prev_api_changes/api_changes_3.7.0/removals.rst b/doc/api/prev_api_changes/api_changes_3.7.0/removals.rst index 03239be31057..56b3ad5c253e 100644 --- a/doc/api/prev_api_changes/api_changes_3.7.0/removals.rst +++ b/doc/api/prev_api_changes/api_changes_3.7.0/removals.rst @@ -323,7 +323,7 @@ Miscellaneous removals - The *format* parameter of ``dviread.find_tex_file`` is removed (with no replacement). - ``FancyArrowPatch.get_path_in_displaycoord`` and - ``ConnectionPath.get_path_in_displaycoord`` are removed. The path in + ``ConnectionPatch.get_path_in_displaycoord`` are removed. The path in display coordinates can still be obtained, as for other patches, using ``patch.get_transform().transform_path(patch.get_path())``. - The ``font_manager.win32InstalledFonts`` and diff --git a/doc/devel/tag_guidelines.rst b/doc/devel/tag_guidelines.rst index 2c80065982bc..2ff77d5279d5 100644 --- a/doc/devel/tag_guidelines.rst +++ b/doc/devel/tag_guidelines.rst @@ -61,7 +61,7 @@ Proposing new tags 1. Review existing tag list, looking out for similar entries (i.e. ``axes`` and ``axis``). 2. If a relevant tag or subcategory does not yet exist, propose it. Each tag is two parts: ``subcategory: tag``. Tags should be one or two words. -3. New tags should be be added when they are relevant to existing gallery entries too. +3. New tags should be added when they are relevant to existing gallery entries too. Avoid tags that will link to only a single gallery entry. 4. Tags can recreate other forms of organization. diff --git a/doc/project/history.rst b/doc/project/history.rst index 966b7a3caa38..7f148902898b 100644 --- a/doc/project/history.rst +++ b/doc/project/history.rst @@ -157,7 +157,7 @@ Matplotlib logo (2008 - 2015). def add_math_background(): - ax = fig.add_axes([0., 0., 1., 1.]) + ax = fig.add_axes((0., 0., 1., 1.)) text = [] text.append( @@ -187,7 +187,7 @@ Matplotlib logo (2008 - 2015). def add_polar_bar(): - ax = fig.add_axes([0.025, 0.075, 0.2, 0.85], projection='polar') + ax = fig.add_axes((0.025, 0.075, 0.2, 0.85), projection='polar') ax.patch.set_alpha(axalpha) ax.set_axisbelow(True) diff --git a/doc/users/faq.rst b/doc/users/faq.rst index b08bd75cee4e..c6bbc5ca8d87 100644 --- a/doc/users/faq.rst +++ b/doc/users/faq.rst @@ -281,8 +281,23 @@ locators as desired because the two axes are independent. Generate images without having a window appear ---------------------------------------------- -Simply do not call `~matplotlib.pyplot.show`, and directly save the figure to -the desired format:: +The recommended approach since matplotlib 3.1 is to explicitly create a Figure +instance:: + + from matplotlib.figure import Figure + fig = Figure() + ax = fig.subplots() + ax.plot([1, 2, 3]) + fig.savefig('myfig.png') + +This prevents any interaction with GUI frameworks and the window manager. + +It's alternatively still possible to use the pyplot interface. Instead of +calling `matplotlib.pyplot.show`, call `matplotlib.pyplot.savefig`. + +Additionally, you must ensure to close the figure after saving it. Not +closing the figure is a memory leak, because pyplot keeps references +to all not-yet-shown figures:: import matplotlib.pyplot as plt plt.plot([1, 2, 3]) diff --git a/doc/users/next_whats_new/new_rcparams_grid_options.rst b/doc/users/next_whats_new/new_rcparams_grid_options.rst new file mode 100644 index 000000000000..c2c0455eecbb --- /dev/null +++ b/doc/users/next_whats_new/new_rcparams_grid_options.rst @@ -0,0 +1,33 @@ +Separate styling options for major/minor grid line in rcParams +-------------------------------------------------------------- + +Using :rc:`grid.major.*` or :rc:`grid.minor.*` will overwrite the value in +:rc:`grid.*` for the major and minor gridlines, respectively. + +.. plot:: + :include-source: true + :alt: Modifying the gridlines using the new options `rcParams` + + import matplotlib as mpl + import matplotlib.pyplot as plt + + + # Set visibility for major and minor gridlines + mpl.rcParams["axes.grid"] = True + mpl.rcParams["ytick.minor.visible"] = True + mpl.rcParams["xtick.minor.visible"] = True + mpl.rcParams["axes.grid.which"] = "both" + + # Using old values to set both major and minor properties + mpl.rcParams["grid.color"] = "red" + mpl.rcParams["grid.linewidth"] = 1 + + # Overwrite some values for major and minor separately + mpl.rcParams["grid.major.color"] = "black" + mpl.rcParams["grid.major.linewidth"] = 2 + mpl.rcParams["grid.minor.linestyle"] = ":" + mpl.rcParams["grid.minor.alpha"] = 0.6 + + plt.plot([0, 1], [0, 1]) + + plt.show() diff --git a/doc/users/prev_whats_new/dflt_style_changes.rst b/doc/users/prev_whats_new/dflt_style_changes.rst index a833064b573b..808204383fb8 100644 --- a/doc/users/prev_whats_new/dflt_style_changes.rst +++ b/doc/users/prev_whats_new/dflt_style_changes.rst @@ -1005,7 +1005,7 @@ a cleaner separation between subplots. ax = fig.add_subplot(2, 2, j) ax.hist(np.random.beta(0.5, 0.5, 10000), 25, density=True) - ax.set_xlim([0, 1]) + ax.set_xlim(0, 1) ax.set_title(title) ax = fig.add_subplot(2, 2, j + 2) diff --git a/doc/users/prev_whats_new/whats_new_3.5.0.rst b/doc/users/prev_whats_new/whats_new_3.5.0.rst index e67573702218..fb156d0c68e8 100644 --- a/doc/users/prev_whats_new/whats_new_3.5.0.rst +++ b/doc/users/prev_whats_new/whats_new_3.5.0.rst @@ -274,9 +274,9 @@ of the text inside the Axes of the `.TextBox` widget. fig = plt.figure(figsize=(4, 3)) for i, alignment in enumerate(['left', 'center', 'right']): - box_input = fig.add_axes([0.1, 0.7 - i*0.3, 0.8, 0.2]) - text_box = TextBox(ax=box_input, initial=f'{alignment} alignment', - label='', textalignment=alignment) + box_input = fig.add_axes((0.1, 0.7 - i*0.3, 0.8, 0.2)) + text_box = TextBox(ax=box_input, initial=f'{alignment} alignment', + label='', textalignment=alignment) Simplifying the font setting for usetex mode -------------------------------------------- @@ -375,9 +375,9 @@ attribute. points = ax.scatter((3, 3), (1, 3), (1, 3), c='red', zorder=10, label='zorder=10') - ax.set_xlim((0, 5)) - ax.set_ylim((0, 5)) - ax.set_zlim((0, 2.5)) + ax.set_xlim(0, 5) + ax.set_ylim(0, 5) + ax.set_zlim(0, 2.5) plane = mpatches.Patch(facecolor='white', edgecolor='black', label='zorder=1') @@ -485,7 +485,7 @@ new styling parameters for the added handles. ax = ax_old valmin = 0 valinit = 0.5 - ax.set_xlim([0, 1]) + ax.set_xlim(0, 1) ax_old.axvspan(valmin, valinit, 0, 1) ax.axvline(valinit, 0, 1, color="r", lw=1) ax.set_xticks([]) diff --git a/doc/users/prev_whats_new/whats_new_3.8.0.rst b/doc/users/prev_whats_new/whats_new_3.8.0.rst index 88f987172adb..fe1d5f7a7952 100644 --- a/doc/users/prev_whats_new/whats_new_3.8.0.rst +++ b/doc/users/prev_whats_new/whats_new_3.8.0.rst @@ -359,7 +359,7 @@ The following delimiter names have been supported earlier, but can now be sized * ``\leftparen`` and ``\rightparen`` There are really no obvious advantages in using these. -Instead, they are are added for completeness. +Instead, they are added for completeness. ``mathtext`` documentation improvements --------------------------------------- @@ -513,7 +513,7 @@ Plot Directive now can make responsive images with "srcset" The plot sphinx directive (``matplotlib.sphinxext.plot_directive``, invoked in rst as ``.. plot::``) can be configured to automatically make higher res -figures and add these to the the built html docs. In ``conf.py``:: +figures and add these to the built html docs. In ``conf.py``:: extensions = [ ... diff --git a/galleries/examples/animation/rain.py b/galleries/examples/animation/rain.py index eacfaecc59e2..a87eace6fe07 100644 --- a/galleries/examples/animation/rain.py +++ b/galleries/examples/animation/rain.py @@ -22,7 +22,7 @@ # Create new Figure and an Axes which fills it. fig = plt.figure(figsize=(7, 7)) -ax = fig.add_axes([0, 0, 1, 1], frameon=False) +ax = fig.add_axes((0, 0, 1, 1), frameon=False) ax.set_xlim(0, 1), ax.set_xticks([]) ax.set_ylim(0, 1), ax.set_yticks([]) diff --git a/galleries/examples/animation/simple_scatter.py b/galleries/examples/animation/simple_scatter.py index 3f8c285810a3..5afef75f6074 100644 --- a/galleries/examples/animation/simple_scatter.py +++ b/galleries/examples/animation/simple_scatter.py @@ -11,7 +11,7 @@ import matplotlib.animation as animation fig, ax = plt.subplots() -ax.set_xlim([0, 10]) +ax.set_xlim(0, 10) scat = ax.scatter(1, 0) x = np.linspace(0, 10) diff --git a/galleries/examples/axes_grid1/make_room_for_ylabel_using_axesgrid.py b/galleries/examples/axes_grid1/make_room_for_ylabel_using_axesgrid.py index f130ef4a6de2..7e914ff76b6b 100644 --- a/galleries/examples/axes_grid1/make_room_for_ylabel_using_axesgrid.py +++ b/galleries/examples/axes_grid1/make_room_for_ylabel_using_axesgrid.py @@ -10,7 +10,7 @@ from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable fig = plt.figure() -ax = fig.add_axes([0, 0, 1, 1]) +ax = fig.add_axes((0, 0, 1, 1)) ax.set_yticks([0.5], labels=["very long label"]) @@ -19,8 +19,8 @@ # %% fig = plt.figure() -ax1 = fig.add_axes([0, 0, 1, 0.5]) -ax2 = fig.add_axes([0, 0.5, 1, 0.5]) +ax1 = fig.add_axes((0, 0, 1, 0.5)) +ax2 = fig.add_axes((0, 0.5, 1, 0.5)) ax1.set_yticks([0.5], labels=["very long label"]) ax1.set_ylabel("Y label") @@ -33,7 +33,7 @@ # %% fig = plt.figure() -ax1 = fig.add_axes([0, 0, 1, 1]) +ax1 = fig.add_axes((0, 0, 1, 1)) divider = make_axes_locatable(ax1) ax2 = divider.append_axes("right", "100%", pad=0.3, sharey=ax1) diff --git a/galleries/examples/axisartist/demo_parasite_axes.py b/galleries/examples/axisartist/demo_parasite_axes.py index 8565ef455c7e..800b9be32ac8 100644 --- a/galleries/examples/axisartist/demo_parasite_axes.py +++ b/galleries/examples/axisartist/demo_parasite_axes.py @@ -24,7 +24,7 @@ fig = plt.figure() -host = fig.add_axes([0.15, 0.1, 0.65, 0.8], axes_class=HostAxes) +host = fig.add_axes((0.15, 0.1, 0.65, 0.8), axes_class=HostAxes) par1 = host.get_aux_axes(viewlim_mode=None, sharex=host) par2 = host.get_aux_axes(viewlim_mode=None, sharex=host) diff --git a/galleries/examples/event_handling/poly_editor.py b/galleries/examples/event_handling/poly_editor.py index f6efd8bb8446..9cc2e5373ae5 100644 --- a/galleries/examples/event_handling/poly_editor.py +++ b/galleries/examples/event_handling/poly_editor.py @@ -203,6 +203,6 @@ def on_mouse_move(self, event): p = PolygonInteractor(ax, poly) ax.set_title('Click and drag a point to move it') - ax.set_xlim((-2, 2)) - ax.set_ylim((-2, 2)) + ax.set_xlim(-2, 2) + ax.set_ylim(-2, 2) plt.show() diff --git a/galleries/examples/event_handling/pong_sgskip.py b/galleries/examples/event_handling/pong_sgskip.py index 583e51eacdc5..2c4c35a7cb35 100644 --- a/galleries/examples/event_handling/pong_sgskip.py +++ b/galleries/examples/event_handling/pong_sgskip.py @@ -134,9 +134,9 @@ def __init__(self, ax): # create the initial line self.ax = ax ax.xaxis.set_visible(False) - ax.set_xlim([0, 7]) + ax.set_xlim(0, 7) ax.yaxis.set_visible(False) - ax.set_ylim([-1, 1]) + ax.set_ylim(-1, 1) pad_a_x = 0 pad_b_x = .50 pad_a_y = pad_b_y = .30 diff --git a/galleries/examples/images_contours_and_fields/barcode_demo.py b/galleries/examples/images_contours_and_fields/barcode_demo.py index bdf48ca22531..5df58535650d 100644 --- a/galleries/examples/images_contours_and_fields/barcode_demo.py +++ b/galleries/examples/images_contours_and_fields/barcode_demo.py @@ -30,7 +30,7 @@ dpi = 100 fig = plt.figure(figsize=(len(code) * pixel_per_bar / dpi, 2), dpi=dpi) -ax = fig.add_axes([0, 0, 1, 1]) # span the whole figure +ax = fig.add_axes((0, 0, 1, 1)) # span the whole figure ax.set_axis_off() ax.imshow(code.reshape(1, -1), cmap='binary', aspect='auto', interpolation='nearest') diff --git a/galleries/examples/images_contours_and_fields/image_antialiasing.py b/galleries/examples/images_contours_and_fields/image_antialiasing.py index 7f223f6998f2..10f563875767 100644 --- a/galleries/examples/images_contours_and_fields/image_antialiasing.py +++ b/galleries/examples/images_contours_and_fields/image_antialiasing.py @@ -245,7 +245,7 @@ # may serve a 100x100 version of the image, which will be downsampled.) fig = plt.figure(figsize=(2, 2)) -ax = fig.add_axes([0, 0, 1, 1]) +ax = fig.add_axes((0, 0, 1, 1)) ax.imshow(aa[:400, :400], cmap='RdBu_r', interpolation='nearest') plt.show() # %% diff --git a/galleries/examples/images_contours_and_fields/image_exact_placement.py b/galleries/examples/images_contours_and_fields/image_exact_placement.py index a3b314a7c7c3..7c667dfed1af 100644 --- a/galleries/examples/images_contours_and_fields/image_exact_placement.py +++ b/galleries/examples/images_contours_and_fields/image_exact_placement.py @@ -134,13 +134,13 @@ def annotate_rect(ax): fig = plt.figure(figsize=(fig_width / dpi, fig_height / dpi), facecolor='aliceblue') # the position posA must be normalized by the figure width and height: -ax = fig.add_axes([posA[0] / fig_width, posA[1] / fig_height, - posA[2] / fig_width, posA[3] / fig_height]) +ax = fig.add_axes((posA[0] / fig_width, posA[1] / fig_height, + posA[2] / fig_width, posA[3] / fig_height)) ax.imshow(A, vmin=-1, vmax=1) annotate_rect(ax) -ax = fig.add_axes([posB[0] / fig_width, posB[1] / fig_height, - posB[2] / fig_width, posB[3] / fig_height]) +ax = fig.add_axes((posB[0] / fig_width, posB[1] / fig_height, + posB[2] / fig_width, posB[3] / fig_height)) ax.imshow(B, vmin=-1, vmax=1) plt.show() # %% diff --git a/galleries/examples/lines_bars_and_markers/eventcollection_demo.py b/galleries/examples/lines_bars_and_markers/eventcollection_demo.py index 1aa2fa622812..6854a13e0974 100644 --- a/galleries/examples/lines_bars_and_markers/eventcollection_demo.py +++ b/galleries/examples/lines_bars_and_markers/eventcollection_demo.py @@ -53,8 +53,8 @@ ax.add_collection(yevents2) # set the limits -ax.set_xlim([0, 1]) -ax.set_ylim([0, 1]) +ax.set_xlim(0, 1) +ax.set_ylim(0, 1) ax.set_title('line plot with data points') diff --git a/galleries/examples/lines_bars_and_markers/markevery_demo.py b/galleries/examples/lines_bars_and_markers/markevery_demo.py index 919e12cde952..da4da0ecf9f1 100644 --- a/galleries/examples/lines_bars_and_markers/markevery_demo.py +++ b/galleries/examples/lines_bars_and_markers/markevery_demo.py @@ -79,8 +79,8 @@ for ax, markevery in zip(axs.flat, cases): ax.set_title(f'markevery={markevery}') ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery) - ax.set_xlim((6, 6.7)) - ax.set_ylim((1.1, 1.7)) + ax.set_xlim(6, 6.7) + ax.set_ylim(1.1, 1.7) # %% # markevery on polar plots diff --git a/galleries/examples/misc/svg_filter_line.py b/galleries/examples/misc/svg_filter_line.py index c6adec093bee..dd97dc975eda 100644 --- a/galleries/examples/misc/svg_filter_line.py +++ b/galleries/examples/misc/svg_filter_line.py @@ -17,7 +17,7 @@ import matplotlib.transforms as mtransforms fig1 = plt.figure() -ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8]) +ax = fig1.add_axes((0.1, 0.1, 0.8, 0.8)) # draw lines l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-", diff --git a/galleries/examples/misc/svg_filter_pie.py b/galleries/examples/misc/svg_filter_pie.py index b823cc9670c9..b19867be9a2f 100644 --- a/galleries/examples/misc/svg_filter_pie.py +++ b/galleries/examples/misc/svg_filter_pie.py @@ -19,7 +19,7 @@ # make a square figure and Axes fig = plt.figure(figsize=(6, 6)) -ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) +ax = fig.add_axes((0.1, 0.1, 0.8, 0.8)) labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' fracs = [15, 30, 45, 10] diff --git a/galleries/examples/mplot3d/box3d.py b/galleries/examples/mplot3d/box3d.py index 807e3d496ec6..4d75c8bc2809 100644 --- a/galleries/examples/mplot3d/box3d.py +++ b/galleries/examples/mplot3d/box3d.py @@ -51,7 +51,7 @@ xmin, xmax = X.min(), X.max() ymin, ymax = Y.min(), Y.max() zmin, zmax = Z.min(), Z.max() -ax.set(xlim=[xmin, xmax], ylim=[ymin, ymax], zlim=[zmin, zmax]) +ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax), zlim=(zmin, zmax)) # Plot edges edges_kw = dict(color='0.4', linewidth=1, zorder=1e3) diff --git a/galleries/examples/scales/custom_scale.py b/galleries/examples/scales/custom_scale.py index 0eedb16ec5cf..1b6bdd6f3e09 100644 --- a/galleries/examples/scales/custom_scale.py +++ b/galleries/examples/scales/custom_scale.py @@ -22,7 +22,7 @@ * You want to override the default locators and formatters for the axis (``set_default_locators_and_formatters`` below). - * You want to limit the range of the the axis (``limit_range_for_scale`` below). + * You want to limit the range of the axis (``limit_range_for_scale`` below). """ diff --git a/galleries/examples/shapes_and_collections/hatch_demo.py b/galleries/examples/shapes_and_collections/hatch_demo.py index f2ca490c4e37..8d44dba5489b 100644 --- a/galleries/examples/shapes_and_collections/hatch_demo.py +++ b/galleries/examples/shapes_and_collections/hatch_demo.py @@ -41,8 +41,8 @@ hatch='*', facecolor='y')) axs['patches'].add_patch(Polygon([(10, 20), (30, 50), (50, 10)], hatch='\\/...', facecolor='g')) -axs['patches'].set_xlim([0, 40]) -axs['patches'].set_ylim([10, 60]) +axs['patches'].set_xlim(0, 40) +axs['patches'].set_ylim(10, 60) axs['patches'].set_aspect(1) plt.show() diff --git a/galleries/examples/showcase/anatomy.py b/galleries/examples/showcase/anatomy.py index b1fbde9c8d7b..798e4204cad3 100644 --- a/galleries/examples/showcase/anatomy.py +++ b/galleries/examples/showcase/anatomy.py @@ -27,7 +27,7 @@ Y3 = np.random.uniform(Y1, Y2, len(X)) fig = plt.figure(figsize=(7.5, 7.5)) -ax = fig.add_axes([0.2, 0.17, 0.68, 0.7], aspect=1) +ax = fig.add_axes((0.2, 0.17, 0.68, 0.7), aspect=1) ax.xaxis.set_major_locator(MultipleLocator(1.000)) ax.xaxis.set_minor_locator(AutoMinorLocator(4)) diff --git a/galleries/examples/showcase/firefox.py b/galleries/examples/showcase/firefox.py index 65682ccd7429..2026d253f6b6 100644 --- a/galleries/examples/showcase/firefox.py +++ b/galleries/examples/showcase/firefox.py @@ -48,7 +48,7 @@ def svg_parse(path): xmax, ymax = verts.max(axis=0) + 1 fig = plt.figure(figsize=(5, 5), facecolor="0.75") # gray background -ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect=1, +ax = fig.add_axes((0, 0, 1, 1), frameon=False, aspect=1, xlim=(xmin, xmax), # centering ylim=(ymax, ymin), # centering, upside down xticks=[], yticks=[]) # no ticks diff --git a/galleries/examples/showcase/mandelbrot.py b/galleries/examples/showcase/mandelbrot.py index ab40a061dc03..d8b7faf4c7b8 100644 --- a/galleries/examples/showcase/mandelbrot.py +++ b/galleries/examples/showcase/mandelbrot.py @@ -55,7 +55,7 @@ def mandelbrot_set(xmin, xmax, ymin, ymax, xn, yn, maxiter, horizon=2.0): width = 10 height = 10*yn/xn fig = plt.figure(figsize=(width, height), dpi=dpi) - ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect=1) + ax = fig.add_axes((0, 0, 1, 1), frameon=False, aspect=1) # Shaded rendering light = colors.LightSource(azdeg=315, altdeg=10) diff --git a/galleries/examples/showcase/xkcd.py b/galleries/examples/showcase/xkcd.py index 3d6d5418a13f..9b4de0a90f5b 100644 --- a/galleries/examples/showcase/xkcd.py +++ b/galleries/examples/showcase/xkcd.py @@ -19,7 +19,7 @@ ax.spines[['top', 'right']].set_visible(False) ax.set_xticks([]) ax.set_yticks([]) - ax.set_ylim([-30, 10]) + ax.set_ylim(-30, 10) data = np.ones(100) data[70:] -= np.arange(30) @@ -50,9 +50,9 @@ ax.xaxis.set_ticks_position('bottom') ax.set_xticks([0, 1]) ax.set_xticklabels(['CONFIRMED BY\nEXPERIMENT', 'REFUTED BY\nEXPERIMENT']) - ax.set_xlim([-0.5, 1.5]) + ax.set_xlim(-0.5, 1.5) ax.set_yticks([]) - ax.set_ylim([0, 110]) + ax.set_ylim(0, 110) ax.set_title("CLAIMS OF SUPERNATURAL POWERS") diff --git a/galleries/examples/specialty_plots/leftventricle_bullseye.py b/galleries/examples/specialty_plots/leftventricle_bullseye.py index 3ad02edbc630..285fcdaecc5e 100644 --- a/galleries/examples/specialty_plots/leftventricle_bullseye.py +++ b/galleries/examples/specialty_plots/leftventricle_bullseye.py @@ -55,7 +55,7 @@ def bullseye_plot(ax, data, seg_bold=None, cmap="viridis", norm=None): r = np.linspace(0.2, 1, 4) - ax.set(ylim=[0, 1], xticklabels=[], yticklabels=[]) + ax.set(ylim=(0, 1), xticklabels=[], yticklabels=[]) ax.grid(False) # Remove grid # Fill segments 1-6, 7-12, 13-16. diff --git a/galleries/examples/statistics/errorbar_limits.py b/galleries/examples/statistics/errorbar_limits.py index f1d26460d947..fde18327af83 100644 --- a/galleries/examples/statistics/errorbar_limits.py +++ b/galleries/examples/statistics/errorbar_limits.py @@ -71,7 +71,7 @@ linestyle='none') # tidy up the figure -ax.set_xlim((0, 5.5)) +ax.set_xlim(0, 5.5) ax.set_title('Errorbar upper and lower limits') plt.show() diff --git a/galleries/examples/subplots_axes_and_figures/axes_demo.py b/galleries/examples/subplots_axes_and_figures/axes_demo.py index 07f3ca2070c2..16db465449a4 100644 --- a/galleries/examples/subplots_axes_and_figures/axes_demo.py +++ b/galleries/examples/subplots_axes_and_figures/axes_demo.py @@ -33,12 +33,12 @@ main_ax.set_title('Gaussian colored noise') # this is an inset Axes over the main Axes -right_inset_ax = fig.add_axes([.65, .6, .2, .2], facecolor='k') +right_inset_ax = fig.add_axes((.65, .6, .2, .2), facecolor='k') right_inset_ax.hist(s, 400, density=True) right_inset_ax.set(title='Probability', xticks=[], yticks=[]) # this is another inset Axes over the main Axes -left_inset_ax = fig.add_axes([.2, .6, .2, .2], facecolor='k') +left_inset_ax = fig.add_axes((.2, .6, .2, .2), facecolor='k') left_inset_ax.plot(t[:len(r)], r) left_inset_ax.set(title='Impulse response', xlim=(0, .2), xticks=[], yticks=[]) diff --git a/galleries/examples/subplots_axes_and_figures/gridspec_nested.py b/galleries/examples/subplots_axes_and_figures/gridspec_nested.py index 025bdb1185a7..789cc0ae6b5b 100644 --- a/galleries/examples/subplots_axes_and_figures/gridspec_nested.py +++ b/galleries/examples/subplots_axes_and_figures/gridspec_nested.py @@ -1,4 +1,6 @@ """ +.. redirect-from:: /gallery/userdemo/demo_gridspec06 + ================ Nested Gridspecs ================ diff --git a/galleries/examples/text_labels_and_annotations/mathtext_examples.py b/galleries/examples/text_labels_and_annotations/mathtext_examples.py index f9f8e628e08b..cf395f0daf0e 100644 --- a/galleries/examples/text_labels_and_annotations/mathtext_examples.py +++ b/galleries/examples/text_labels_and_annotations/mathtext_examples.py @@ -61,7 +61,7 @@ def doall(): # Creating figure and axis. fig = plt.figure(figsize=(7, 7)) - ax = fig.add_axes([0.01, 0.01, 0.98, 0.90], + ax = fig.add_axes((0.01, 0.01, 0.98, 0.90), facecolor="white", frameon=True) ax.set_xlim(0, 1) ax.set_ylim(0, 1) diff --git a/galleries/examples/ticks/date_formatters_locators.py b/galleries/examples/ticks/date_formatters_locators.py index 39492168242f..8c3b24bb4c26 100644 --- a/galleries/examples/ticks/date_formatters_locators.py +++ b/galleries/examples/ticks/date_formatters_locators.py @@ -12,6 +12,7 @@ import matplotlib.pyplot as plt import numpy as np +# While these appear unused directly, they are used from eval'd strings. from matplotlib.dates import (FR, MO, MONTHLY, SA, SU, TH, TU, WE, AutoDateFormatter, AutoDateLocator, ConciseDateFormatter, DateFormatter, DayLocator, diff --git a/galleries/examples/ticks/fig_axes_customize_simple.py b/galleries/examples/ticks/fig_axes_customize_simple.py index 0dd85ec4bd93..07a569e3d31d 100644 --- a/galleries/examples/ticks/fig_axes_customize_simple.py +++ b/galleries/examples/ticks/fig_axes_customize_simple.py @@ -13,7 +13,7 @@ fig = plt.figure() fig.patch.set_facecolor('lightgoldenrodyellow') -ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4]) +ax1 = fig.add_axes((0.1, 0.3, 0.4, 0.4)) ax1.patch.set_facecolor('lightslategray') ax1.tick_params(axis='x', labelcolor='tab:red', labelrotation=45, labelsize=16) diff --git a/galleries/examples/user_interfaces/fourier_demo_wx_sgskip.py b/galleries/examples/user_interfaces/fourier_demo_wx_sgskip.py index f51917fda6b9..9e72b3745a40 100644 --- a/galleries/examples/user_interfaces/fourier_demo_wx_sgskip.py +++ b/galleries/examples/user_interfaces/fourier_demo_wx_sgskip.py @@ -194,10 +194,10 @@ def createPlots(self): self.subplot1.set_xlabel("frequency f", fontsize=8) self.subplot2.set_ylabel("Time Domain Waveform x(t)", fontsize=8) self.subplot2.set_xlabel("time t", fontsize=8) - self.subplot1.set_xlim([-6, 6]) - self.subplot1.set_ylim([0, 1]) - self.subplot2.set_xlim([-2, 2]) - self.subplot2.set_ylim([-2, 2]) + self.subplot1.set_xlim(-6, 6) + self.subplot1.set_ylim(0, 1) + self.subplot2.set_xlim(-2, 2) + self.subplot2.set_ylim(-2, 2) self.subplot1.text(0.05, .95, r'$X(f) = \mathcal{F}\{x(t)\}$', verticalalignment='top', diff --git a/galleries/examples/userdemo/README.txt b/galleries/examples/userdemo/README.txt deleted file mode 100644 index 7be351dc70dd..000000000000 --- a/galleries/examples/userdemo/README.txt +++ /dev/null @@ -1,4 +0,0 @@ -.. _userdemo: - -Userdemo -======== diff --git a/galleries/examples/userdemo/demo_gridspec06.py b/galleries/examples/userdemo/demo_gridspec06.py deleted file mode 100644 index c42224ce1e7b..000000000000 --- a/galleries/examples/userdemo/demo_gridspec06.py +++ /dev/null @@ -1,38 +0,0 @@ -r""" -================ -Nested GridSpecs -================ - -This example demonstrates the use of nested `.GridSpec`\s. -""" - -import matplotlib.pyplot as plt -import numpy as np - - -def squiggle_xy(a, b, c, d): - i = np.arange(0.0, 2*np.pi, 0.05) - return np.sin(i*a)*np.cos(i*b), np.sin(i*c)*np.cos(i*d) - - -fig = plt.figure(figsize=(8, 8)) -outer_grid = fig.add_gridspec(4, 4, wspace=0, hspace=0) - -for a in range(4): - for b in range(4): - # gridspec inside gridspec - inner_grid = outer_grid[a, b].subgridspec(3, 3, wspace=0, hspace=0) - axs = inner_grid.subplots() # Create all subplots for the inner grid. - for (c, d), ax in np.ndenumerate(axs): - ax.plot(*squiggle_xy(a + 1, b + 1, c + 1, d + 1)) - ax.set(xticks=[], yticks=[]) - -# show only the outside spines -for ax in fig.get_axes(): - ss = ax.get_subplotspec() - ax.spines.top.set_visible(ss.is_first_row()) - ax.spines.bottom.set_visible(ss.is_last_row()) - ax.spines.left.set_visible(ss.is_first_col()) - ax.spines.right.set_visible(ss.is_last_col()) - -plt.show() diff --git a/galleries/examples/widgets/buttons.py b/galleries/examples/widgets/buttons.py index 61249522c72c..2aef798399f4 100644 --- a/galleries/examples/widgets/buttons.py +++ b/galleries/examples/widgets/buttons.py @@ -41,8 +41,8 @@ def prev(self, event): plt.draw() callback = Index() -axprev = fig.add_axes([0.7, 0.05, 0.1, 0.075]) -axnext = fig.add_axes([0.81, 0.05, 0.1, 0.075]) +axprev = fig.add_axes((0.7, 0.05, 0.1, 0.075)) +axnext = fig.add_axes((0.81, 0.05, 0.1, 0.075)) bnext = Button(axnext, 'Next') bnext.on_clicked(callback.next) bprev = Button(axprev, 'Previous') diff --git a/galleries/examples/widgets/range_slider.py b/galleries/examples/widgets/range_slider.py index f1bed7431e39..d2f2d1554246 100644 --- a/galleries/examples/widgets/range_slider.py +++ b/galleries/examples/widgets/range_slider.py @@ -34,7 +34,7 @@ axs[1].set_title('Histogram of pixel intensities') # Create the RangeSlider -slider_ax = fig.add_axes([0.20, 0.1, 0.60, 0.03]) +slider_ax = fig.add_axes((0.20, 0.1, 0.60, 0.03)) slider = RangeSlider(slider_ax, "Threshold", img.min(), img.max()) # Create the Vertical lines on the histogram diff --git a/galleries/examples/widgets/slider_demo.py b/galleries/examples/widgets/slider_demo.py index 7dc47b9c7b6f..e56390c182a0 100644 --- a/galleries/examples/widgets/slider_demo.py +++ b/galleries/examples/widgets/slider_demo.py @@ -38,7 +38,7 @@ def f(t, amplitude, frequency): fig.subplots_adjust(left=0.25, bottom=0.25) # Make a horizontal slider to control the frequency. -axfreq = fig.add_axes([0.25, 0.1, 0.65, 0.03]) +axfreq = fig.add_axes((0.25, 0.1, 0.65, 0.03)) freq_slider = Slider( ax=axfreq, label='Frequency [Hz]', @@ -48,7 +48,7 @@ def f(t, amplitude, frequency): ) # Make a vertically oriented slider to control the amplitude -axamp = fig.add_axes([0.1, 0.25, 0.0225, 0.63]) +axamp = fig.add_axes((0.1, 0.25, 0.0225, 0.63)) amp_slider = Slider( ax=axamp, label="Amplitude", @@ -70,7 +70,7 @@ def update(val): amp_slider.on_changed(update) # Create a `matplotlib.widgets.Button` to reset the sliders to initial values. -resetax = fig.add_axes([0.8, 0.025, 0.1, 0.04]) +resetax = fig.add_axes((0.8, 0.025, 0.1, 0.04)) button = Button(resetax, 'Reset', hovercolor='0.975') diff --git a/galleries/examples/widgets/slider_snap_demo.py b/galleries/examples/widgets/slider_snap_demo.py index 953ffaf63672..5826be32fa07 100644 --- a/galleries/examples/widgets/slider_snap_demo.py +++ b/galleries/examples/widgets/slider_snap_demo.py @@ -30,8 +30,8 @@ fig.subplots_adjust(bottom=0.25) l, = ax.plot(t, s, lw=2) -ax_freq = fig.add_axes([0.25, 0.1, 0.65, 0.03]) -ax_amp = fig.add_axes([0.25, 0.15, 0.65, 0.03]) +ax_freq = fig.add_axes((0.25, 0.1, 0.65, 0.03)) +ax_amp = fig.add_axes((0.25, 0.15, 0.65, 0.03)) # define the values to use for snapping allowed_amplitudes = np.concatenate([np.linspace(.1, 5, 100), [6, 7, 8, 9]]) @@ -60,7 +60,7 @@ def update(val): sfreq.on_changed(update) samp.on_changed(update) -ax_reset = fig.add_axes([0.8, 0.025, 0.1, 0.04]) +ax_reset = fig.add_axes((0.8, 0.025, 0.1, 0.04)) button = Button(ax_reset, 'Reset', hovercolor='0.975') diff --git a/galleries/examples/widgets/textbox.py b/galleries/examples/widgets/textbox.py index d5f02b82a30b..2121ce8594ce 100644 --- a/galleries/examples/widgets/textbox.py +++ b/galleries/examples/widgets/textbox.py @@ -39,7 +39,7 @@ def submit(expression): plt.draw() -axbox = fig.add_axes([0.1, 0.05, 0.8, 0.075]) +axbox = fig.add_axes((0.1, 0.05, 0.8, 0.075)) text_box = TextBox(axbox, "Evaluate", textalignment="center") text_box.on_submit(submit) text_box.set_val("t ** 2") # Trigger `submit` with the initial string. diff --git a/galleries/tutorials/artists.py b/galleries/tutorials/artists.py index a258eb71d447..4f93f7c71a6e 100644 --- a/galleries/tutorials/artists.py +++ b/galleries/tutorials/artists.py @@ -70,7 +70,7 @@ class in the Matplotlib API, and the one you will be working with most coordinates:: fig2 = plt.figure() - ax2 = fig2.add_axes([0.15, 0.1, 0.7, 0.3]) + ax2 = fig2.add_axes((0.15, 0.1, 0.7, 0.3)) Continuing with our example:: @@ -134,7 +134,7 @@ class in the Matplotlib API, and the one you will be working with most # Fixing random state for reproducibility np.random.seed(19680801) -ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3]) +ax2 = fig.add_axes((0.15, 0.1, 0.7, 0.3)) n, bins, patches = ax2.hist(np.random.randn(1000), 50, facecolor='yellow', edgecolor='yellow') ax2.set_xlabel('Time [s]') @@ -295,7 +295,7 @@ class in the Matplotlib API, and the one you will be working with most # # In [157]: ax1 = fig.add_subplot(211) # -# In [158]: ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.3]) +# In [158]: ax2 = fig.add_axes((0.1, 0.1, 0.7, 0.3)) # # In [159]: ax1 # Out[159]: @@ -669,7 +669,7 @@ class in the Matplotlib API, and the one you will be working with most rect = fig.patch # a rectangle instance rect.set_facecolor('lightgoldenrodyellow') -ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4]) +ax1 = fig.add_axes((0.1, 0.3, 0.4, 0.4)) rect = ax1.patch rect.set_facecolor('lightslategray') diff --git a/galleries/tutorials/images.py b/galleries/tutorials/images.py index 0867f7b6d672..a7c474dab40b 100644 --- a/galleries/tutorials/images.py +++ b/galleries/tutorials/images.py @@ -33,8 +33,8 @@ In [1]: %matplotlib inline -This turns on inline plotting, where plot graphics will appear in your -notebook. This has important implications for interactivity. For inline plotting, commands in +This turns on inline plotting, where plot graphics will appear in your notebook. This +has important implications for interactivity. For inline plotting, commands in cells below the cell that outputs a plot will not affect the plot. For example, changing the colormap is not possible from cells below the cell that creates a plot. However, for other backends, such as Qt, that open a separate window, diff --git a/galleries/tutorials/lifecycle.py b/galleries/tutorials/lifecycle.py index 4aae4d6c1dbc..4c009f802cf4 100644 --- a/galleries/tutorials/lifecycle.py +++ b/galleries/tutorials/lifecycle.py @@ -169,7 +169,7 @@ ax.barh(group_names, group_data) labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') -ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', +ax.set(xlim=(-10000, 140000), xlabel='Total Revenue', ylabel='Company', title='Company Revenue') # %% @@ -187,7 +187,7 @@ ax.barh(group_names, group_data) labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') -ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', +ax.set(xlim=(-10000, 140000), xlabel='Total Revenue', ylabel='Company', title='Company Revenue') # %% @@ -220,7 +220,7 @@ def currency(x, pos): labels = ax.get_xticklabels() plt.setp(labels, rotation=45, horizontalalignment='right') -ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', +ax.set(xlim=(-10000, 140000), xlabel='Total Revenue', ylabel='Company', title='Company Revenue') ax.xaxis.set_major_formatter(currency) @@ -248,7 +248,7 @@ def currency(x, pos): # Now we move our title up since it's getting a little cramped ax.title.set(y=1.05) -ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', +ax.set(xlim=(-10000, 140000), xlabel='Total Revenue', ylabel='Company', title='Company Revenue') ax.xaxis.set_major_formatter(currency) ax.set_xticks([0, 25e3, 50e3, 75e3, 100e3, 125e3]) diff --git a/galleries/users_explain/animations/animations.py b/galleries/users_explain/animations/animations.py index a0669956ab81..dca49fc5228e 100644 --- a/galleries/users_explain/animations/animations.py +++ b/galleries/users_explain/animations/animations.py @@ -111,7 +111,7 @@ scat = ax.scatter(t[0], z[0], c="b", s=5, label=f'v0 = {v0} m/s') line2 = ax.plot(t[0], z2[0], label=f'v0 = {v02} m/s')[0] -ax.set(xlim=[0, 3], ylim=[-4, 10], xlabel='Time [s]', ylabel='Z [m]') +ax.set(xlim=(0, 3), ylim=(-4, 10), xlabel='Time [s]', ylabel='Z [m]') ax.legend() diff --git a/galleries/users_explain/artists/transforms_tutorial.py b/galleries/users_explain/artists/transforms_tutorial.py index f8a3e98e8077..3920fe886c7f 100644 --- a/galleries/users_explain/artists/transforms_tutorial.py +++ b/galleries/users_explain/artists/transforms_tutorial.py @@ -401,7 +401,7 @@ fig, ax = plt.subplots() xdata, ydata = (0.2, 0.7), (0.5, 0.5) ax.plot(xdata, ydata, "o") -ax.set_xlim((0, 1)) +ax.set_xlim(0, 1) trans = (fig.dpi_scale_trans + transforms.ScaledTranslation(xdata[0], ydata[0], ax.transData)) diff --git a/galleries/users_explain/axes/arranging_axes.py b/galleries/users_explain/axes/arranging_axes.py index bc537e15c12c..64879d4a696d 100644 --- a/galleries/users_explain/axes/arranging_axes.py +++ b/galleries/users_explain/axes/arranging_axes.py @@ -103,8 +103,8 @@ w, h = 4, 3 margin = 0.5 fig = plt.figure(figsize=(w, h), facecolor='lightblue') -ax = fig.add_axes([margin / w, margin / h, (w - 2 * margin) / w, - (h - 2 * margin) / h]) +ax = fig.add_axes((margin / w, margin / h, + (w - 2 * margin) / w, (h - 2 * margin) / h)) # %% diff --git a/galleries/users_explain/axes/axes_intro.rst b/galleries/users_explain/axes/axes_intro.rst index 16738d929056..bb3094495026 100644 --- a/galleries/users_explain/axes/axes_intro.rst +++ b/galleries/users_explain/axes/axes_intro.rst @@ -52,8 +52,8 @@ Axes are added using methods on `~.Figure` objects, or via the `~.pyplot` interf There are a number of other methods for adding Axes to a Figure: -* `.Figure.add_axes`: manually position an Axes. ``fig.add_axes([0, 0, 1, - 1])`` makes an Axes that fills the whole figure. +* `.Figure.add_axes`: manually position an Axes. ``fig.add_axes((0, 0, 1, 1))`` makes an + Axes that fills the whole figure. * `.pyplot.subplots` and `.Figure.subplots`: add a grid of Axes as in the example above. The pyplot version returns both the Figure object and an array of Axes. Note that ``fig, ax = plt.subplots()`` adds a single Axes to a Figure. @@ -143,7 +143,7 @@ Other important methods set the extent on the axes (`~.axes.Axes.set_xlim`, `~.a x = 2**np.cumsum(np.random.randn(200)) linesx = ax.plot(t, x) ax.set_yscale('log') - ax.set_xlim([20, 180]) + ax.set_xlim(20, 180) The Axes class also has helpers to deal with Axis ticks and their labels. Most straight-forward is `~.axes.Axes.set_xticks` and `~.axes.Axes.set_yticks` which manually set the tick locations and optionally their labels. Minor ticks can be toggled with `~.axes.Axes.minorticks_on` or `~.axes.Axes.minorticks_off`. diff --git a/galleries/users_explain/axes/axes_scales.py b/galleries/users_explain/axes/axes_scales.py index 6b163835070c..f901c012974a 100644 --- a/galleries/users_explain/axes/axes_scales.py +++ b/galleries/users_explain/axes/axes_scales.py @@ -171,7 +171,7 @@ def inverse(a): ax.set_yscale('function', functions=(forward, inverse)) ax.set_title('function: Mercator') ax.grid(True) -ax.set_xlim([0, 180]) +ax.set_xlim(0, 180) ax.yaxis.set_minor_formatter(NullFormatter()) ax.yaxis.set_major_locator(FixedLocator(np.arange(0, 90, 10))) diff --git a/galleries/users_explain/axes/legend_guide.py b/galleries/users_explain/axes/legend_guide.py index 5da3ceafe387..ec0468fe172d 100644 --- a/galleries/users_explain/axes/legend_guide.py +++ b/galleries/users_explain/axes/legend_guide.py @@ -1,7 +1,7 @@ """ .. redirect-from:: /tutorials/intermediate/legend_guide -.. redirect-from:: /galleries/examples/userdemo/simple_legend01 -.. redirect-from:: /galleries/examples/userdemo/simple_legend02 +.. redirect-from:: /gallery/userdemo/simple_legend01 +.. redirect-from:: /gallery/userdemo/simple_legend02 .. _legend_guide: diff --git a/galleries/users_explain/colors/colors.py b/galleries/users_explain/colors/colors.py index c91a5fcb0dbe..97a281bf1977 100644 --- a/galleries/users_explain/colors/colors.py +++ b/galleries/users_explain/colors/colors.py @@ -197,7 +197,7 @@ def demo(sty): if f'xkcd:{name}' in mcolors.XKCD_COLORS} fig = plt.figure(figsize=[9, 5]) -ax = fig.add_axes([0, 0, 1, 1]) +ax = fig.add_axes((0, 0, 1, 1)) n_groups = 3 n_rows = len(overlap) // n_groups + 1 diff --git a/galleries/users_explain/text/text_props.py b/galleries/users_explain/text/text_props.py index c5ae22c02d38..fb67421fd880 100644 --- a/galleries/users_explain/text/text_props.py +++ b/galleries/users_explain/text/text_props.py @@ -75,7 +75,7 @@ top = bottom + height fig = plt.figure() -ax = fig.add_axes([0, 0, 1, 1]) +ax = fig.add_axes((0, 0, 1, 1)) # axes coordinates: (0, 0) is bottom left and (1, 1) is upper right p = patches.Rectangle( diff --git a/galleries/users_explain/toolkits/axisartist.rst b/galleries/users_explain/toolkits/axisartist.rst index eff2b575a63f..7ff0897f23d8 100644 --- a/galleries/users_explain/toolkits/axisartist.rst +++ b/galleries/users_explain/toolkits/axisartist.rst @@ -50,7 +50,7 @@ To create an Axes, :: import mpl_toolkits.axisartist as AA fig = plt.figure() - fig.add_axes([0.1, 0.1, 0.8, 0.8], axes_class=AA.Axes) + fig.add_axes((0.1, 0.1, 0.8, 0.8), axes_class=AA.Axes) or to create a subplot :: diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 9abc6c5a84dd..e98e8ea07502 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -400,12 +400,15 @@ def impl(args, regex, min_ver=None, ignore_exit_code=False): try: output = subprocess.check_output( args, stderr=subprocess.STDOUT, - text=True, errors="replace") + text=True, errors="replace", timeout=30) except subprocess.CalledProcessError as _cpe: if ignore_exit_code: output = _cpe.output else: raise ExecutableNotFoundError(str(_cpe)) from _cpe + except subprocess.TimeoutExpired as _te: + msg = f"Timed out running {cbook._pformat_subprocess(args)}" + raise ExecutableNotFoundError(msg) from _te except OSError as _ose: raise ExecutableNotFoundError(str(_ose)) from _ose match = re.search(regex, output) @@ -799,13 +802,13 @@ def find_all(self, pattern): """ pattern_re = re.compile(pattern) - return RcParams((key, value) - for key, value in self.items() - if pattern_re.search(key)) + return self.__class__( + (key, value) for key, value in self.items() if pattern_re.search(key) + ) def copy(self): """Copy this RcParams instance.""" - rccopy = RcParams() + rccopy = self.__class__() for k in self: # Skip deprecations and revalidation. rccopy._set(k, self._get(k)) return rccopy @@ -1309,11 +1312,18 @@ def is_interactive(): return rcParams['interactive'] -def _val_or_rc(val, rc_name): +def _val_or_rc(val, *rc_names): """ - If *val* is None, return ``mpl.rcParams[rc_name]``, otherwise return val. + If *val* is None, the first not-None value in ``mpl.rcParams[rc_names[i]]``. + If all are None returns ``mpl.rcParams[rc_names[-1]]``. """ - return val if val is not None else rcParams[rc_name] + if val is not None: + return val + + for rc_name in rc_names[:-1]: + if rcParams[rc_name] is not None: + return rcParams[rc_name] + return rcParams[rc_names[-1]] def _init_tests(): diff --git a/lib/matplotlib/_enums.py b/lib/matplotlib/_enums.py index 75a09b7b5d8c..d85c5c5f03db 100644 --- a/lib/matplotlib/_enums.py +++ b/lib/matplotlib/_enums.py @@ -151,7 +151,7 @@ def demo(): import matplotlib.pyplot as plt fig = plt.figure(figsize=(4, 1.2)) - ax = fig.add_axes([0, 0, 1, 0.8]) + ax = fig.add_axes((0, 0, 1, 0.8)) ax.set_title('Cap style') for x, style in enumerate(['butt', 'round', 'projecting']): diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index c6ff7702d992..8756cb0c1439 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -1,5 +1,6 @@ import abc import base64 +import collections import contextlib from io import BytesIO, TextIOWrapper import itertools @@ -1708,13 +1709,13 @@ def iter_frames(frames=frames): self._cache_frame_data = cache_frame_data # Needs to be initialized so the draw functions work without checking - self._save_seq = [] + self._save_seq = collections.deque([], self._save_count) super().__init__(fig, **kwargs) # Need to reset the saved seq, since right now it will contain data # for a single frame from init, which is not what we want. - self._save_seq = [] + self._save_seq.clear() def new_frame_seq(self): # Use the generating function to generate a new frame sequence @@ -1727,8 +1728,7 @@ def new_saved_frame_seq(self): if self._save_seq: # While iterating we are going to update _save_seq # so make a copy to safely iterate over - self._old_saved_seq = list(self._save_seq) - return iter(self._old_saved_seq) + return iter([*self._save_seq]) else: if self._save_count is None: frame_seq = self.new_frame_seq() @@ -1773,13 +1773,12 @@ def _init_draw(self): 'return a sequence of Artist objects.') for a in self._drawn_artists: a.set_animated(self._blit) - self._save_seq = [] + self._save_seq.clear() def _draw_frame(self, framedata): if self._cache_frame_data: # Save the data for potential saving of movies. self._save_seq.append(framedata) - self._save_seq = self._save_seq[-self._save_count:] # Call the func with framedata and args. If blitting is desired, # func needs to return a sequence of any artists that were modified. diff --git a/lib/matplotlib/artist.py b/lib/matplotlib/artist.py index fd35b312835a..eaaae43e283a 100644 --- a/lib/matplotlib/artist.py +++ b/lib/matplotlib/artist.py @@ -321,13 +321,12 @@ def stale(self, val): def get_window_extent(self, renderer=None): """ - Get the artist's bounding box in display space. + Get the artist's bounding box in display space, ignoring clipping. The bounding box's width and height are non-negative. - Subclasses should override for inclusion in the bounding box - "tight" calculation. Default is to return an empty bounding - box at 0, 0. + Subclasses should override for inclusion in the bounding box "tight" + calculation. Default is to return an empty bounding box at 0, 0. .. warning:: @@ -341,28 +340,40 @@ def get_window_extent(self, renderer=None): screen render incorrectly when saved to file. To get accurate results you may need to manually call - `matplotlib.figure.Figure.savefig` or - `matplotlib.figure.Figure.draw_without_rendering` to have Matplotlib - compute the rendered size. + `~.Figure.savefig` or `~.Figure.draw_without_rendering` to have + Matplotlib compute the rendered size. + Parameters + ---------- + renderer : `~matplotlib.backend_bases.RendererBase`, optional + Renderer used to draw the figure (i.e. ``fig.canvas.get_renderer()``). + + See Also + -------- + .Artist.get_tightbbox : + Get the artist bounding box, taking clipping into account. """ return Bbox([[0, 0], [0, 0]]) def get_tightbbox(self, renderer=None): """ - Like `.Artist.get_window_extent`, but includes any clipping. + Get the artist's bounding box in display space, taking clipping into account. Parameters ---------- - renderer : `~matplotlib.backend_bases.RendererBase` subclass, optional - renderer that will be used to draw the figures (i.e. - ``fig.canvas.get_renderer()``) + renderer : `~matplotlib.backend_bases.RendererBase`, optional + Renderer used to draw the figure (i.e. ``fig.canvas.get_renderer()``). Returns ------- `.Bbox` or None - The enclosing bounding box (in figure pixel coordinates). - Returns None if clipping results in no intersection. + The enclosing bounding box (in figure pixel coordinates), or None + if clipping results in no intersection. + + See Also + -------- + .Artist.get_window_extent : + Get the artist bounding box, ignoring clipping. """ bbox = self.get_window_extent(renderer) if self.get_clip_on(): diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index b4ed7ae22d35..8ac300296538 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -3436,6 +3436,9 @@ def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0, else: # horizontal heads, locs = self._process_unit_info([("x", heads), ("y", locs)]) + heads = cbook._check_1d(heads) + locs = cbook._check_1d(locs) + # resolve line format if linefmt is None: linefmt = args[0] if len(args) > 0 else "C0-" diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 15f8e97b449f..87d42b4d3014 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -2185,9 +2185,9 @@ def axis(self, arg=None, /, *, emit=True, **kwargs): xlim = self.get_xlim() ylim = self.get_ylim() edge_size = max(np.diff(xlim), np.diff(ylim))[0] - self.set_xlim([xlim[0], xlim[0] + edge_size], + self.set_xlim(xlim[0], xlim[0] + edge_size, emit=emit, auto=False) - self.set_ylim([ylim[0], ylim[0] + edge_size], + self.set_ylim(ylim[0], ylim[0] + edge_size, emit=emit, auto=False) else: raise ValueError(f"Unrecognized string {arg!r} to axis; " @@ -4749,14 +4749,25 @@ def label_outer(self, remove_inner_ticks=False): self._label_outer_yaxis(skip_non_rectangular_axes=False, remove_inner_ticks=remove_inner_ticks) + def _get_subplotspec_with_optional_colorbar(self): + """ + Return the subplotspec for this Axes, except that if this Axes has been + moved to a subgridspec to make room for a colorbar, then return the + subplotspec that encloses both this Axes and the colorbar Axes. + """ + ss = self.get_subplotspec() + if any(cax.get_subplotspec() for cax in self._colorbars): + ss = ss.get_gridspec()._subplot_spec + return ss + def _label_outer_xaxis(self, *, skip_non_rectangular_axes, remove_inner_ticks=False): # see documentation in label_outer. if skip_non_rectangular_axes and not isinstance(self.patch, mpl.patches.Rectangle): return - ss = self.get_subplotspec() - if not ss: + ss = self._get_subplotspec_with_optional_colorbar() + if ss is None: return label_position = self.xaxis.get_label_position() if not ss.is_first_row(): # Remove top label/ticklabels/offsettext. @@ -4782,8 +4793,8 @@ def _label_outer_yaxis(self, *, skip_non_rectangular_axes, if skip_non_rectangular_axes and not isinstance(self.patch, mpl.patches.Rectangle): return - ss = self.get_subplotspec() - if not ss: + ss = self._get_subplotspec_with_optional_colorbar() + if ss is None: return label_position = self.yaxis.get_label_position() if not ss.is_first_col(): # Remove left label/ticklabels/offsettext. diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index 19096fc29d3e..fafdf92017f2 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -125,16 +125,33 @@ def __init__( zorder = mlines.Line2D.zorder self._zorder = zorder - grid_color = mpl._val_or_rc(grid_color, "grid.color") - grid_linestyle = mpl._val_or_rc(grid_linestyle, "grid.linestyle") - grid_linewidth = mpl._val_or_rc(grid_linewidth, "grid.linewidth") + grid_color = mpl._val_or_rc( + grid_color, + f"grid.{major_minor}.color", + "grid.color", + ) + grid_linestyle = mpl._val_or_rc( + grid_linestyle, + f"grid.{major_minor}.linestyle", + "grid.linestyle", + ) + grid_linewidth = mpl._val_or_rc( + grid_linewidth, + f"grid.{major_minor}.linewidth", + "grid.linewidth", + ) if grid_alpha is None and not mcolors._has_alpha_channel(grid_color): # alpha precedence: kwarg > color alpha > rcParams['grid.alpha'] # Note: only resolve to rcParams if the color does not have alpha # otherwise `grid(color=(1, 1, 1, 0.5))` would work like # grid(color=(1, 1, 1, 0.5), alpha=rcParams['grid.alpha']) # so the that the rcParams default would override color alpha. - grid_alpha = mpl.rcParams["grid.alpha"] + grid_alpha = mpl._val_or_rc( + # grid_alpha is None so we can use the first key + mpl.rcParams[f"grid.{major_minor}.alpha"], + "grid.alpha", + ) + grid_kw = {k[5:]: v for k, v in kwargs.items() if k != "rotation_mode"} self.tick1line = mlines.Line2D( diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py index 527d8c010710..626852f2aa34 100644 --- a/lib/matplotlib/backend_bases.py +++ b/lib/matplotlib/backend_bases.py @@ -1619,7 +1619,8 @@ def _allow_interrupt(prepare_notifier, handle_sigint): If SIGINT was indeed caught, after exiting the on_signal() function the interpreter reacts to the signal according to the handler function which had been set up by a signal.signal() call; here, we arrange to call the - backend-specific *handle_sigint* function. Finally, we call the old SIGINT + backend-specific *handle_sigint* function, passing the notifier object + as returned by prepare_notifier(). Finally, we call the old SIGINT handler with the same arguments that were given to our custom handler. We do this only if the old handler for SIGINT was not None, which means @@ -1629,7 +1630,7 @@ def _allow_interrupt(prepare_notifier, handle_sigint): Parameters ---------- prepare_notifier : Callable[[socket.socket], object] - handle_sigint : Callable[[], object] + handle_sigint : Callable[[object], object] """ old_sigint_handler = signal.getsignal(signal.SIGINT) @@ -1645,9 +1646,10 @@ def _allow_interrupt(prepare_notifier, handle_sigint): notifier = prepare_notifier(rsock) def save_args_and_handle_sigint(*args): - nonlocal handler_args + nonlocal handler_args, notifier handler_args = args - handle_sigint() + handle_sigint(notifier) + notifier = None signal.signal(signal.SIGINT, save_args_and_handle_sigint) try: diff --git a/lib/matplotlib/backends/_backend_tk.py b/lib/matplotlib/backends/_backend_tk.py index 0bbff1379ffa..eaf868fd8bec 100644 --- a/lib/matplotlib/backends/_backend_tk.py +++ b/lib/matplotlib/backends/_backend_tk.py @@ -775,7 +775,7 @@ def _recolor_icon(image, color): image_data = np.asarray(image).copy() black_mask = (image_data[..., :3] == 0).all(axis=-1) image_data[black_mask, :3] = color - return Image.fromarray(image_data, mode="RGBA") + return Image.fromarray(image_data) # Use the high-resolution (48x48 px) icon if it exists and is needed with Image.open(path_large if (size > 24 and path_large.exists()) diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index bfdcafc8842b..ff351e301176 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -699,7 +699,7 @@ def __init__(self, filename, metadata=None): self._internal_font_seq = (Name(f'F{i}') for i in itertools.count(1)) self._fontNames = {} # maps filenames to internal font names - self._dviFontInfo = {} # maps dvi font names to embedding information + self._dviFontInfo = {} # maps pdf names to dvifonts self._character_tracker = _backend_pdf_ps.CharacterTracker() self.alphaStates = {} # maps alpha values to graphics state objects @@ -742,9 +742,30 @@ def __init__(self, filename, metadata=None): self.writeObject(self.resourceObject, resources) fontNames = _api.deprecated("3.11")(property(lambda self: self._fontNames)) - dviFontInfo = _api.deprecated("3.11")(property(lambda self: self._dviFontInfo)) type1Descriptors = _api.deprecated("3.11")(property(lambda _: {})) + @_api.deprecated("3.11") + @property + def dviFontInfo(self): + d = {} + tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map')) + for pdfname, dvifont in self._dviFontInfo.items(): + psfont = tex_font_map[dvifont.texname] + if psfont.filename is None: + raise ValueError( + "No usable font file found for {} (TeX: {}); " + "the font may lack a Type-1 version" + .format(psfont.psname, dvifont.texname)) + d[dvifont.texname] = types.SimpleNamespace( + dvifont=dvifont, + pdfname=pdfname, + fontfile=psfont.filename, + basefont=psfont.psname, + encodingfile=psfont.encoding, + effects=psfont.effects, + ) + return d + def newPage(self, width, height): self.endStream() @@ -916,39 +937,19 @@ def fontName(self, fontprop): def dviFontName(self, dvifont): """ Given a dvi font object, return a name suitable for Op.selectfont. - This registers the font information internally (in ``_dviFontInfo``) if - not yet registered. - """ - - dvi_info = self._dviFontInfo.get(dvifont.texname) - if dvi_info is not None: - return dvi_info.pdfname - - tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map')) - psfont = tex_font_map[dvifont.texname] - if psfont.filename is None: - raise ValueError( - "No usable font file found for {} (TeX: {}); " - "the font may lack a Type-1 version" - .format(psfont.psname, dvifont.texname)) - pdfname = next(self._internal_font_seq) + Register the font internally (in ``_dviFontInfo``) if not yet registered. + """ + pdfname = Name(f"F-{dvifont.texname.decode('ascii')}") _log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname) - self._dviFontInfo[dvifont.texname] = types.SimpleNamespace( - dvifont=dvifont, - pdfname=pdfname, - fontfile=psfont.filename, - basefont=psfont.psname, - encodingfile=psfont.encoding, - effects=psfont.effects) - return pdfname + self._dviFontInfo[pdfname] = dvifont + return Name(pdfname) def writeFonts(self): fonts = {} - for dviname, info in sorted(self._dviFontInfo.items()): - Fx = info.pdfname - _log.debug('Embedding Type-1 font %s from dvi.', dviname) - fonts[Fx] = self._embedTeXFont(info) + for pdfname, dvifont in sorted(self._dviFontInfo.items()): + _log.debug('Embedding Type-1 font %s from dvi.', dvifont.texname) + fonts[pdfname] = self._embedTeXFont(dvifont) for filename in sorted(self._fontNames): Fx = self._fontNames[filename] _log.debug('Embedding font %s.', filename) @@ -976,9 +977,14 @@ def _write_afm_font(self, filename): self.writeObject(fontdictObject, fontdict) return fontdictObject - def _embedTeXFont(self, fontinfo): - _log.debug('Embedding TeX font %s - fontinfo=%s', - fontinfo.dvifont.texname, fontinfo.__dict__) + def _embedTeXFont(self, dvifont): + tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map')) + psfont = tex_font_map[dvifont.texname] + if psfont.filename is None: + raise ValueError( + "No usable font file found for {} (TeX: {}); " + "the font may lack a Type-1 version" + .format(psfont.psname, dvifont.texname)) # The font dictionary is the top-level object describing a font fontdictObject = self.reserveObject('font dictionary') @@ -988,17 +994,17 @@ def _embedTeXFont(self, fontinfo): } # Read the font file and apply any encoding changes and effects - t1font = _type1font.Type1Font(fontinfo.fontfile) - if fontinfo.encodingfile is not None: + t1font = _type1font.Type1Font(psfont.filename) + if psfont.encoding is not None: t1font = t1font.with_encoding( - {i: c for i, c in enumerate(dviread._parse_enc(fontinfo.encodingfile))} + {i: c for i, c in enumerate(dviread._parse_enc(psfont.encoding))} ) - if fontinfo.effects: - t1font = t1font.transform(fontinfo.effects) + if psfont.effects: + t1font = t1font.transform(psfont.effects) # Reduce the font to only the glyphs used in the document, get the encoding # for that subset, and compute various properties based on the encoding. - chars = frozenset(self._character_tracker.used[fontinfo.dvifont.fname]) + chars = frozenset(self._character_tracker.used[dvifont.fname]) t1font = t1font.subset(chars, self._get_subset_prefix(chars)) fontdict['BaseFont'] = Name(t1font.prop['FontName']) # createType1Descriptor writes the font data as a side effect @@ -1009,17 +1015,15 @@ def _embedTeXFont(self, fontinfo): lc = fontdict['LastChar'] = max(encoding.keys(), default=255) # Convert glyph widths from TeX 12.20 fixed point to 1/1000 text space units - tfm = fontinfo.dvifont._tfm + tfm = dvifont._tfm widths = [(1000 * metrics.tex_width) >> 20 if (metrics := tfm.get_metrics(char)) else 0 for char in range(fc, lc + 1)] fontdict['Widths'] = widthsObject = self.reserveObject('glyph widths') self.writeObject(widthsObject, widths) - self.writeObject(fontdictObject, fontdict) return fontdictObject - def _generate_encoding(self, encoding): prev = -2 result = [] @@ -1033,7 +1037,6 @@ def _generate_encoding(self, encoding): 'Differences': result } - @_api.delete_parameter("3.11", "fontfile") def createType1Descriptor(self, t1font, fontfile=None): # Create and write the font descriptor and the font file @@ -1759,7 +1762,7 @@ def _writeImg(self, data, id, smask=None): data[:, :, 2]) indices = np.argsort(palette24).astype(np.uint8) rgb8 = indices[np.searchsorted(palette24, rgb24, sorter=indices)] - img = Image.fromarray(rgb8, mode='P') + img = Image.fromarray(rgb8).convert("P") img.putpalette(palette) png_data, bit_depth, palette = self._writePng(img) if bit_depth is None or palette is None: diff --git a/lib/matplotlib/backends/backend_qt.py b/lib/matplotlib/backends/backend_qt.py index 5cde4866cad7..9089e982cea6 100644 --- a/lib/matplotlib/backends/backend_qt.py +++ b/lib/matplotlib/backends/backend_qt.py @@ -169,9 +169,14 @@ def _may_clear_sock(): # be forgiving about reading an empty socket. pass - return sn # Actually keep the notifier alive. - - def handle_sigint(): + # We return the QSocketNotifier so that the caller holds a reference, and we + # also explicitly clean it up in handle_sigint(). Without doing both, deletion + # of the socket notifier can happen prematurely or not at all. + return sn + + def handle_sigint(sn): + sn.deleteLater() + QtCore.QCoreApplication.sendPostedEvents(sn, QtCore.QEvent.Type.DeferredDelete) if hasattr(qapp_or_eventloop, 'closeAllWindows'): qapp_or_eventloop.closeAllWindows() qapp_or_eventloop.quit() diff --git a/lib/matplotlib/backends/web_backend/nbagg_uat.ipynb b/lib/matplotlib/backends/web_backend/nbagg_uat.ipynb index e9fc62bc2883..0513fee2b54c 100644 --- a/lib/matplotlib/backends/web_backend/nbagg_uat.ipynb +++ b/lib/matplotlib/backends/web_backend/nbagg_uat.ipynb @@ -309,7 +309,7 @@ "metadata": {}, "outputs": [], "source": [ - "from matplotlib.backends.backend_nbagg import new_figure_manager,show\n", + "from matplotlib.backends.backend_nbagg import new_figure_manager\n", "\n", "manager = new_figure_manager(1000)\n", "fig = manager.canvas.figure\n", @@ -341,15 +341,18 @@ "x = np.arange(0, 2*np.pi, 0.01) # x-array\n", "line, = ax.plot(x, np.sin(x))\n", "\n", + "\n", "def animate(i):\n", " line.set_ydata(np.sin(x+i/10.0)) # update the data\n", " return line,\n", "\n", - "#Init only required for blitting to give a clean slate.\n", + "\n", + "# Init only required for blitting to give a clean slate.\n", "def init():\n", " line.set_ydata(np.ma.array(x, mask=True))\n", " return line,\n", "\n", + "\n", "ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,\n", " interval=100., blit=True)\n", "plt.show()" @@ -405,6 +408,8 @@ "ln, = ax.plot(x,y)\n", "evt = []\n", "colors = iter(itertools.cycle(['r', 'g', 'b', 'k', 'c']))\n", + "\n", + "\n", "def on_event(event):\n", " if event.name.startswith('key'):\n", " fig.suptitle('%s: %s' % (event.name, event.key))\n", @@ -417,6 +422,7 @@ " fig.canvas.draw()\n", " fig.canvas.draw_idle()\n", "\n", + "\n", "fig.canvas.mpl_connect('button_press_event', on_event)\n", "fig.canvas.mpl_connect('button_release_event', on_event)\n", "fig.canvas.mpl_connect('scroll_event', on_event)\n", @@ -448,10 +454,12 @@ "fig, ax = plt.subplots()\n", "text = ax.text(0.5, 0.5, '', ha='center')\n", "\n", + "\n", "def update(text):\n", " text.set(text=time.ctime())\n", " text.axes.figure.canvas.draw()\n", - " \n", + "\n", + "\n", "timer = fig.canvas.new_timer(500, [(update, [text], {})])\n", "timer.start()\n", "plt.show()" @@ -471,7 +479,7 @@ "outputs": [], "source": [ "fig, ax = plt.subplots()\n", - "text = ax.text(0.5, 0.5, '', ha='center') \n", + "text = ax.text(0.5, 0.5, '', ha='center')\n", "timer = fig.canvas.new_timer(500, [(update, [text], {})])\n", "\n", "timer.single_shot = True\n", @@ -578,11 +586,12 @@ "cnt = itertools.count()\n", "bg = None\n", "\n", + "\n", "def onclick_handle(event):\n", " \"\"\"Should draw elevating green line on each mouse click\"\"\"\n", " global bg\n", " if bg is None:\n", - " bg = ax.figure.canvas.copy_from_bbox(ax.bbox) \n", + " bg = ax.figure.canvas.copy_from_bbox(ax.bbox)\n", " ax.figure.canvas.restore_region(bg)\n", "\n", " cur_y = (next(cnt) % 10) * 0.1\n", @@ -590,6 +599,7 @@ " ax.draw_artist(ln)\n", " ax.figure.canvas.blit(ax.bbox)\n", "\n", + "\n", "fig, ax = plt.subplots()\n", "ax.plot([0, 1], [0, 1], 'r')\n", "ln, = ax.plot([0, 1], [0, 0], 'g', animated=True)\n", @@ -598,13 +608,6 @@ "\n", "ax.figure.canvas.mpl_connect('button_press_event', onclick_handle)" ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] } ], "metadata": { diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 19bdbe605d88..4348f02cfc34 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -1455,8 +1455,7 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15, cax = fig.add_axes(pbcb, label="") for a in parents: - # tell the parent it has a colorbar - a._colorbars += [cax] + a._colorbars.append(cax) # tell the parent it has a colorbar cax._colorbar_info = dict( parents=parents, location=location, @@ -1549,6 +1548,7 @@ def make_axes_gridspec(parent, *, location=None, orientation=None, fig = parent.get_figure() cax = fig.add_subplot(ss_cb, label="") + parent._colorbars.append(cax) # tell the parent it has a colorbar cax.set_anchor(anchor) cax.set_box_aspect(aspect) cax.set_aspect('auto') diff --git a/lib/matplotlib/colorizer.py b/lib/matplotlib/colorizer.py index b4223f389804..92a6e4ea4c4f 100644 --- a/lib/matplotlib/colorizer.py +++ b/lib/matplotlib/colorizer.py @@ -90,7 +90,7 @@ def norm(self): @norm.setter def norm(self, norm): - _api.check_isinstance((colors.Normalize, str, None), norm=norm) + _api.check_isinstance((colors.Norm, str, None), norm=norm) if norm is None: norm = colors.Normalize() elif isinstance(norm, str): diff --git a/lib/matplotlib/colorizer.pyi b/lib/matplotlib/colorizer.pyi index f35ebe5295e4..9a5a73415d83 100644 --- a/lib/matplotlib/colorizer.pyi +++ b/lib/matplotlib/colorizer.pyi @@ -10,12 +10,12 @@ class Colorizer: def __init__( self, cmap: str | colors.Colormap | None = ..., - norm: str | colors.Normalize | None = ..., + norm: str | colors.Norm | None = ..., ) -> None: ... @property - def norm(self) -> colors.Normalize: ... + def norm(self) -> colors.Norm: ... @norm.setter - def norm(self, norm: colors.Normalize | str | None) -> None: ... + def norm(self, norm: colors.Norm | str | None) -> None: ... def to_rgba( self, x: np.ndarray, @@ -63,10 +63,10 @@ class _ColorizerInterface: def get_cmap(self) -> colors.Colormap: ... def set_cmap(self, cmap: str | colors.Colormap) -> None: ... @property - def norm(self) -> colors.Normalize: ... + def norm(self) -> colors.Norm: ... @norm.setter - def norm(self, norm: colors.Normalize | str | None) -> None: ... - def set_norm(self, norm: colors.Normalize | str | None) -> None: ... + def norm(self, norm: colors.Norm | str | None) -> None: ... + def set_norm(self, norm: colors.Norm | str | None) -> None: ... def autoscale(self) -> None: ... def autoscale_None(self) -> None: ... @@ -74,7 +74,7 @@ class _ColorizerInterface: class _ScalarMappable(_ColorizerInterface): def __init__( self, - norm: colors.Normalize | None = ..., + norm: colors.Norm | None = ..., cmap: str | colors.Colormap | None = ..., *, colorizer: Colorizer | None = ..., diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index 254e2c1a203b..a09b4f3d4f5c 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -41,6 +41,7 @@ import base64 from collections.abc import Sequence, Mapping +from abc import ABC, abstractmethod import functools import importlib import inspect @@ -2257,7 +2258,87 @@ def _init(self): self._isinit = True -class Normalize: +class Norm(ABC): + """ + Abstract base class for normalizations. + + Subclasses include `Normalize` which maps from a scalar to + a scalar. However, this class makes no such requirement, and subclasses may + support the normalization of multiple variates simultaneously, with + separate normalization for each variate. + """ + + def __init__(self): + self.callbacks = cbook.CallbackRegistry(signals=["changed"]) + + @property + @abstractmethod + def vmin(self): + """Lower limit of the input data interval; maps to 0.""" + pass + + @property + @abstractmethod + def vmax(self): + """Upper limit of the input data interval; maps to 1.""" + pass + + @property + @abstractmethod + def clip(self): + """ + Determines the behavior for mapping values outside the range ``[vmin, vmax]``. + + See the *clip* parameter in `.Normalize`. + """ + pass + + @abstractmethod + def __call__(self, value, clip=None): + """ + Normalize the data and return the normalized data. + + Parameters + ---------- + value + Data to normalize. + clip : bool, optional + See the description of the parameter *clip* in `.Normalize`. + + If ``None``, defaults to ``self.clip`` (which defaults to + ``False``). + + Notes + ----- + If not already initialized, ``self.vmin`` and ``self.vmax`` are + initialized using ``self.autoscale_None(value)``. + """ + pass + + @abstractmethod + def autoscale(self, A): + """Set *vmin*, *vmax* to min, max of *A*.""" + pass + + @abstractmethod + def autoscale_None(self, A): + """If *vmin* or *vmax* are not set, use the min/max of *A* to set them.""" + pass + + @abstractmethod + def scaled(self): + """Return whether *vmin* and *vmax* are both set.""" + pass + + def _changed(self): + """ + Call this whenever the norm is changed to notify all the + callback listeners to the 'changed' signal. + """ + self.callbacks.process('changed') + + +class Normalize(Norm): """ A class which, when called, maps values within the interval ``[vmin, vmax]`` linearly to the interval ``[0.0, 1.0]``. The mapping of @@ -2307,15 +2388,15 @@ def __init__(self, vmin=None, vmax=None, clip=False): ----- If ``vmin == vmax``, input data will be mapped to 0. """ + super().__init__() self._vmin = _sanitize_extrema(vmin) self._vmax = _sanitize_extrema(vmax) self._clip = clip self._scale = None - self.callbacks = cbook.CallbackRegistry(signals=["changed"]) @property def vmin(self): - """Lower limit of the input data interval; maps to 0.""" + # docstring inherited return self._vmin @vmin.setter @@ -2327,7 +2408,7 @@ def vmin(self, value): @property def vmax(self): - """Upper limit of the input data interval; maps to 1.""" + # docstring inherited return self._vmax @vmax.setter @@ -2339,11 +2420,7 @@ def vmax(self, value): @property def clip(self): - """ - Determines the behavior for mapping values outside the range ``[vmin, vmax]``. - - See the *clip* parameter in `.Normalize`. - """ + # docstring inherited return self._clip @clip.setter @@ -2352,13 +2429,6 @@ def clip(self, value): self._clip = value self._changed() - def _changed(self): - """ - Call this whenever the norm is changed to notify all the - callback listeners to the 'changed' signal. - """ - self.callbacks.process('changed') - @staticmethod def process_value(value): """ @@ -2400,24 +2470,7 @@ def process_value(value): return result, is_scalar def __call__(self, value, clip=None): - """ - Normalize the data and return the normalized data. - - Parameters - ---------- - value - Data to normalize. - clip : bool, optional - See the description of the parameter *clip* in `.Normalize`. - - If ``None``, defaults to ``self.clip`` (which defaults to - ``False``). - - Notes - ----- - If not already initialized, ``self.vmin`` and ``self.vmax`` are - initialized using ``self.autoscale_None(value)``. - """ + # docstring inherited if clip is None: clip = self.clip @@ -2468,7 +2521,7 @@ def inverse(self, value): return vmin + value * (vmax - vmin) def autoscale(self, A): - """Set *vmin*, *vmax* to min, max of *A*.""" + # docstring inherited with self.callbacks.blocked(): # Pause callbacks while we are updating so we only get # a single update signal at the end @@ -2477,7 +2530,7 @@ def autoscale(self, A): self._changed() def autoscale_None(self, A): - """If *vmin* or *vmax* are not set, use the min/max of *A* to set them.""" + # docstring inherited A = np.asanyarray(A) if isinstance(A, np.ma.MaskedArray): @@ -2491,7 +2544,7 @@ def autoscale_None(self, A): self.vmax = A.max() def scaled(self): - """Return whether *vmin* and *vmax* are both set.""" + # docstring inherited return self.vmin is not None and self.vmax is not None @@ -2775,7 +2828,7 @@ def _make_norm_from_scale( unlike to arbitrary lambdas. """ - class Norm(base_norm_cls): + class ScaleNorm(base_norm_cls): def __reduce__(self): cls = type(self) # If the class is toplevel-accessible, it is possible to directly @@ -2855,15 +2908,15 @@ def autoscale_None(self, A): return super().autoscale_None(in_trf_domain) if base_norm_cls is Normalize: - Norm.__name__ = f"{scale_cls.__name__}Norm" - Norm.__qualname__ = f"{scale_cls.__qualname__}Norm" + ScaleNorm.__name__ = f"{scale_cls.__name__}Norm" + ScaleNorm.__qualname__ = f"{scale_cls.__qualname__}Norm" else: - Norm.__name__ = base_norm_cls.__name__ - Norm.__qualname__ = base_norm_cls.__qualname__ - Norm.__module__ = base_norm_cls.__module__ - Norm.__doc__ = base_norm_cls.__doc__ + ScaleNorm.__name__ = base_norm_cls.__name__ + ScaleNorm.__qualname__ = base_norm_cls.__qualname__ + ScaleNorm.__module__ = base_norm_cls.__module__ + ScaleNorm.__doc__ = base_norm_cls.__doc__ - return Norm + return ScaleNorm def _create_empty_object_of_class(cls): diff --git a/lib/matplotlib/colors.pyi b/lib/matplotlib/colors.pyi index eadd759bcaa3..cdc6e5e7d89f 100644 --- a/lib/matplotlib/colors.pyi +++ b/lib/matplotlib/colors.pyi @@ -1,4 +1,5 @@ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from abc import ABC, abstractmethod from matplotlib import cbook, scale import re @@ -249,8 +250,29 @@ class BivarColormapFromImage(BivarColormap): origin: Sequence[float] = ..., name: str = ... ) -> None: ... -class Normalize: +class Norm(ABC): callbacks: cbook.CallbackRegistry + def __init__(self) -> None: ... + @property + @abstractmethod + def vmin(self) -> float | tuple[float] | None: ... + @property + @abstractmethod + def vmax(self) -> float | tuple[float] | None: ... + @property + @abstractmethod + def clip(self) -> bool | tuple[bool]: ... + @abstractmethod + def __call__(self, value: np.ndarray, clip: bool | None = ...) -> ArrayLike: ... + @abstractmethod + def autoscale(self, A: ArrayLike) -> None: ... + @abstractmethod + def autoscale_None(self, A: ArrayLike) -> None: ... + @abstractmethod + def scaled(self) -> bool: ... + + +class Normalize(Norm): def __init__( self, vmin: float | None = ..., vmax: float | None = ..., clip: bool = ... ) -> None: ... diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index c15da7597acd..03549dd53bc1 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -3680,7 +3680,7 @@ def figaspect(arg): w, h = figaspect(2.) fig = Figure(figsize=(w, h)) - ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) + ax = fig.add_axes((0.1, 0.1, 0.8, 0.8)) ax.imshow(A, **kwargs) Make a figure with the proper aspect for an array:: @@ -3688,7 +3688,7 @@ def figaspect(arg): A = rand(5, 3) w, h = figaspect(A) fig = Figure(figsize=(w, h)) - ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) + ax = fig.add_axes((0.1, 0.1, 0.8, 0.8)) ax.imshow(A, **kwargs) """ diff --git a/lib/matplotlib/figure.pyi b/lib/matplotlib/figure.pyi index e7c5175d8af9..61dc79619a80 100644 --- a/lib/matplotlib/figure.pyi +++ b/lib/matplotlib/figure.pyi @@ -89,19 +89,20 @@ class FigureBase(Artist): # TODO: docstring indicates SubplotSpec a valid arg, but none of the listed signatures appear to be that @overload - def add_subplot(self, *args, projection: Literal["3d"], **kwargs) -> Axes3D: ... + def add_subplot(self, *args: Any, projection: Literal["3d"], **kwargs: Any) -> Axes3D: ... @overload def add_subplot( - self, nrows: int, ncols: int, index: int | tuple[int, int], **kwargs + self, nrows: int, ncols: int, index: int | tuple[int, int], **kwargs: Any ) -> Axes: ... @overload - def add_subplot(self, pos: int, **kwargs) -> Axes: ... + def add_subplot(self, pos: int, **kwargs: Any) -> Axes: ... @overload - def add_subplot(self, ax: Axes, **kwargs) -> Axes: ... + def add_subplot(self, ax: Axes, **kwargs: Any) -> Axes: ... @overload - def add_subplot(self, ax: SubplotSpec, **kwargs) -> Axes: ... + def add_subplot(self, ax: SubplotSpec, **kwargs: Any) -> Axes: ... @overload - def add_subplot(self, **kwargs) -> Axes: ... + def add_subplot(self, **kwargs: Any) -> Axes: ... + @overload def subplots( self, diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 6ca472518b65..c1846f92608c 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -967,9 +967,9 @@ def set_extent(self, extent, **kwargs): self.sticky_edges.x[:] = [xmin, xmax] self.sticky_edges.y[:] = [ymin, ymax] if self.axes.get_autoscalex_on(): - self.axes.set_xlim((xmin, xmax), auto=None) + self.axes.set_xlim(xmin, xmax, auto=None) if self.axes.get_autoscaley_on(): - self.axes.set_ylim((ymin, ymax), auto=None) + self.axes.set_ylim(ymin, ymax, auto=None) self.stale = True def get_extent(self): @@ -1823,7 +1823,7 @@ def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear', fig = Figure(figsize=(width, height), dpi=dpi) FigureCanvasBase(fig) - ax = fig.add_axes([0, 0, 1, 1], aspect='auto', + ax = fig.add_axes((0, 0, 1, 1), aspect='auto', frameon=False, xticks=[], yticks=[]) ax.imshow(im, aspect='auto', resample=True, interpolation=interpolation) fig.savefig(thumbfile, dpi=dpi) diff --git a/lib/matplotlib/legend_handler.py b/lib/matplotlib/legend_handler.py index 263945b050d0..65a78891b17f 100644 --- a/lib/matplotlib/legend_handler.py +++ b/lib/matplotlib/legend_handler.py @@ -799,7 +799,6 @@ def get_first(prop_array): legend_handle.set_linewidth(get_first(orig_handle.get_linewidths())) legend_handle.set_linestyle(get_first(orig_handle.get_linestyles())) legend_handle.set_transform(get_first(orig_handle.get_transforms())) - legend_handle.set_figure(orig_handle.get_figure()) # Alpha is already taken into account by the color attributes. def create_artists(self, legend, orig_handle, diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index f538b79e44f0..b4b4c3f96828 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -48,7 +48,8 @@ """ import functools -from numbers import Number +from numbers import Integral, Number +import sys import numpy as np @@ -210,6 +211,23 @@ def detrend_linear(y): return y - (b*x + a) +def _stride_windows(x, n, noverlap=0): + x = np.asarray(x) + + _api.check_isinstance(Integral, n=n, noverlap=noverlap) + if not (1 <= n <= x.size and n < noverlap): + raise ValueError(f'n ({n}) and noverlap ({noverlap}) must be positive integers ' + f'with n < noverlap and n <= x.size ({x.size})') + + if n == 1 and noverlap == 0: + return x[np.newaxis] + + step = n - noverlap + shape = (n, (x.shape[-1]-noverlap)//step) + strides = (x.strides[0], step*x.strides[0]) + return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides) + + def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, mode=None): @@ -304,8 +322,12 @@ def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None, raise ValueError( "The window length must match the data's first dimension") - result = np.lib.stride_tricks.sliding_window_view( - x, NFFT, axis=0)[::NFFT - noverlap].T + if sys.maxsize > 2**32: + result = np.lib.stride_tricks.sliding_window_view( + x, NFFT, axis=0)[::NFFT - noverlap].T + else: + # The NumPy version on 32-bit will OOM, so use old implementation. + result = _stride_windows(x, NFFT, noverlap=noverlap) result = detrend(result, detrend_func, axis=0) result = result * window.reshape((-1, 1)) result = np.fft.fft(result, n=pad_to, axis=0)[:numFreqs, :] @@ -313,8 +335,12 @@ def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None, if not same_data: # if same_data is False, mode must be 'psd' - resultY = np.lib.stride_tricks.sliding_window_view( - y, NFFT, axis=0)[::NFFT - noverlap].T + if sys.maxsize > 2**32: + resultY = np.lib.stride_tricks.sliding_window_view( + y, NFFT, axis=0)[::NFFT - noverlap].T + else: + # The NumPy version on 32-bit will OOM, so use old implementation. + resultY = _stride_windows(y, NFFT, noverlap=noverlap) resultY = detrend(resultY, detrend_func, axis=0) resultY = resultY * window.reshape((-1, 1)) resultY = np.fft.fft(resultY, n=pad_to, axis=0)[:numFreqs, :] diff --git a/lib/matplotlib/mpl-data/matplotlibrc b/lib/matplotlib/mpl-data/matplotlibrc index 780dcd377041..ec649560ba3b 100644 --- a/lib/matplotlib/mpl-data/matplotlibrc +++ b/lib/matplotlib/mpl-data/matplotlibrc @@ -543,6 +543,16 @@ #grid.linewidth: 0.8 # in points #grid.alpha: 1.0 # transparency, between 0.0 and 1.0 +#grid.major.color: None # If None defaults to grid.color +#grid.major.linestyle: None # If None defaults to grid.linestyle +#grid.major.linewidth: None # If None defaults to grid.linewidth +#grid.major.alpha: None # If None defaults to grid.alpha + +#grid.minor.color: None # If None defaults to grid.color +#grid.minor.linestyle: None # If None defaults to grid.linestyle +#grid.minor.linewidth: None # If None defaults to grid.linewidth +#grid.minor.alpha: None # If None defaults to grid.alpha + ## *************************************************************************** ## * LEGEND * diff --git a/lib/matplotlib/offsetbox.py b/lib/matplotlib/offsetbox.py index 1e07125cdc2a..974cc4f2db05 100644 --- a/lib/matplotlib/offsetbox.py +++ b/lib/matplotlib/offsetbox.py @@ -201,7 +201,7 @@ def _get_aligned_offsets(yspans, height, align="baseline"): class OffsetBox(martist.Artist): """ - The OffsetBox is a simple container artist. + A simple container artist. The child artists are meant to be drawn at a relative position to its parent. @@ -826,17 +826,18 @@ def draw(self, renderer): class AuxTransformBox(OffsetBox): """ - Offset Box with the aux_transform. Its children will be - transformed with the aux_transform first then will be - offsetted. The absolute coordinate of the aux_transform is meaning - as it will be automatically adjust so that the left-lower corner - of the bounding box of children will be set to (0, 0) before the - offset transform. - - It is similar to drawing area, except that the extent of the box - is not predetermined but calculated from the window extent of its - children. Furthermore, the extent of the children will be - calculated in the transformed coordinate. + An OffsetBox with an auxiliary transform. + + All child artists are first transformed with *aux_transform*, then + translated with an offset (the same for all children) so the bounding + box of the children matches the drawn box. (In other words, adding an + arbitrary translation to *aux_transform* has no effect as it will be + cancelled out by the later offsetting.) + + `AuxTransformBox` is similar to `.DrawingArea`, except that the extent of + the box is not predetermined but calculated from the window extent of its + children, and the extent of the children will be calculated in the + transformed coordinate. """ def __init__(self, aux_transform): self.aux_transform = aux_transform @@ -853,10 +854,7 @@ def add_artist(self, a): self.stale = True def get_transform(self): - """ - Return the :class:`~matplotlib.transforms.Transform` applied - to the children - """ + """Return the `.Transform` applied to the children.""" return (self.aux_transform + self.ref_offset_transform + self.offset_transform) @@ -908,7 +906,7 @@ def draw(self, renderer): class AnchoredOffsetbox(OffsetBox): """ - An offset box placed according to location *loc*. + An OffsetBox placed according to location *loc*. AnchoredOffsetbox has a single child. When multiple children are needed, use an extra OffsetBox to enclose them. By default, the offset box is diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 63453d416b99..477eee9f5a7a 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -1538,7 +1538,7 @@ def _make_verts(self): length = distance else: length = distance + head_length - if not length: + if np.size(length) == 0: self.verts = np.empty([0, 2]) # display nothing if empty else: # start by drawing horizontal arrow, point at (0, 0) diff --git a/lib/matplotlib/path.py b/lib/matplotlib/path.py index a021706fb1e5..f65ade669167 100644 --- a/lib/matplotlib/path.py +++ b/lib/matplotlib/path.py @@ -275,17 +275,37 @@ def copy(self): """ return copy.copy(self) - def __deepcopy__(self, memo=None): + def __deepcopy__(self, memo): """ Return a deepcopy of the `Path`. The `Path` will not be readonly, even if the source `Path` is. """ # Deepcopying arrays (vertices, codes) strips the writeable=False flag. - p = copy.deepcopy(super(), memo) + cls = type(self) + memo[id(self)] = p = cls.__new__(cls) + + for k, v in self.__dict__.items(): + setattr(p, k, copy.deepcopy(v, memo)) + p._readonly = False return p - deepcopy = __deepcopy__ + def deepcopy(self, memo=None): + """ + Return a deep copy of the `Path`. The `Path` will not be readonly, + even if the source `Path` is. + + Parameters + ---------- + memo : dict, optional + A dictionary to use for memoizing, passed to `copy.deepcopy`. + + Returns + ------- + Path + A deep copy of the `Path`, but not readonly. + """ + return copy.deepcopy(self, memo) @classmethod def make_compound_path_from_polys(cls, XY): diff --git a/lib/matplotlib/path.pyi b/lib/matplotlib/path.pyi index 464fc6d9a912..8a5a5c03792e 100644 --- a/lib/matplotlib/path.pyi +++ b/lib/matplotlib/path.pyi @@ -44,8 +44,8 @@ class Path: @property def readonly(self) -> bool: ... def copy(self) -> Path: ... - def __deepcopy__(self, memo: dict[int, Any] | None = ...) -> Path: ... - deepcopy = __deepcopy__ + def __deepcopy__(self, memo: dict[int, Any]) -> Path: ... + def deepcopy(self, memo: dict[int, Any] | None = None) -> Path: ... @classmethod def make_compound_path_from_polys(cls, XY: ArrayLike) -> Path: ... diff --git a/lib/matplotlib/projections/polar.py b/lib/matplotlib/projections/polar.py index 948b3a6e704f..8fdb31b4256e 100644 --- a/lib/matplotlib/projections/polar.py +++ b/lib/matplotlib/projections/polar.py @@ -817,6 +817,10 @@ def _init_axis(self): self.xaxis = ThetaAxis(self, clear=False) self.yaxis = RadialAxis(self, clear=False) self.spines['polar'].register_axis(self.yaxis) + inner_spine = self.spines.get('inner', None) + if inner_spine is not None: + # Subclasses may not have inner spine. + inner_spine.register_axis(self.yaxis) def _set_lim_and_transforms(self): # A view limit where the minimum radius can be locked if the user @@ -961,7 +965,9 @@ def draw(self, renderer): thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx) if thetamin > thetamax: thetamin, thetamax = thetamax, thetamin - rmin, rmax = ((self._realViewLim.intervaly - self.get_rorigin()) * + rscale_tr = self.yaxis.get_transform() + rmin, rmax = ((rscale_tr.transform(self._realViewLim.intervaly) - + rscale_tr.transform(self.get_rorigin())) * self.get_rsign()) if isinstance(self.patch, mpatches.Wedge): # Backwards-compatibility: Any subclassed Axes might override the diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index cf5c9b4b739f..8c9d1e1e5a29 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -50,7 +50,7 @@ import sys import threading import time -from typing import TYPE_CHECKING, cast, overload +from typing import IO, TYPE_CHECKING, cast, overload from cycler import cycler # noqa: F401 import matplotlib @@ -338,8 +338,8 @@ def uninstall_repl_displayhook() -> None: # Ensure this appears in the pyplot docs. @_copy_docstring_and_deprecators(matplotlib.set_loglevel) -def set_loglevel(*args, **kwargs) -> None: - return matplotlib.set_loglevel(*args, **kwargs) +def set_loglevel(level: str) -> None: + return matplotlib.set_loglevel(level) @_copy_docstring_and_deprecators(Artist.findobj) @@ -569,6 +569,14 @@ def draw_if_interactive(*args, **kwargs): return _get_backend_mod().draw_if_interactive(*args, **kwargs) +@overload +def show(*, block: bool, **kwargs) -> None: ... + + +@overload +def show(*args: Any, **kwargs: Any) -> None: ... + + # This function's signature is rewritten upon backend-load by switch_backend. def show(*args, **kwargs) -> None: """ @@ -1251,11 +1259,11 @@ def draw() -> None: @_copy_docstring_and_deprecators(Figure.savefig) -def savefig(*args, **kwargs) -> None: +def savefig(fname: str | os.PathLike | IO, **kwargs) -> None: fig = gcf() # savefig default implementation has no return, so mypy is unhappy # presumably this is here because subclasses can return? - res = fig.savefig(*args, **kwargs) # type: ignore[func-returns-value] + res = fig.savefig(fname, **kwargs) # type: ignore[func-returns-value] fig.canvas.draw_idle() # Need this if 'transparent=True', to reset colors. return res @@ -1393,6 +1401,18 @@ def cla() -> None: ## More ways of creating Axes ## +@overload +def subplot(nrows: int, ncols: int, index: int, /, **kwargs): ... + + +@overload +def subplot(pos: int | SubplotSpec, /, **kwargs): ... + + +@overload +def subplot(**kwargs): ... + + @_docstring.interpd def subplot(*args, **kwargs) -> Axes: """ @@ -1406,7 +1426,6 @@ def subplot(*args, **kwargs) -> Axes: subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(**kwargs) - subplot(ax) Parameters ---------- @@ -2096,6 +2115,24 @@ def box(on: bool | None = None) -> None: ## Axis ## +@overload +def xlim() -> tuple[float, float]: + ... + + +@overload +def xlim( + left: float | tuple[float, float] | None = None, + right: float | None = None, + *, + emit: bool = True, + auto: bool | None = False, + xmin: float | None = None, + xmax: float | None = None, +) -> tuple[float, float]: + ... + + def xlim(*args, **kwargs) -> tuple[float, float]: """ Get or set the x limits of the current Axes. @@ -2133,6 +2170,24 @@ def xlim(*args, **kwargs) -> tuple[float, float]: return ret +@overload +def ylim() -> tuple[float, float]: + ... + + +@overload +def ylim( + bottom: float | tuple[float, float] | None = None, + top: float | None = None, + *, + emit: bool = True, + auto: bool | None = False, + ymin: float | None = None, + ymax: float | None = None, +) -> tuple[float, float]: + ... + + def ylim(*args, **kwargs) -> tuple[float, float]: """ Get or set the y-limits of the current Axes. diff --git a/lib/matplotlib/rcsetup.py b/lib/matplotlib/rcsetup.py index 02e3601ff4c2..80d25659888e 100644 --- a/lib/matplotlib/rcsetup.py +++ b/lib/matplotlib/rcsetup.py @@ -361,6 +361,12 @@ def validate_color(s): raise ValueError(f'{s!r} does not look like a color arg') +def _validate_color_or_None(s): + if s is None or cbook._str_equal(s, "None"): + return None + return validate_color(s) + + validate_colorlist = _listify_validator( validate_color, allow_stringlist=True, doc='return a list of colorspecs') @@ -515,6 +521,13 @@ def _is_iterable_not_string_like(x): raise ValueError(f"linestyle {ls!r} is not a valid on-off ink sequence.") +def _validate_linestyle_or_None(s): + if s is None or cbook._str_equal(s, "None"): + return None + + return _validate_linestyle(s) + + validate_fillstyle = ValidateInStrings( 'markers.fillstyle', ['full', 'left', 'right', 'bottom', 'top', 'none']) @@ -1242,6 +1255,16 @@ def _convert_validator_spec(key, conv): "grid.linewidth": validate_float, # in points "grid.alpha": validate_float, + "grid.major.color": _validate_color_or_None, # grid color + "grid.major.linestyle": _validate_linestyle_or_None, # solid + "grid.major.linewidth": validate_float_or_None, # in points + "grid.major.alpha": validate_float_or_None, + + "grid.minor.color": _validate_color_or_None, # grid color + "grid.minor.linestyle": _validate_linestyle_or_None, # solid + "grid.minor.linewidth": validate_float_or_None, # in points + "grid.minor.alpha": validate_float_or_None, + ## figure props # figure title "figure.titlesize": validate_fontsize, diff --git a/lib/matplotlib/rcsetup.pyi b/lib/matplotlib/rcsetup.pyi index eb1d7c9f3a33..c6611845723d 100644 --- a/lib/matplotlib/rcsetup.pyi +++ b/lib/matplotlib/rcsetup.pyi @@ -48,6 +48,7 @@ def validate_color_or_auto(s: Any) -> ColorType | Literal["auto"]: ... def _validate_color_or_edge(s: Any) -> ColorType | Literal["edge"]: ... def validate_color_for_prop_cycle(s: Any) -> ColorType: ... def validate_color(s: Any) -> ColorType: ... +def _validate_color_or_None(s: Any) -> ColorType | None: ... def validate_colorlist(s: Any) -> list[ColorType]: ... def _validate_color_or_linecolor( s: Any, @@ -137,6 +138,7 @@ def validate_fillstylelist( ) -> list[Literal["full", "left", "right", "bottom", "top", "none"]]: ... def validate_markevery(s: Any) -> MarkEveryType: ... def _validate_linestyle(s: Any) -> LineStyleType: ... +def _validate_linestyle_or_None(s: Any) -> LineStyleType | None: ... def validate_markeverylist(s: Any) -> list[MarkEveryType]: ... def validate_bbox(s: Any) -> Literal["tight", "standard"] | None: ... def validate_sketch(s: Any) -> None | tuple[float, float, float]: ... diff --git a/lib/matplotlib/scale.py b/lib/matplotlib/scale.py index 44fbe5209c4d..4517b8946b03 100644 --- a/lib/matplotlib/scale.py +++ b/lib/matplotlib/scale.py @@ -31,6 +31,7 @@ import inspect import textwrap +from functools import wraps import numpy as np @@ -103,6 +104,53 @@ def limit_range_for_scale(self, vmin, vmax, minpos): return vmin, vmax +def _make_axis_parameter_optional(init_func): + """ + Decorator to allow leaving out the *axis* parameter in scale constructors. + + This decorator ensures backward compatibility for scale classes that + previously required an *axis* parameter. It allows constructors to be + callerd with or without the *axis* parameter. + + For simplicity, this does not handle the case when *axis* + is passed as a keyword. However, + scanning GitHub, there's no evidence that that is used anywhere. + + Parameters + ---------- + init_func : callable + The original __init__ method of a scale class. + + Returns + ------- + callable + A wrapped version of *init_func* that handles the optional *axis*. + + Notes + ----- + If the wrapped constructor defines *axis* as its first argument, the + parameter is preserved when present. Otherwise, the value `None` is injected + as the first argument. + + Examples + -------- + >>> from matplotlib.scale import ScaleBase + >>> class CustomScale(ScaleBase): + ... @_make_axis_parameter_optional + ... def __init__(self, axis, custom_param=1): + ... self.custom_param = custom_param + """ + @wraps(init_func) + def wrapper(self, *args, **kwargs): + if args and isinstance(args[0], mpl.axis.Axis): + return init_func(self, *args, **kwargs) + else: + # Remove 'axis' from kwargs to avoid double assignment + axis = kwargs.pop('axis', None) + return init_func(self, axis, *args, **kwargs) + return wrapper + + class LinearScale(ScaleBase): """ The default linear scale. @@ -110,6 +158,7 @@ class LinearScale(ScaleBase): name = 'linear' + @_make_axis_parameter_optional def __init__(self, axis): # This method is present only to prevent inheritance of the base class' # constructor docstring, which would otherwise end up interpolated into @@ -180,6 +229,7 @@ class FuncScale(ScaleBase): name = 'function' + @_make_axis_parameter_optional def __init__(self, axis, functions): """ Parameters @@ -279,7 +329,8 @@ class LogScale(ScaleBase): """ name = 'log' - def __init__(self, axis, *, base=10, subs=None, nonpositive="clip"): + @_make_axis_parameter_optional + def __init__(self, axis=None, *, base=10, subs=None, nonpositive="clip"): """ Parameters ---------- @@ -330,6 +381,7 @@ class FuncScaleLog(LogScale): name = 'functionlog' + @_make_axis_parameter_optional def __init__(self, axis, functions, base=10): """ Parameters @@ -455,7 +507,8 @@ class SymmetricalLogScale(ScaleBase): """ name = 'symlog' - def __init__(self, axis, *, base=10, linthresh=2, subs=None, linscale=1): + @_make_axis_parameter_optional + def __init__(self, axis=None, *, base=10, linthresh=2, subs=None, linscale=1): self._transform = SymmetricalLogTransform(base, linthresh, linscale) self.subs = subs @@ -547,7 +600,8 @@ class AsinhScale(ScaleBase): 1024: (256, 512) } - def __init__(self, axis, *, linear_width=1.0, + @_make_axis_parameter_optional + def __init__(self, axis=None, *, linear_width=1.0, base=10, subs='auto', **kwargs): """ Parameters @@ -645,7 +699,8 @@ class LogitScale(ScaleBase): """ name = 'logit' - def __init__(self, axis, nonpositive='mask', *, + @_make_axis_parameter_optional + def __init__(self, axis=None, nonpositive='mask', *, one_half=r"\frac{1}{2}", use_overline=False): r""" Parameters diff --git a/lib/matplotlib/scale.pyi b/lib/matplotlib/scale.pyi index 7fec8e68cc5a..ba9f269b8c78 100644 --- a/lib/matplotlib/scale.pyi +++ b/lib/matplotlib/scale.pyi @@ -15,6 +15,10 @@ class ScaleBase: class LinearScale(ScaleBase): name: str + def __init__( + self, + axis: Axis | None, + ) -> None: ... class FuncTransform(Transform): input_dims: int @@ -57,7 +61,7 @@ class LogScale(ScaleBase): subs: Iterable[int] | None def __init__( self, - axis: Axis | None, + axis: Axis | None = ..., *, base: float = ..., subs: Iterable[int] | None = ..., @@ -104,7 +108,7 @@ class SymmetricalLogScale(ScaleBase): subs: Iterable[int] | None def __init__( self, - axis: Axis | None, + axis: Axis | None = ..., *, base: float = ..., linthresh: float = ..., @@ -138,7 +142,7 @@ class AsinhScale(ScaleBase): auto_tick_multipliers: dict[int, tuple[int, ...]] def __init__( self, - axis: Axis | None, + axis: Axis | None = ..., *, linear_width: float = ..., base: float = ..., @@ -165,7 +169,7 @@ class LogitScale(ScaleBase): name: str def __init__( self, - axis: Axis | None, + axis: Axis | None = ..., nonpositive: Literal["mask", "clip"] = ..., *, one_half: str = ..., @@ -176,3 +180,4 @@ class LogitScale(ScaleBase): def get_scale_names() -> list[str]: ... def scale_factory(scale: str, axis: Axis, **kwargs) -> ScaleBase: ... def register_scale(scale_class: type[ScaleBase]) -> None: ... +def _make_axis_parameter_optional(init_func: Callable[..., None]) -> Callable[..., None]: ... diff --git a/lib/matplotlib/spines.py b/lib/matplotlib/spines.py index 7e77a393f2a2..9732a2f3347a 100644 --- a/lib/matplotlib/spines.py +++ b/lib/matplotlib/spines.py @@ -265,11 +265,17 @@ def _adjust_location(self): self._path = mpath.Path.arc(np.rad2deg(low), np.rad2deg(high)) if self.spine_type == 'bottom': - rmin, rmax = self.axes.viewLim.intervaly + if self.axis is None: + tr = mtransforms.IdentityTransform() + else: + tr = self.axis.get_transform() + rmin, rmax = tr.transform(self.axes.viewLim.intervaly) try: rorigin = self.axes.get_rorigin() except AttributeError: rorigin = rmin + else: + rorigin = tr.transform(rorigin) scaled_diameter = (rmin - rorigin) / (rmax - rorigin) self._height = scaled_diameter self._width = scaled_diameter diff --git a/lib/matplotlib/style/__init__.py b/lib/matplotlib/style/__init__.py index 488c6d6ae1ec..80c6de00a18d 100644 --- a/lib/matplotlib/style/__init__.py +++ b/lib/matplotlib/style/__init__.py @@ -1,4 +1,253 @@ -from .core import available, context, library, reload_library, use +""" +Core functions and attributes for the matplotlib style library: +``use`` + Select style sheet to override the current matplotlib settings. +``context`` + Context manager to use a style sheet temporarily. +``available`` + List available style sheets. Underscore-prefixed names are considered private and + not listed, though may still be accessed directly from ``library``. +``library`` + A dictionary of style names and matplotlib settings. +""" -__all__ = ["available", "context", "library", "reload_library", "use"] +import contextlib +import importlib.resources +import logging +import os +from pathlib import Path +import warnings + +import matplotlib as mpl +from matplotlib import _api, _docstring, rc_params_from_file, rcParamsDefault + +_log = logging.getLogger(__name__) + +__all__ = ['use', 'context', 'available', 'library', 'reload_library'] + + +_BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib') +# Users may want multiple library paths, so store a list of paths. +USER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')] +_STYLE_EXTENSION = 'mplstyle' +# A list of rcParams that should not be applied from styles +_STYLE_BLACKLIST = { + 'interactive', 'backend', 'webagg.port', 'webagg.address', + 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback', + 'toolbar', 'timezone', 'figure.max_open_warning', + 'figure.raise_window', 'savefig.directory', 'tk.window_focus', + 'docstring.hardcopy', 'date.epoch'} + + +@_docstring.Substitution( + "\n".join(map("- {}".format, sorted(_STYLE_BLACKLIST, key=str.lower))) +) +def use(style): + """ + Use Matplotlib style settings from a style specification. + + The style name of 'default' is reserved for reverting back to + the default style settings. + + .. note:: + + This updates the `.rcParams` with the settings from the style. + `.rcParams` not defined in the style are kept. + + Parameters + ---------- + style : str, dict, Path or list + + A style specification. Valid options are: + + str + - One of the style names in `.style.available` (a builtin style or + a style installed in the user library path). + + - A dotted name of the form "package.style_name"; in that case, + "package" should be an importable Python package name, e.g. at + ``/path/to/package/__init__.py``; the loaded style file is + ``/path/to/package/style_name.mplstyle``. (Style files in + subpackages are likewise supported.) + + - The path or URL to a style file, which gets loaded by + `.rc_params_from_file`. + + dict + A mapping of key/value pairs for `matplotlib.rcParams`. + + Path + The path to a style file, which gets loaded by + `.rc_params_from_file`. + + list + A list of style specifiers (str, Path or dict), which are applied + from first to last in the list. + + Notes + ----- + The following `.rcParams` are not related to style and will be ignored if + found in a style specification: + + %s + """ + if isinstance(style, (str, Path)) or hasattr(style, 'keys'): + # If name is a single str, Path or dict, make it a single element list. + styles = [style] + else: + styles = style + + style_alias = {'mpl20': 'default', 'mpl15': 'classic'} + + for style in styles: + if isinstance(style, str): + style = style_alias.get(style, style) + if style == "default": + # Deprecation warnings were already handled when creating + # rcParamsDefault, no need to reemit them here. + with _api.suppress_matplotlib_deprecation_warning(): + # don't trigger RcParams.__getitem__('backend') + style = {k: rcParamsDefault[k] for k in rcParamsDefault + if k not in _STYLE_BLACKLIST} + elif style in library: + style = library[style] + elif "." in style: + pkg, _, name = style.rpartition(".") + try: + path = importlib.resources.files(pkg) / f"{name}.{_STYLE_EXTENSION}" + style = rc_params_from_file(path, use_default_template=False) + except (ModuleNotFoundError, OSError, TypeError) as exc: + # There is an ambiguity whether a dotted name refers to a + # package.style_name or to a dotted file path. Currently, + # we silently try the first form and then the second one; + # in the future, we may consider forcing file paths to + # either use Path objects or be prepended with "./" and use + # the slash as marker for file paths. + pass + if isinstance(style, (str, Path)): + try: + style = rc_params_from_file(style, use_default_template=False) + except OSError as err: + raise OSError( + f"{style!r} is not a valid package style, path of style " + f"file, URL of style file, or library style name (library " + f"styles are listed in `style.available`)") from err + filtered = {} + for k in style: # don't trigger RcParams.__getitem__('backend') + if k in _STYLE_BLACKLIST: + _api.warn_external( + f"Style includes a parameter, {k!r}, that is not " + f"related to style. Ignoring this parameter.") + else: + filtered[k] = style[k] + mpl.rcParams.update(filtered) + + +@contextlib.contextmanager +def context(style, after_reset=False): + """ + Context manager for using style settings temporarily. + + Parameters + ---------- + style : str, dict, Path or list + A style specification. Valid options are: + + str + - One of the style names in `.style.available` (a builtin style or + a style installed in the user library path). + + - A dotted name of the form "package.style_name"; in that case, + "package" should be an importable Python package name, e.g. at + ``/path/to/package/__init__.py``; the loaded style file is + ``/path/to/package/style_name.mplstyle``. (Style files in + subpackages are likewise supported.) + + - The path or URL to a style file, which gets loaded by + `.rc_params_from_file`. + dict + A mapping of key/value pairs for `matplotlib.rcParams`. + + Path + The path to a style file, which gets loaded by + `.rc_params_from_file`. + + list + A list of style specifiers (str, Path or dict), which are applied + from first to last in the list. + + after_reset : bool + If True, apply style after resetting settings to their defaults; + otherwise, apply style on top of the current settings. + """ + with mpl.rc_context(): + if after_reset: + mpl.rcdefaults() + use(style) + yield + + +def _update_user_library(library): + """Update style library with user-defined rc files.""" + for stylelib_path in map(os.path.expanduser, USER_LIBRARY_PATHS): + styles = _read_style_directory(stylelib_path) + _update_nested_dict(library, styles) + return library + + +@_api.deprecated("3.11") +def update_user_library(library): + return _update_user_library(library) + + +def _read_style_directory(style_dir): + """Return dictionary of styles defined in *style_dir*.""" + styles = dict() + for path in Path(style_dir).glob(f"*.{_STYLE_EXTENSION}"): + with warnings.catch_warnings(record=True) as warns: + styles[path.stem] = rc_params_from_file(path, use_default_template=False) + for w in warns: + _log.warning('In %s: %s', path, w.message) + return styles + + +@_api.deprecated("3.11") +def read_style_directory(style_dir): + return _read_style_directory(style_dir) + + +def _update_nested_dict(main_dict, new_dict): + """ + Update nested dict (only level of nesting) with new values. + + Unlike `dict.update`, this assumes that the values of the parent dict are + dicts (or dict-like), so you shouldn't replace the nested dict if it + already exists. Instead you should update the sub-dict. + """ + # update named styles specified by user + for name, rc_dict in new_dict.items(): + main_dict.setdefault(name, {}).update(rc_dict) + return main_dict + + +@_api.deprecated("3.11") +def update_nested_dict(main_dict, new_dict): + return _update_nested_dict(main_dict, new_dict) + + +# Load style library +# ================== +_base_library = _read_style_directory(_BASE_LIBRARY_PATH) +library = {} +available = [] + + +def reload_library(): + """Reload the style library.""" + library.clear() + library.update(_update_user_library(_base_library.copy())) + available[:] = sorted(name for name in library if not name.startswith('_')) + + +reload_library() diff --git a/lib/matplotlib/style/__init__.pyi b/lib/matplotlib/style/__init__.pyi new file mode 100644 index 000000000000..c93b504fe6bd --- /dev/null +++ b/lib/matplotlib/style/__init__.pyi @@ -0,0 +1,20 @@ +from collections.abc import Generator +import contextlib + +from matplotlib import RcParams +from matplotlib.typing import RcStyleType + +USER_LIBRARY_PATHS: list[str] = ... + +def use(style: RcStyleType) -> None: ... +@contextlib.contextmanager +def context( + style: RcStyleType, after_reset: bool = ... +) -> Generator[None, None, None]: ... + +library: dict[str, RcParams] +available: list[str] + +def reload_library() -> None: ... + +__all__ = ['use', 'context', 'available', 'library', 'reload_library'] diff --git a/lib/matplotlib/style/core.py b/lib/matplotlib/style/core.py index e36c3c37a882..c377bc64077a 100644 --- a/lib/matplotlib/style/core.py +++ b/lib/matplotlib/style/core.py @@ -11,227 +11,17 @@ A dictionary of style names and matplotlib settings. """ -import contextlib -import importlib.resources -import logging -import os -from pathlib import Path -import warnings - -import matplotlib as mpl -from matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault - -_log = logging.getLogger(__name__) - -__all__ = ['use', 'context', 'available', 'library', 'reload_library'] - - -BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib') -# Users may want multiple library paths, so store a list of paths. -USER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')] -STYLE_EXTENSION = 'mplstyle' -# A list of rcParams that should not be applied from styles -STYLE_BLACKLIST = { - 'interactive', 'backend', 'webagg.port', 'webagg.address', - 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback', - 'toolbar', 'timezone', 'figure.max_open_warning', - 'figure.raise_window', 'savefig.directory', 'tk.window_focus', - 'docstring.hardcopy', 'date.epoch'} - - -@_docstring.Substitution( - "\n".join(map("- {}".format, sorted(STYLE_BLACKLIST, key=str.lower))) +from .. import _api +from . import ( + use, context, available, library, reload_library, USER_LIBRARY_PATHS, + _BASE_LIBRARY_PATH as BASE_LIBRARY_PATH, + _STYLE_EXTENSION as STYLE_EXTENSION, + _STYLE_BLACKLIST as STYLE_BLACKLIST, ) -def use(style): - """ - Use Matplotlib style settings from a style specification. - - The style name of 'default' is reserved for reverting back to - the default style settings. - - .. note:: - - This updates the `.rcParams` with the settings from the style. - `.rcParams` not defined in the style are kept. - - Parameters - ---------- - style : str, dict, Path or list - - A style specification. Valid options are: - - str - - One of the style names in `.style.available` (a builtin style or - a style installed in the user library path). - - - A dotted name of the form "package.style_name"; in that case, - "package" should be an importable Python package name, e.g. at - ``/path/to/package/__init__.py``; the loaded style file is - ``/path/to/package/style_name.mplstyle``. (Style files in - subpackages are likewise supported.) - - - The path or URL to a style file, which gets loaded by - `.rc_params_from_file`. - - dict - A mapping of key/value pairs for `matplotlib.rcParams`. - - Path - The path to a style file, which gets loaded by - `.rc_params_from_file`. - - list - A list of style specifiers (str, Path or dict), which are applied - from first to last in the list. - - Notes - ----- - The following `.rcParams` are not related to style and will be ignored if - found in a style specification: - - %s - """ - if isinstance(style, (str, Path)) or hasattr(style, 'keys'): - # If name is a single str, Path or dict, make it a single element list. - styles = [style] - else: - styles = style - - style_alias = {'mpl20': 'default', 'mpl15': 'classic'} - - for style in styles: - if isinstance(style, str): - style = style_alias.get(style, style) - if style == "default": - # Deprecation warnings were already handled when creating - # rcParamsDefault, no need to reemit them here. - with _api.suppress_matplotlib_deprecation_warning(): - # don't trigger RcParams.__getitem__('backend') - style = {k: rcParamsDefault[k] for k in rcParamsDefault - if k not in STYLE_BLACKLIST} - elif style in library: - style = library[style] - elif "." in style: - pkg, _, name = style.rpartition(".") - try: - path = importlib.resources.files(pkg) / f"{name}.{STYLE_EXTENSION}" - style = _rc_params_in_file(path) - except (ModuleNotFoundError, OSError, TypeError) as exc: - # There is an ambiguity whether a dotted name refers to a - # package.style_name or to a dotted file path. Currently, - # we silently try the first form and then the second one; - # in the future, we may consider forcing file paths to - # either use Path objects or be prepended with "./" and use - # the slash as marker for file paths. - pass - if isinstance(style, (str, Path)): - try: - style = _rc_params_in_file(style) - except OSError as err: - raise OSError( - f"{style!r} is not a valid package style, path of style " - f"file, URL of style file, or library style name (library " - f"styles are listed in `style.available`)") from err - filtered = {} - for k in style: # don't trigger RcParams.__getitem__('backend') - if k in STYLE_BLACKLIST: - _api.warn_external( - f"Style includes a parameter, {k!r}, that is not " - f"related to style. Ignoring this parameter.") - else: - filtered[k] = style[k] - mpl.rcParams.update(filtered) - - -@contextlib.contextmanager -def context(style, after_reset=False): - """ - Context manager for using style settings temporarily. - - Parameters - ---------- - style : str, dict, Path or list - A style specification. Valid options are: - - str - - One of the style names in `.style.available` (a builtin style or - a style installed in the user library path). - - - A dotted name of the form "package.style_name"; in that case, - "package" should be an importable Python package name, e.g. at - ``/path/to/package/__init__.py``; the loaded style file is - ``/path/to/package/style_name.mplstyle``. (Style files in - subpackages are likewise supported.) - - - The path or URL to a style file, which gets loaded by - `.rc_params_from_file`. - dict - A mapping of key/value pairs for `matplotlib.rcParams`. - - Path - The path to a style file, which gets loaded by - `.rc_params_from_file`. - - list - A list of style specifiers (str, Path or dict), which are applied - from first to last in the list. - - after_reset : bool - If True, apply style after resetting settings to their defaults; - otherwise, apply style on top of the current settings. - """ - with mpl.rc_context(): - if after_reset: - mpl.rcdefaults() - use(style) - yield - - -def update_user_library(library): - """Update style library with user-defined rc files.""" - for stylelib_path in map(os.path.expanduser, USER_LIBRARY_PATHS): - styles = read_style_directory(stylelib_path) - update_nested_dict(library, styles) - return library - - -def read_style_directory(style_dir): - """Return dictionary of styles defined in *style_dir*.""" - styles = dict() - for path in Path(style_dir).glob(f"*.{STYLE_EXTENSION}"): - with warnings.catch_warnings(record=True) as warns: - styles[path.stem] = _rc_params_in_file(path) - for w in warns: - _log.warning('In %s: %s', path, w.message) - return styles - - -def update_nested_dict(main_dict, new_dict): - """ - Update nested dict (only level of nesting) with new values. - - Unlike `dict.update`, this assumes that the values of the parent dict are - dicts (or dict-like), so you shouldn't replace the nested dict if it - already exists. Instead you should update the sub-dict. - """ - # update named styles specified by user - for name, rc_dict in new_dict.items(): - main_dict.setdefault(name, {}).update(rc_dict) - return main_dict - - -# Load style library -# ================== -_base_library = read_style_directory(BASE_LIBRARY_PATH) -library = {} -available = [] - - -def reload_library(): - """Reload the style library.""" - library.clear() - library.update(update_user_library(_base_library)) - available[:] = sorted(library.keys()) +__all__ = [ + "use", "context", "available", "library", "reload_library", + "USER_LIBRARY_PATHS", "BASE_LIBRARY_PATH", "STYLE_EXTENSION", "STYLE_BLACKLIST", +] -reload_library() +_api.warn_deprecated("3.11", name=__name__, obj_type="module") diff --git a/lib/matplotlib/style/core.pyi b/lib/matplotlib/style/core.pyi index 5734b017f7c4..ee21d2f41ef5 100644 --- a/lib/matplotlib/style/core.pyi +++ b/lib/matplotlib/style/core.pyi @@ -5,7 +5,9 @@ from matplotlib import RcParams from matplotlib.typing import RcStyleType USER_LIBRARY_PATHS: list[str] = ... +BASE_LIBRARY_PATH: str = ... STYLE_EXTENSION: str = ... +STYLE_BLACKLIST: set[str] = ... def use(style: RcStyleType) -> None: ... @contextlib.contextmanager @@ -18,4 +20,7 @@ available: list[str] def reload_library() -> None: ... -__all__ = ['use', 'context', 'available', 'library', 'reload_library'] +__all__ = [ + "use", "context", "available", "library", "reload_library", + "USER_LIBRARY_PATHS", "BASE_LIBRARY_PATH", "STYLE_EXTENSION", "STYLE_BLACKLIST", +] diff --git a/lib/matplotlib/style/meson.build b/lib/matplotlib/style/meson.build index 03e7972132bb..e7a183c8581c 100644 --- a/lib/matplotlib/style/meson.build +++ b/lib/matplotlib/style/meson.build @@ -4,6 +4,7 @@ python_sources = [ ] typing_sources = [ + '__init__.pyi', 'core.pyi', ] diff --git a/lib/matplotlib/tests/baseline_images/test_colors/test_norm_abc.png b/lib/matplotlib/tests/baseline_images/test_colors/test_norm_abc.png new file mode 100644 index 000000000000..077365674ac2 Binary files /dev/null and b/lib/matplotlib/tests/baseline_images/test_colors/test_norm_abc.png differ diff --git a/lib/matplotlib/tests/test_arrow_patches.py b/lib/matplotlib/tests/test_arrow_patches.py index c2b6d4fa8086..e26c806c9ea4 100644 --- a/lib/matplotlib/tests/test_arrow_patches.py +++ b/lib/matplotlib/tests/test_arrow_patches.py @@ -59,8 +59,8 @@ def __prepare_fancyarrow_dpi_cor_test(): """ fig2 = plt.figure("fancyarrow_dpi_cor_test", figsize=(4, 3), dpi=50) ax = fig2.add_subplot() - ax.set_xlim([0, 1]) - ax.set_ylim([0, 1]) + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) ax.add_patch(mpatches.FancyArrowPatch(posA=(0.3, 0.4), posB=(0.8, 0.6), lw=3, arrowstyle='->', mutation_scale=100)) diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py index 5c8141e40741..1367701ffe3e 100644 --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -120,15 +120,15 @@ def test_clipping(): patch.set_clip_path(clip_path, ax2.transData) ax2.add_patch(patch) - ax1.set_xlim([-3, 3]) - ax1.set_ylim([-3, 3]) + ax1.set_xlim(-3, 3) + ax1.set_ylim(-3, 3) @check_figures_equal() def test_clipping_zoom(fig_test, fig_ref): # This test places the Axes and sets its limits such that the clip path is # outside the figure entirely. This should not break the clip path. - ax_test = fig_test.add_axes([0, 0, 1, 1]) + ax_test = fig_test.add_axes((0, 0, 1, 1)) l, = ax_test.plot([-3, 3], [-3, 3]) # Explicit Path instead of a Rectangle uses clip path processing, instead # of a clip box optimization. @@ -136,7 +136,7 @@ def test_clipping_zoom(fig_test, fig_ref): p = mpatches.PathPatch(p, transform=ax_test.transData) l.set_clip_path(p) - ax_ref = fig_ref.add_axes([0, 0, 1, 1]) + ax_ref = fig_ref.add_axes((0, 0, 1, 1)) ax_ref.plot([-3, 3], [-3, 3]) ax_ref.set(xlim=(0.5, 0.75), ylim=(0.5, 0.75)) @@ -226,8 +226,8 @@ def test_default_edges(): np.arange(10) + 1, np.arange(10), 'o') ax2.bar(np.arange(10), np.arange(10), align='edge') ax3.text(0, 0, "BOX", size=24, bbox=dict(boxstyle='sawtooth')) - ax3.set_xlim((-1, 1)) - ax3.set_ylim((-1, 1)) + ax3.set_xlim(-1, 1) + ax3.set_ylim(-1, 1) pp1 = mpatches.PathPatch( mpath.Path([(0, 0), (1, 0), (1, 1), (0, 0)], [mpath.Path.MOVETO, mpath.Path.CURVE3, diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index ae2e91b811f1..c96173e340f7 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -3362,16 +3362,16 @@ def test_stackplot(): y3 = 3.0 * x + 2 ax = fig.add_subplot(1, 1, 1) ax.stackplot(x, y1, y2, y3) - ax.set_xlim((0, 10)) - ax.set_ylim((0, 70)) + ax.set_xlim(0, 10) + ax.set_ylim(0, 70) # Reuse testcase from above for a test with labeled data and with colours # from the Axes property cycle. data = {"x": x, "y1": y1, "y2": y2, "y3": y3} fig, ax = plt.subplots() ax.stackplot("x", "y1", "y2", "y3", data=data, colors=["C0", "C1", "C2"]) - ax.set_xlim((0, 10)) - ax.set_ylim((0, 70)) + ax.set_xlim(0, 10) + ax.set_ylim(0, 70) @image_comparison(['stackplot_test_baseline.png'], remove_text=True) @@ -3408,16 +3408,30 @@ def test_stackplot_hatching(fig_ref, fig_test): # stackplot with different hatching styles (issue #27146) ax_test = fig_test.subplots() ax_test.stackplot(x, y1, y2, y3, hatch=["x", "//", "\\\\"], colors=["white"]) - ax_test.set_xlim((0, 10)) - ax_test.set_ylim((0, 70)) + ax_test.set_xlim(0, 10) + ax_test.set_ylim(0, 70) # compare with result from hatching each layer individually stack_baseline = np.zeros(len(x)) ax_ref = fig_ref.subplots() ax_ref.fill_between(x, stack_baseline, y1, hatch="x", facecolor="white") ax_ref.fill_between(x, y1, y1+y2, hatch="//", facecolor="white") ax_ref.fill_between(x, y1+y2, y1+y2+y3, hatch="\\\\", facecolor="white") - ax_ref.set_xlim((0, 10)) - ax_ref.set_ylim((0, 70)) + ax_ref.set_xlim(0, 10) + ax_ref.set_ylim(0, 70) + + +def test_stackplot_subfig_legend(): + # Smoke test for https://github.com/matplotlib/matplotlib/issues/30158 + + fig = plt.figure() + subfigs = fig.subfigures(nrows=1, ncols=2) + + for _fig in subfigs: + ax = _fig.subplots(nrows=1, ncols=1) + ax.stackplot([3, 4], [[1, 2]], labels=['a']) + + fig.legend() + fig.draw_without_rendering() def _bxp_test_helper( @@ -3694,13 +3708,13 @@ def test_boxplot(): fig, ax = plt.subplots() ax.boxplot([x, x], bootstrap=10000, notch=1) - ax.set_ylim((-30, 30)) + ax.set_ylim(-30, 30) # Reuse testcase from above for a labeled data test data = {"x": [x, x]} fig, ax = plt.subplots() ax.boxplot("x", bootstrap=10000, notch=1, data=data) - ax.set_ylim((-30, 30)) + ax.set_ylim(-30, 30) @check_figures_equal() @@ -3738,10 +3752,10 @@ def test_boxplot_sym2(): fig, [ax1, ax2] = plt.subplots(1, 2) ax1.boxplot([x, x], bootstrap=10000, sym='^') - ax1.set_ylim((-30, 30)) + ax1.set_ylim(-30, 30) ax2.boxplot([x, x], bootstrap=10000, sym='g') - ax2.set_ylim((-30, 30)) + ax2.set_ylim(-30, 30) @image_comparison(['boxplot_sym.png'], @@ -3754,7 +3768,7 @@ def test_boxplot_sym(): fig, ax = plt.subplots() ax.boxplot([x, x], sym='gs') - ax.set_ylim((-30, 30)) + ax.set_ylim(-30, 30) @image_comparison(['boxplot_autorange_false_whiskers.png', @@ -3769,11 +3783,11 @@ def test_boxplot_autorange_whiskers(): fig1, ax1 = plt.subplots() ax1.boxplot([x, x], bootstrap=10000, notch=1) - ax1.set_ylim((-5, 5)) + ax1.set_ylim(-5, 5) fig2, ax2 = plt.subplots() ax2.boxplot([x, x], bootstrap=10000, notch=1, autorange=True) - ax2.set_ylim((-5, 5)) + ax2.set_ylim(-5, 5) def _rc_test_bxp_helper(ax, rc_dict): @@ -3863,7 +3877,7 @@ def test_boxplot_with_CIarray(): # another with manual values ax.boxplot([x, x], bootstrap=10000, usermedians=[None, 1.0], conf_intervals=CIs, notch=1) - ax.set_ylim((-30, 30)) + ax.set_ylim(-30, 30) @image_comparison(['boxplot_no_inverted_whisker.png'], @@ -4452,7 +4466,7 @@ def test_errorbar_limits(): xlolims=xlolims, xuplims=xuplims, uplims=uplims, lolims=lolims, ls='none', mec='blue', capsize=0, color='cyan') - ax.set_xlim((0, 5.5)) + ax.set_xlim(0, 5.5) ax.set_title('Errorbar upper and lower limits') @@ -4744,6 +4758,11 @@ def _assert_equal(stem_container, expected): _assert_equal(ax.stem(y, linefmt='r--'), expected=([0, 1, 2], y)) _assert_equal(ax.stem(y, 'r--'), expected=([0, 1, 2], y)) + with pytest.raises(ValueError): + ax.stem([[y]]) + with pytest.raises(ValueError): + ax.stem([[x]], y) + def test_stem_markerfmt(): """Test that stem(..., markerfmt=...) produces the intended markers.""" @@ -5388,8 +5407,8 @@ def test_vertex_markers(): fig, ax = plt.subplots() ax.plot(data, linestyle='', marker=marker_as_tuple, mfc='k') ax.plot(data[::-1], linestyle='', marker=marker_as_list, mfc='b') - ax.set_xlim([-1, 10]) - ax.set_ylim([-1, 10]) + ax.set_xlim(-1, 10) + ax.set_ylim(-1, 10) @image_comparison(['vline_hline_zorder.png', 'errorbar_zorder.png'], @@ -5658,8 +5677,8 @@ def test_step_linestyle(): ax.step(x, y, lw=5, linestyle=ls, where='pre') ax.step(x, y + 1, lw=5, linestyle=ls, where='mid') ax.step(x, y + 2, lw=5, linestyle=ls, where='post') - ax.set_xlim([-1, 5]) - ax.set_ylim([-1, 7]) + ax.set_xlim(-1, 5) + ax.set_ylim(-1, 7) # Reuse testcase from above for a labeled data test data = {"X": x, "Y0": y, "Y1": y+1, "Y2": y+2} @@ -5670,8 +5689,8 @@ def test_step_linestyle(): ax.step("X", "Y0", lw=5, linestyle=ls, where='pre', data=data) ax.step("X", "Y1", lw=5, linestyle=ls, where='mid', data=data) ax.step("X", "Y2", lw=5, linestyle=ls, where='post', data=data) - ax.set_xlim([-1, 5]) - ax.set_ylim([-1, 7]) + ax.set_xlim(-1, 5) + ax.set_ylim(-1, 7) @image_comparison(['mixed_collection'], remove_text=True) @@ -7232,7 +7251,7 @@ def shared_axes_generator(request): ax = ax_lst[0][0] elif request.param == 'add_axes': fig = plt.figure() - ax = fig.add_axes([.1, .1, .8, .8]) + ax = fig.add_axes((.1, .1, .8, .8)) return fig, ax @@ -7566,7 +7585,7 @@ def test_title_no_move_off_page(): # make sure that the automatic title repositioning does not get done. mpl.rcParams['axes.titley'] = None fig = plt.figure() - ax = fig.add_axes([0.1, -0.5, 0.8, 0.2]) + ax = fig.add_axes((0.1, -0.5, 0.8, 0.2)) ax.tick_params(axis="x", bottom=True, top=True, labelbottom=True, labeltop=True) tt = ax.set_title('Boo') @@ -7908,8 +7927,8 @@ def test_zoom_inset(): axin1 = ax.inset_axes([0.7, 0.7, 0.35, 0.35]) # redraw the data in the inset axes... axin1.pcolormesh(x, y, z[:-1, :-1]) - axin1.set_xlim([1.5, 2.15]) - axin1.set_ylim([2, 2.5]) + axin1.set_xlim(1.5, 2.15) + axin1.set_ylim(2, 2.5) axin1.set_aspect(ax.get_aspect()) with pytest.warns(mpl.MatplotlibDeprecationWarning): @@ -8505,7 +8524,7 @@ def test_aspect_nonlinear_adjustable_box(): def test_aspect_nonlinear_adjustable_datalim(): fig = plt.figure(figsize=(10, 10)) # Square. - ax = fig.add_axes([.1, .1, .8, .8]) # Square. + ax = fig.add_axes((.1, .1, .8, .8)) # Square. ax.plot([.4, .6], [.4, .6]) # Set minpos to keep logit happy. ax.set(xscale="log", xlim=(1, 100), yscale="logit", ylim=(1 / 101, 1 / 11), @@ -8729,7 +8748,7 @@ def test_multiplot_autoscale(): def test_sharing_does_not_link_positions(): fig = plt.figure() ax0 = fig.add_subplot(221) - ax1 = fig.add_axes([.6, .6, .3, .3], sharex=ax0) + ax1 = fig.add_axes((.6, .6, .3, .3), sharex=ax0) init_pos = ax1.get_position() fig.subplots_adjust(left=0) assert (ax1.get_position().get_points() == init_pos.get_points()).all() @@ -9828,7 +9847,7 @@ def test_axes_set_position_external_bbox_unchanged(fig_test, fig_ref): ax_test = fig_test.add_axes(bbox) ax_test.set_position([0.25, 0.25, 0.5, 0.5]) assert (bbox.x0, bbox.y0, bbox.width, bbox.height) == (0.0, 0.0, 1.0, 1.0) - ax_ref = fig_ref.add_axes([0.25, 0.25, 0.5, 0.5]) + ax_ref = fig_ref.add_axes((0.25, 0.25, 0.5, 0.5)) def test_bar_shape_mismatch(): diff --git a/lib/matplotlib/tests/test_axis.py b/lib/matplotlib/tests/test_axis.py index e33656ea9c17..97884a33208f 100644 --- a/lib/matplotlib/tests/test_axis.py +++ b/lib/matplotlib/tests/test_axis.py @@ -15,9 +15,9 @@ def test_axis_not_in_layout(): fig2, (ax2_left, ax2_right) = plt.subplots(ncols=2, layout='constrained') # 100 label overlapping the end of the axis - ax1_left.set_xlim([0, 100]) + ax1_left.set_xlim(0, 100) # 100 label not overlapping the end of the axis - ax2_left.set_xlim([0, 120]) + ax2_left.set_xlim(0, 120) for ax in ax1_left, ax2_left: ax.set_xticks([0, 100]) @@ -67,3 +67,31 @@ def test_get_tick_position_tick_params(): right=True, labelright=True, left=False, labelleft=False) assert ax.xaxis.get_ticks_position() == "top" assert ax.yaxis.get_ticks_position() == "right" + + +def test_grid_rcparams(): + """Tests that `grid.major/minor.*` overwrites `grid.*` in rcParams.""" + plt.rcParams.update({ + "axes.grid": True, "axes.grid.which": "both", + "ytick.minor.visible": True, "xtick.minor.visible": True, + }) + def_linewidth = plt.rcParams["grid.linewidth"] + def_linestyle = plt.rcParams["grid.linestyle"] + def_alpha = plt.rcParams["grid.alpha"] + + plt.rcParams.update({ + "grid.color": "gray", "grid.minor.color": "red", + "grid.major.linestyle": ":", "grid.major.linewidth": 2, + "grid.minor.alpha": 0.6, + }) + _, ax = plt.subplots() + ax.plot([0, 1]) + + assert ax.xaxis.get_major_ticks()[0].gridline.get_color() == "gray" + assert ax.xaxis.get_minor_ticks()[0].gridline.get_color() == "red" + assert ax.xaxis.get_major_ticks()[0].gridline.get_linewidth() == 2 + assert ax.xaxis.get_minor_ticks()[0].gridline.get_linewidth() == def_linewidth + assert ax.xaxis.get_major_ticks()[0].gridline.get_linestyle() == ":" + assert ax.xaxis.get_minor_ticks()[0].gridline.get_linestyle() == def_linestyle + assert ax.xaxis.get_major_ticks()[0].gridline.get_alpha() == def_alpha + assert ax.xaxis.get_minor_ticks()[0].gridline.get_alpha() == 0.6 diff --git a/lib/matplotlib/tests/test_colorbar.py b/lib/matplotlib/tests/test_colorbar.py index f95f131e3bf6..ba20f325f4d7 100644 --- a/lib/matplotlib/tests/test_colorbar.py +++ b/lib/matplotlib/tests/test_colorbar.py @@ -332,11 +332,11 @@ def test_colorbar_closed_patch(): plt.rcParams['pcolormesh.snap'] = False fig = plt.figure(figsize=(8, 6)) - ax1 = fig.add_axes([0.05, 0.85, 0.9, 0.1]) - ax2 = fig.add_axes([0.1, 0.65, 0.75, 0.1]) - ax3 = fig.add_axes([0.05, 0.45, 0.9, 0.1]) - ax4 = fig.add_axes([0.05, 0.25, 0.9, 0.1]) - ax5 = fig.add_axes([0.05, 0.05, 0.9, 0.1]) + ax1 = fig.add_axes((0.05, 0.85, 0.9, 0.1)) + ax2 = fig.add_axes((0.1, 0.65, 0.75, 0.1)) + ax3 = fig.add_axes((0.05, 0.45, 0.9, 0.1)) + ax4 = fig.add_axes((0.05, 0.25, 0.9, 0.1)) + ax5 = fig.add_axes((0.05, 0.05, 0.9, 0.1)) cmap = mpl.colormaps["RdBu"].resampled(5) @@ -845,7 +845,7 @@ def test_colorbar_change_lim_scale(): pc = ax[1].pcolormesh(np.arange(100).reshape(10, 10)+1) cb = fig.colorbar(pc, ax=ax[1], extend='both') - cb.ax.set_ylim([20, 90]) + cb.ax.set_ylim(20, 90) @check_figures_equal() @@ -854,7 +854,7 @@ def test_axes_handles_same_functions(fig_ref, fig_test): for nn, fig in enumerate([fig_ref, fig_test]): ax = fig.add_subplot() pc = ax.pcolormesh(np.ones(300).reshape(10, 30)) - cax = fig.add_axes([0.9, 0.1, 0.03, 0.8]) + cax = fig.add_axes((0.9, 0.1, 0.03, 0.8)) cb = fig.colorbar(pc, cax=cax) if nn == 0: caxx = cax diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index df3f65bdb2dc..73de50408401 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -7,6 +7,7 @@ from PIL import Image import pytest import base64 +import platform from numpy.testing import assert_array_equal, assert_array_almost_equal @@ -857,9 +858,9 @@ def test_boundarynorm_and_colorbarbase(): # Make a figure and axes with dimensions as desired. fig = plt.figure() - ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15]) - ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15]) - ax3 = fig.add_axes([0.05, 0.15, 0.9, 0.15]) + ax1 = fig.add_axes((0.05, 0.80, 0.9, 0.15)) + ax2 = fig.add_axes((0.05, 0.475, 0.9, 0.15)) + ax3 = fig.add_axes((0.05, 0.15, 0.9, 0.15)) # Set the colormap and bounds bounds = [-1, 2, 5, 7, 12, 15] @@ -1829,3 +1830,49 @@ def test_LinearSegmentedColormap_from_list_value_color_tuple(): cmap([value for value, _ in value_color_tuples]), to_rgba_array([color for _, color in value_color_tuples]), ) + + +@image_comparison(['test_norm_abc.png'], remove_text=True, + tol=0 if platform.machine() == 'x86_64' else 0.05) +def test_norm_abc(): + + class CustomHalfNorm(mcolors.Norm): + def __init__(self): + super().__init__() + + @property + def vmin(self): + return 0 + + @property + def vmax(self): + return 1 + + @property + def clip(self): + return False + + def __call__(self, value, clip=None): + return value / 2 + + def inverse(self, value): + return 2 * value + + def autoscale(self, A): + pass + + def autoscale_None(self, A): + pass + + def scaled(self): + return True + + fig, axes = plt.subplots(2,2) + + r = np.linspace(-1, 3, 16*16).reshape((16,16)) + norm = CustomHalfNorm() + colorizer = mpl.colorizer.Colorizer(cmap='viridis', norm=norm) + c = axes[0,0].imshow(r, colorizer=colorizer) + axes[0,1].pcolor(r, colorizer=colorizer) + axes[1,0].contour(r, colorizer=colorizer) + axes[1,1].contourf(r, colorizer=colorizer) diff --git a/lib/matplotlib/tests/test_constrainedlayout.py b/lib/matplotlib/tests/test_constrainedlayout.py index df2dbd6f43bd..a2fa5efe780f 100644 --- a/lib/matplotlib/tests/test_constrainedlayout.py +++ b/lib/matplotlib/tests/test_constrainedlayout.py @@ -309,7 +309,7 @@ def test_constrained_layout16(): """Test ax.set_position.""" fig, ax = plt.subplots(layout="constrained") example_plot(ax, fontsize=12) - ax2 = fig.add_axes([0.2, 0.2, 0.4, 0.4]) + ax2 = fig.add_axes((0.2, 0.2, 0.4, 0.4)) @image_comparison(['constrained_layout17.png'], style='mpl20') @@ -357,7 +357,7 @@ def test_constrained_layout20(): img = np.hypot(gx, gx[:, None]) fig = plt.figure() - ax = fig.add_axes([0, 0, 1, 1]) + ax = fig.add_axes((0, 0, 1, 1)) mesh = ax.pcolormesh(gx, gx, img[:-1, :-1]) fig.colorbar(mesh) diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 73f10cec52aa..8ee12131fdbe 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -199,7 +199,7 @@ def test_too_many_date_ticks(caplog): tf = datetime.datetime(2000, 1, 20) fig, ax = plt.subplots() with pytest.warns(UserWarning) as rec: - ax.set_xlim((t0, tf), auto=True) + ax.set_xlim(t0, tf, auto=True) assert len(rec) == 1 assert ('Attempting to set identical low and high xlims' in str(rec[0].message)) diff --git a/lib/matplotlib/tests/test_figure.py b/lib/matplotlib/tests/test_figure.py index 496ac0a071ec..c5890a2963b3 100644 --- a/lib/matplotlib/tests/test_figure.py +++ b/lib/matplotlib/tests/test_figure.py @@ -241,7 +241,7 @@ def test_gca(): fig = plt.figure() # test that gca() picks up Axes created via add_axes() - ax0 = fig.add_axes([0, 0, 1, 1]) + ax0 = fig.add_axes((0, 0, 1, 1)) assert fig.gca() is ax0 # test that gca() picks up Axes created via add_subplot() @@ -546,7 +546,7 @@ def test_invalid_figure_add_axes(): fig.add_axes((.1, .1, .5, np.nan)) with pytest.raises(TypeError, match="multiple values for argument 'rect'"): - fig.add_axes([0, 0, 1, 1], rect=[0, 0, 1, 1]) + fig.add_axes((0, 0, 1, 1), rect=[0, 0, 1, 1]) fig2, ax = plt.subplots() with pytest.raises(ValueError, @@ -559,7 +559,7 @@ def test_invalid_figure_add_axes(): fig2.add_axes(ax, "extra positional argument") with pytest.raises(TypeError, match=r"add_axes\(\) takes 1 positional arguments"): - fig.add_axes([0, 0, 1, 1], "extra positional argument") + fig.add_axes((0, 0, 1, 1), "extra positional argument") def test_subplots_shareax_loglabels(): @@ -1583,22 +1583,22 @@ def test_add_subplot_kwargs(): def test_add_axes_kwargs(): # fig.add_axes() always creates new axes, even if axes kwargs differ. fig = plt.figure() - ax = fig.add_axes([0, 0, 1, 1]) - ax1 = fig.add_axes([0, 0, 1, 1]) + ax = fig.add_axes((0, 0, 1, 1)) + ax1 = fig.add_axes((0, 0, 1, 1)) assert ax is not None assert ax1 is not ax plt.close() fig = plt.figure() - ax = fig.add_axes([0, 0, 1, 1], projection='polar') - ax1 = fig.add_axes([0, 0, 1, 1], projection='polar') + ax = fig.add_axes((0, 0, 1, 1), projection='polar') + ax1 = fig.add_axes((0, 0, 1, 1), projection='polar') assert ax is not None assert ax1 is not ax plt.close() fig = plt.figure() - ax = fig.add_axes([0, 0, 1, 1], projection='polar') - ax1 = fig.add_axes([0, 0, 1, 1]) + ax = fig.add_axes((0, 0, 1, 1), projection='polar') + ax1 = fig.add_axes((0, 0, 1, 1)) assert ax is not None assert ax1.name == 'rectilinear' assert ax1 is not ax diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index 1c89bc5e7912..00c223c59362 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -114,12 +114,12 @@ def test_imshow_zoom(fig_test, fig_ref): fig.set_size_inches(2.9, 2.9) ax = fig_test.subplots() ax.imshow(A, interpolation='auto') - ax.set_xlim([10, 20]) - ax.set_ylim([10, 20]) + ax.set_xlim(10, 20) + ax.set_ylim(10, 20) ax = fig_ref.subplots() ax.imshow(A, interpolation='nearest') - ax.set_xlim([10, 20]) - ax.set_ylim([10, 20]) + ax.set_xlim(10, 20) + ax.set_ylim(10, 20) @check_figures_equal() @@ -526,7 +526,7 @@ def test_image_shift(): def test_image_edges(): fig = plt.figure(figsize=[1, 1]) - ax = fig.add_axes([0, 0, 1, 1], frameon=False) + ax = fig.add_axes((0, 0, 1, 1), frameon=False) data = np.tile(np.arange(12), 15).reshape(20, 9) @@ -534,8 +534,8 @@ def test_image_edges(): interpolation='none', cmap='gray') x = y = 2 - ax.set_xlim([-x, x]) - ax.set_ylim([-y, y]) + ax.set_xlim(-x, x) + ax.set_ylim(-y, y) ax.set_xticks([]) ax.set_yticks([]) @@ -560,7 +560,7 @@ def test_image_composite_background(): ax.imshow(arr, extent=[0, 2, 15, 0]) ax.imshow(arr, extent=[4, 6, 15, 0]) ax.set_facecolor((1, 0, 0, 0.5)) - ax.set_xlim([0, 12]) + ax.set_xlim(0, 12) @image_comparison(['image_composite_alpha'], remove_text=True, tol=0.07) @@ -586,8 +586,8 @@ def test_image_composite_alpha(): ax.imshow(arr2, extent=[0, 5, 2, 3], alpha=0.6) ax.imshow(arr2, extent=[0, 5, 3, 4], alpha=0.3) ax.set_facecolor((0, 0.5, 0, 1)) - ax.set_xlim([0, 5]) - ax.set_ylim([5, 0]) + ax.set_xlim(0, 5) + ax.set_ylim(5, 0) @check_figures_equal(extensions=["pdf"]) @@ -1214,7 +1214,7 @@ def test_exact_vmin(): # make the image exactly 190 pixels wide fig = plt.figure(figsize=(1.9, 0.1), dpi=100) - ax = fig.add_axes([0, 0, 1, 1]) + ax = fig.add_axes((0, 0, 1, 1)) data = np.array( [[-1, -1, -1, 0, 0, 0, 0, 43, 79, 95, 66, 1, -1, -1, -1, 0, 0, 0, 34]], @@ -1491,8 +1491,8 @@ def test_rgba_antialias(): axs = axs.flatten() # zoom in axs[0].imshow(aa, interpolation='nearest', cmap=cmap, vmin=-1.2, vmax=1.2) - axs[0].set_xlim([N/2-25, N/2+25]) - axs[0].set_ylim([N/2+50, N/2-10]) + axs[0].set_xlim(N/2-25, N/2+25) + axs[0].set_ylim(N/2+50, N/2-10) # no anti-alias axs[1].imshow(aa, interpolation='nearest', cmap=cmap, vmin=-1.2, vmax=1.2) diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index d80c6b2ed92a..9b100037cc41 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -530,8 +530,8 @@ def test_legend_stackplot(): y2 = 2.0 * x + 1 y3 = 3.0 * x + 2 ax.stackplot(x, y1, y2, y3, labels=['y1', 'y2', 'y3']) - ax.set_xlim((0, 10)) - ax.set_ylim((0, 70)) + ax.set_xlim(0, 10) + ax.set_ylim(0, 70) ax.legend(loc='best') diff --git a/lib/matplotlib/tests/test_lines.py b/lib/matplotlib/tests/test_lines.py index 68ee1ff8a9a6..fe92547c5963 100644 --- a/lib/matplotlib/tests/test_lines.py +++ b/lib/matplotlib/tests/test_lines.py @@ -219,8 +219,8 @@ def test_marker_fill_styles(): markeredgecolor=color, markeredgewidth=2) - ax.set_ylim([0, 7.5]) - ax.set_xlim([-5, 155]) + ax.set_ylim(0, 7.5) + ax.set_xlim(-5, 155) def test_markerfacecolor_fillstyle(): diff --git a/lib/matplotlib/tests/test_marker.py b/lib/matplotlib/tests/test_marker.py index f6e20c148897..a1e71f1f6533 100644 --- a/lib/matplotlib/tests/test_marker.py +++ b/lib/matplotlib/tests/test_marker.py @@ -181,9 +181,9 @@ def test_marker_clipping(fig_ref, fig_test): width = 2 * marker_size * ncol height = 2 * marker_size * nrow * 2 fig_ref.set_size_inches((width / fig_ref.dpi, height / fig_ref.dpi)) - ax_ref = fig_ref.add_axes([0, 0, 1, 1]) + ax_ref = fig_ref.add_axes((0, 0, 1, 1)) fig_test.set_size_inches((width / fig_test.dpi, height / fig_ref.dpi)) - ax_test = fig_test.add_axes([0, 0, 1, 1]) + ax_test = fig_test.add_axes((0, 0, 1, 1)) for i, marker in enumerate(markers.MarkerStyle.markers): x = i % ncol diff --git a/lib/matplotlib/tests/test_matplotlib.py b/lib/matplotlib/tests/test_matplotlib.py index 37b41fafdb78..d0a3f8c617e1 100644 --- a/lib/matplotlib/tests/test_matplotlib.py +++ b/lib/matplotlib/tests/test_matplotlib.py @@ -1,6 +1,7 @@ import os import subprocess import sys +from unittest.mock import patch import pytest @@ -80,3 +81,16 @@ def test_importable_with__OO(): [sys.executable, "-OO", "-c", program], env={**os.environ, "MPLBACKEND": ""}, check=True ) + + +@patch('matplotlib.subprocess.check_output') +def test_get_executable_info_timeout(mock_check_output): + """ + Test that _get_executable_info raises ExecutableNotFoundError if the + command times out. + """ + + mock_check_output.side_effect = subprocess.TimeoutExpired(cmd=['mock'], timeout=30) + + with pytest.raises(matplotlib.ExecutableNotFoundError, match='Timed out'): + matplotlib._get_executable_info.__wrapped__('inkscape') diff --git a/lib/matplotlib/tests/test_offsetbox.py b/lib/matplotlib/tests/test_offsetbox.py index d9791ff5bc20..bd353ffc719b 100644 --- a/lib/matplotlib/tests/test_offsetbox.py +++ b/lib/matplotlib/tests/test_offsetbox.py @@ -48,8 +48,8 @@ def test_offsetbox_clipping(): da.add_artist(bg) da.add_artist(line) ax.add_artist(anchored_box) - ax.set_xlim((0, 1)) - ax.set_ylim((0, 1)) + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) def test_offsetbox_clip_children(): @@ -455,7 +455,7 @@ def test_remove_draggable(): def test_draggable_in_subfigure(): fig = plt.figure() # Put annotation at lower left corner to make it easily pickable below. - ann = fig.subfigures().add_axes([0, 0, 1, 1]).annotate("foo", (0, 0)) + ann = fig.subfigures().add_axes((0, 0, 1, 1)).annotate("foo", (0, 0)) ann.draggable(True) fig.canvas.draw() # Texts are non-pickable until the first draw. MouseEvent("button_press_event", fig.canvas, 1, 1)._process() diff --git a/lib/matplotlib/tests/test_patches.py b/lib/matplotlib/tests/test_patches.py index 4ed9222eb95e..d69a9dad4337 100644 --- a/lib/matplotlib/tests/test_patches.py +++ b/lib/matplotlib/tests/test_patches.py @@ -1093,3 +1093,9 @@ def test_facecolor_none_edgecolor_force_edgecolor(): rcParams['patch.edgecolor'] = 'red' rect = Rectangle((0, 0), 1, 1, facecolor="none") assert mcolors.same_color(rect.get_edgecolor(), rcParams['patch.edgecolor']) + + +def test_empty_fancyarrow(): + fig, ax = plt.subplots() + arrow = ax.arrow([], [], [], []) + assert arrow is not None diff --git a/lib/matplotlib/tests/test_path.py b/lib/matplotlib/tests/test_path.py index 21f4c33794af..a61f01c0d48a 100644 --- a/lib/matplotlib/tests/test_path.py +++ b/lib/matplotlib/tests/test_path.py @@ -155,8 +155,8 @@ def test_nonlinear_containment(): def test_arrow_contains_point(): # fix bug (#8384) fig, ax = plt.subplots() - ax.set_xlim((0, 2)) - ax.set_ylim((0, 2)) + ax.set_xlim(0, 2) + ax.set_ylim(0, 2) # create an arrow with Curve style arrow = patches.FancyArrowPatch((0.5, 0.25), (1.5, 0.75), @@ -355,15 +355,49 @@ def test_path_deepcopy(): # Should not raise any error verts = [[0, 0], [1, 1]] codes = [Path.MOVETO, Path.LINETO] - path1 = Path(verts) - path2 = Path(verts, codes) + path1 = Path(verts, readonly=True) + path2 = Path(verts, codes, readonly=True) path1_copy = path1.deepcopy() path2_copy = path2.deepcopy() assert path1 is not path1_copy assert path1.vertices is not path1_copy.vertices + assert_array_equal(path1.vertices, path1_copy.vertices) + assert path1.readonly + assert not path1_copy.readonly assert path2 is not path2_copy assert path2.vertices is not path2_copy.vertices + assert_array_equal(path2.vertices, path2_copy.vertices) assert path2.codes is not path2_copy.codes + assert_array_equal(path2.codes, path2_copy.codes) + assert path2.readonly + assert not path2_copy.readonly + + +def test_path_deepcopy_cycle(): + class PathWithCycle(Path): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.x = self + + p = PathWithCycle([[0, 0], [1, 1]], readonly=True) + p_copy = p.deepcopy() + assert p_copy is not p + assert p.readonly + assert not p_copy.readonly + assert p_copy.x is p_copy + + class PathWithCycle2(Path): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.x = [self] * 2 + + p2 = PathWithCycle2([[0, 0], [1, 1]], readonly=True) + p2_copy = p2.deepcopy() + assert p2_copy is not p2 + assert p2.readonly + assert not p2_copy.readonly + assert p2_copy.x[0] is p2_copy + assert p2_copy.x[1] is p2_copy def test_path_shallowcopy(): diff --git a/lib/matplotlib/tests/test_polar.py b/lib/matplotlib/tests/test_polar.py index a0969df5de90..c0bf72b89eb0 100644 --- a/lib/matplotlib/tests/test_polar.py +++ b/lib/matplotlib/tests/test_polar.py @@ -150,7 +150,7 @@ def test_polar_rmin(): theta = 2*np.pi*r fig = plt.figure() - ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) + ax = fig.add_axes((0.1, 0.1, 0.8, 0.8), polar=True) ax.plot(theta, r) ax.set_rmax(2.0) ax.set_rmin(0.5) @@ -162,7 +162,7 @@ def test_polar_negative_rmin(): theta = 2*np.pi*r fig = plt.figure() - ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) + ax = fig.add_axes((0.1, 0.1, 0.8, 0.8), polar=True) ax.plot(theta, r) ax.set_rmax(0.0) ax.set_rmin(-3.0) @@ -174,7 +174,7 @@ def test_polar_rorigin(): theta = 2*np.pi*r fig = plt.figure() - ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) + ax = fig.add_axes((0.1, 0.1, 0.8, 0.8), polar=True) ax.plot(theta, r) ax.set_rmax(2.0) ax.set_rmin(0.5) @@ -184,14 +184,14 @@ def test_polar_rorigin(): @image_comparison(['polar_invertedylim.png'], style='default') def test_polar_invertedylim(): fig = plt.figure() - ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) + ax = fig.add_axes((0.1, 0.1, 0.8, 0.8), polar=True) ax.set_ylim(2, 0) @image_comparison(['polar_invertedylim_rorigin.png'], style='default') def test_polar_invertedylim_rorigin(): fig = plt.figure() - ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) + ax = fig.add_axes((0.1, 0.1, 0.8, 0.8), polar=True) ax.yaxis.set_inverted(True) # Set the rlims to inverted (2, 0) without calling set_rlim, to check that # viewlims are correctly unstaled before draw()ing. @@ -206,7 +206,7 @@ def test_polar_theta_position(): theta = 2*np.pi*r fig = plt.figure() - ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True) + ax = fig.add_axes((0.1, 0.1, 0.8, 0.8), polar=True) ax.plot(theta, r) ax.set_theta_zero_location("NW", 30) ax.set_theta_direction('clockwise') @@ -482,6 +482,26 @@ def test_polar_log(): ax.plot(np.linspace(0, 2 * np.pi, n), np.logspace(0, 2, n)) +@check_figures_equal() +def test_polar_log_rorigin(fig_ref, fig_test): + # Test that equivalent linear and log radial settings give the same axes patch + # and spines. + ax_ref = fig_ref.add_subplot(projection='polar', facecolor='red') + ax_ref.set_rlim(0, 2) + ax_ref.set_rorigin(-3) + ax_ref.set_rticks(np.linspace(0, 2, 5)) + + ax_test = fig_test.add_subplot(projection='polar', facecolor='red') + ax_test.set_rscale('log') + ax_test.set_rlim(1, 100) + ax_test.set_rorigin(10**-3) + ax_test.set_rticks(np.logspace(0, 2, 5)) + + for ax in ax_ref, ax_test: + # Radial tick labels should be the only difference, so turn them off. + ax.tick_params(labelleft=False) + + def test_polar_neg_theta_lims(): fig = plt.figure() ax = fig.add_subplot(projection='polar') diff --git a/lib/matplotlib/tests/test_pyplot.py b/lib/matplotlib/tests/test_pyplot.py index ab713707bace..55f7c33cb52e 100644 --- a/lib/matplotlib/tests/test_pyplot.py +++ b/lib/matplotlib/tests/test_pyplot.py @@ -1,4 +1,5 @@ import difflib +import inspect import numpy as np import sys @@ -484,3 +485,26 @@ def test_matshow(): # Smoke test that matshow does not ask for a new figsize on the existing figure plt.matshow(arr, fignum=fig.number) + + +def assert_same_signature(func1, func2): + """ + Assert that `func1` and `func2` have the same arguments, + i.e. same parameter count, names and kinds. + + :param func1: First function to check + :param func2: Second function to check + """ + params1 = inspect.signature(func1).parameters + params2 = inspect.signature(func2).parameters + + assert len(params1) == len(params2) + assert all([ + params1[p].name == params2[p].name and + params1[p].kind == params2[p].kind + for p in params1 + ]) + + +def test_setloglevel_signature(): + assert_same_signature(plt.set_loglevel, mpl.set_loglevel) diff --git a/lib/matplotlib/tests/test_simplification.py b/lib/matplotlib/tests/test_simplification.py index bc9b46b14db2..41d01addd622 100644 --- a/lib/matplotlib/tests/test_simplification.py +++ b/lib/matplotlib/tests/test_simplification.py @@ -25,7 +25,7 @@ def test_clipping(): fig, ax = plt.subplots() ax.plot(t, s, linewidth=1.0) - ax.set_ylim((-0.20, -0.28)) + ax.set_ylim(-0.20, -0.28) @image_comparison(['overflow'], remove_text=True, @@ -244,8 +244,8 @@ def test_simplify_curve(): fig, ax = plt.subplots() ax.add_patch(pp1) - ax.set_xlim((0, 2)) - ax.set_ylim((0, 2)) + ax.set_xlim(0, 2) + ax.set_ylim(0, 2) @check_figures_equal(extensions=['png', 'pdf', 'svg']) @@ -401,8 +401,8 @@ def test_closed_path_clipping(fig_test, fig_ref): def test_hatch(): fig, ax = plt.subplots() ax.add_patch(plt.Rectangle((0, 0), 1, 1, fill=False, hatch="/")) - ax.set_xlim((0.45, 0.55)) - ax.set_ylim((0.45, 0.55)) + ax.set_xlim(0.45, 0.55) + ax.set_ylim(0.45, 0.55) @image_comparison(['fft_peaks'], remove_text=True) diff --git a/lib/matplotlib/tests/test_spines.py b/lib/matplotlib/tests/test_spines.py index 353aede00298..d6ddcabb6878 100644 --- a/lib/matplotlib/tests/test_spines.py +++ b/lib/matplotlib/tests/test_spines.py @@ -154,3 +154,15 @@ def test_spines_black_axes(): ax.set_xticks([]) ax.set_yticks([]) ax.set_facecolor((0, 0, 0)) + + +def test_arc_spine_inner_no_axis(): + # Backcompat: smoke test that inner arc spine does not need a registered + # axis in order to be drawn + fig = plt.figure() + ax = fig.add_subplot(projection="polar") + inner_spine = ax.spines["inner"] + inner_spine.register_axis(None) + assert ax.spines["inner"].axis is None + + fig.draw_without_rendering() diff --git a/lib/matplotlib/tests/test_style.py b/lib/matplotlib/tests/test_style.py index be038965e33d..7b54f1141720 100644 --- a/lib/matplotlib/tests/test_style.py +++ b/lib/matplotlib/tests/test_style.py @@ -8,7 +8,6 @@ import matplotlib as mpl from matplotlib import pyplot as plt, style -from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION PARAM = 'image.cmap' @@ -21,7 +20,8 @@ def temp_style(style_name, settings=None): """Context manager to create a style sheet in a temporary directory.""" if not settings: settings = DUMMY_SETTINGS - temp_file = f'{style_name}.{STYLE_EXTENSION}' + temp_file = f'{style_name}.mplstyle' + orig_library_paths = style.USER_LIBRARY_PATHS try: with TemporaryDirectory() as tmpdir: # Write style settings to file in the tmpdir. @@ -29,10 +29,11 @@ def temp_style(style_name, settings=None): "\n".join(f"{k}: {v}" for k, v in settings.items()), encoding="utf-8") # Add tmpdir to style path and reload so we can access this style. - USER_LIBRARY_PATHS.append(tmpdir) + style.USER_LIBRARY_PATHS.append(tmpdir) style.reload_library() yield finally: + style.USER_LIBRARY_PATHS = orig_library_paths style.reload_library() @@ -47,8 +48,17 @@ def test_invalid_rc_warning_includes_filename(caplog): def test_available(): - with temp_style('_test_', DUMMY_SETTINGS): - assert '_test_' in style.available + # Private name should not be listed in available but still usable. + assert '_classic_test_patch' not in style.available + assert '_classic_test_patch' in style.library + + with temp_style('_test_', DUMMY_SETTINGS), temp_style('dummy', DUMMY_SETTINGS): + assert 'dummy' in style.available + assert 'dummy' in style.library + assert '_test_' not in style.available + assert '_test_' in style.library + assert 'dummy' not in style.available + assert '_test_' not in style.available def test_use(): @@ -71,7 +81,7 @@ def test_use_url(tmp_path): def test_single_path(tmp_path): mpl.rcParams[PARAM] = 'gray' - path = tmp_path / f'text.{STYLE_EXTENSION}' + path = tmp_path / 'text.mplstyle' path.write_text(f'{PARAM} : {VALUE}', encoding='utf-8') with style.context(path): assert mpl.rcParams[PARAM] == VALUE diff --git a/lib/matplotlib/tests/test_subplots.py b/lib/matplotlib/tests/test_subplots.py index a899110ac77a..0f00a88aa72d 100644 --- a/lib/matplotlib/tests/test_subplots.py +++ b/lib/matplotlib/tests/test_subplots.py @@ -4,6 +4,7 @@ import numpy as np import pytest +import matplotlib as mpl from matplotlib.axes import Axes, SubplotBase import matplotlib.pyplot as plt from matplotlib.testing.decorators import check_figures_equal, image_comparison @@ -111,10 +112,15 @@ def test_shared(): @pytest.mark.parametrize('remove_ticks', [True, False]) -def test_label_outer(remove_ticks): - f, axs = plt.subplots(2, 2, sharex=True, sharey=True) +@pytest.mark.parametrize('layout_engine', ['none', 'tight', 'constrained']) +@pytest.mark.parametrize('with_colorbar', [True, False]) +def test_label_outer(remove_ticks, layout_engine, with_colorbar): + fig = plt.figure(layout=layout_engine) + axs = fig.subplots(2, 2, sharex=True, sharey=True) for ax in axs.flat: ax.set(xlabel="foo", ylabel="bar") + if with_colorbar: + fig.colorbar(mpl.cm.ScalarMappable(), ax=ax) ax.label_outer(remove_inner_ticks=remove_ticks) check_ticklabel_visible( axs.flat, [False, False, True, True], [True, False, True, False]) diff --git a/lib/matplotlib/tests/test_text.py b/lib/matplotlib/tests/test_text.py index 906484c8a526..7e1a50df8a2f 100644 --- a/lib/matplotlib/tests/test_text.py +++ b/lib/matplotlib/tests/test_text.py @@ -144,8 +144,8 @@ def test_multiline2(): fig, ax = plt.subplots() - ax.set_xlim([0, 1.4]) - ax.set_ylim([0, 2]) + ax.set_xlim(0, 1.4) + ax.set_ylim(0, 2) ax.axhline(0.5, color='C2', linewidth=0.3) sts = ['Line', '2 Lineg\n 2 Lg', '$\\sum_i x $', 'hi $\\sum_i x $\ntest', 'test\n $\\sum_i x $', '$\\sum_i x $\n $\\sum_i x $'] diff --git a/lib/matplotlib/tests/test_tightlayout.py b/lib/matplotlib/tests/test_tightlayout.py index f6b6d8f644cc..98fd5e70cdb9 100644 --- a/lib/matplotlib/tests/test_tightlayout.py +++ b/lib/matplotlib/tests/test_tightlayout.py @@ -331,8 +331,8 @@ def test_collapsed(): # zero (i.e. margins add up to more than the available width) that a call # to tight_layout will not get applied: fig, ax = plt.subplots(tight_layout=True) - ax.set_xlim([0, 1]) - ax.set_ylim([0, 1]) + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) ax.annotate('BIG LONG STRING', xy=(1.25, 2), xytext=(10.5, 1.75), annotation_clip=False) diff --git a/lib/matplotlib/tests/test_usetex.py b/lib/matplotlib/tests/test_usetex.py index 95eb69325622..cd9f2597361b 100644 --- a/lib/matplotlib/tests/test_usetex.py +++ b/lib/matplotlib/tests/test_usetex.py @@ -232,8 +232,8 @@ def test_rotation(): mpl.rcParams['text.usetex'] = True fig = plt.figure() - ax = fig.add_axes([0, 0, 1, 1]) - ax.set(xlim=[-0.5, 5], xticks=[], ylim=[-0.5, 3], yticks=[], frame_on=False) + ax = fig.add_axes((0, 0, 1, 1)) + ax.set(xlim=(-0.5, 5), xticks=[], ylim=(-0.5, 3), yticks=[], frame_on=False) text = {val: val[0] for val in ['top', 'center', 'bottom', 'left', 'right']} text['baseline'] = 'B' diff --git a/lib/matplotlib/transforms.py b/lib/matplotlib/transforms.py index 7228f05bcf9e..350113c56170 100644 --- a/lib/matplotlib/transforms.py +++ b/lib/matplotlib/transforms.py @@ -35,7 +35,6 @@ # `np.minimum` instead of the builtin `min`, and likewise for `max`. This is # done so that `nan`s are propagated, instead of being silently dropped. -import copy import functools import itertools import textwrap @@ -139,7 +138,9 @@ def __setstate__(self, data_dict): for k, v in self._parents.items() if v is not None} def __copy__(self): - other = copy.copy(super()) + cls = type(self) + other = cls.__new__(cls) + other.__dict__.update(self.__dict__) # If `c = a + b; a1 = copy(a)`, then modifications to `a1` do not # propagate back to `c`, i.e. we need to clear the parents of `a1`. other._parents = {} diff --git a/lib/matplotlib/widgets.py b/lib/matplotlib/widgets.py index 6b196571814d..9ded7c61ce2d 100644 --- a/lib/matplotlib/widgets.py +++ b/lib/matplotlib/widgets.py @@ -273,10 +273,10 @@ def __init__(self, ax, orientation, closedmin, closedmax, self.valfmt = valfmt if orientation == "vertical": - ax.set_ylim((valmin, valmax)) + ax.set_ylim(valmin, valmax) axis = ax.yaxis else: - ax.set_xlim((valmin, valmax)) + ax.set_xlim(valmin, valmax) axis = ax.xaxis self._fmt = axis.get_major_formatter() @@ -1841,7 +1841,7 @@ def __init__(self, targetfig, toolfig): self.sliderbottom.slidermax = self.slidertop self.slidertop.slidermin = self.sliderbottom - bax = toolfig.add_axes([0.8, 0.05, 0.15, 0.075]) + bax = toolfig.add_axes((0.8, 0.05, 0.15, 0.075)) self.buttonreset = Button(bax, 'Reset') self.buttonreset.on_clicked(self._on_reset) diff --git a/lib/mpl_toolkits/axes_grid1/tests/test_axes_grid1.py b/lib/mpl_toolkits/axes_grid1/tests/test_axes_grid1.py index 26f0aaa37de0..b6d72e408a52 100644 --- a/lib/mpl_toolkits/axes_grid1/tests/test_axes_grid1.py +++ b/lib/mpl_toolkits/axes_grid1/tests/test_axes_grid1.py @@ -699,7 +699,7 @@ def test_mark_inset_unstales_viewlim(fig_test, fig_ref): def test_auto_adjustable(): fig = plt.figure() - ax = fig.add_axes([0, 0, 1, 1]) + ax = fig.add_axes((0, 0, 1, 1)) pad = 0.1 make_axes_area_auto_adjustable(ax, pad=pad) fig.canvas.draw() diff --git a/lib/mpl_toolkits/axisartist/tests/test_axislines.py b/lib/mpl_toolkits/axisartist/tests/test_axislines.py index 8bc3707421b6..a1485d4f436b 100644 --- a/lib/mpl_toolkits/axisartist/tests/test_axislines.py +++ b/lib/mpl_toolkits/axisartist/tests/test_axislines.py @@ -83,8 +83,8 @@ def test_ParasiteAxesAuxTrans(): getattr(ax2, name)(xx, yy, data[:-1, :-1]) else: getattr(ax2, name)(xx, yy, data) - ax1.set_xlim((0, 5)) - ax1.set_ylim((0, 5)) + ax1.set_xlim(0, 5) + ax1.set_ylim(0, 5) ax2.contour(xx, yy, data, colors='k') diff --git a/lib/mpl_toolkits/mplot3d/tests/test_axes3d.py b/lib/mpl_toolkits/mplot3d/tests/test_axes3d.py index 79c7baba9bd1..cd45c8e33a6f 100644 --- a/lib/mpl_toolkits/mplot3d/tests/test_axes3d.py +++ b/lib/mpl_toolkits/mplot3d/tests/test_axes3d.py @@ -2227,9 +2227,9 @@ def test_computed_zorder(): # plot some points ax.scatter((3, 3), (1, 3), (1, 3), c='red', zorder=10) - ax.set_xlim((0, 5.0)) - ax.set_ylim((0, 5.0)) - ax.set_zlim((0, 2.5)) + ax.set_xlim(0, 5.0) + ax.set_ylim(0, 5.0) + ax.set_zlim(0, 2.5) ax3 = fig.add_subplot(223, projection='3d') ax4 = fig.add_subplot(224, projection='3d') diff --git a/pyproject.toml b/pyproject.toml index 70b078a73d27..b580feff930e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -93,19 +93,13 @@ sections = "FUTURE,STDLIB,THIRDPARTY,PYDATA,FIRSTPARTY,LOCALFOLDER" force_sort_within_sections = true [tool.ruff] -exclude = [ - ".git", +extend-exclude = [ "build", "doc/gallery", "doc/tutorials", "tools/gh_api.py", - ".tox", - ".eggs", - # TODO: fix .ipynb files - "*.ipynb" ] line-length = 88 -target-version = "py311" [tool.ruff.lint] ignore = [ @@ -131,9 +125,7 @@ ignore = [ "D404", "D413", "D415", - "D416", "D417", - "E24", "E266", "E305", "E306", @@ -174,15 +166,13 @@ convention = "numpy" [tool.ruff.lint.per-file-ignores] "*.pyi" = ["E501"] +"*.ipynb" = ["E402"] "doc/conf.py" = ["E402"] -"galleries/examples/animation/frame_grabbing_sgskip.py" = ["E402"] "galleries/examples/images_contours_and_fields/tricontour_demo.py" = ["E201"] "galleries/examples/images_contours_and_fields/tripcolor_demo.py" = ["E201"] "galleries/examples/images_contours_and_fields/triplot_demo.py" = ["E201"] "galleries/examples/lines_bars_and_markers/marker_reference.py" = ["E402"] -"galleries/examples/misc/print_stdout_sgskip.py" = ["E402"] "galleries/examples/misc/table_demo.py" = ["E201"] -"galleries/examples/style_sheets/bmh.py" = ["E501"] "galleries/examples/subplots_axes_and_figures/demo_constrained_layout.py" = ["E402"] "galleries/examples/text_labels_and_annotations/custom_legends.py" = ["E402"] "galleries/examples/ticks/date_concise_formatter.py" = ["E402"] @@ -196,7 +186,6 @@ convention = "numpy" "galleries/examples/user_interfaces/mpl_with_glade3_sgskip.py" = ["E402"] "galleries/examples/user_interfaces/pylab_with_gtk3_sgskip.py" = ["E402"] "galleries/examples/user_interfaces/pylab_with_gtk4_sgskip.py" = ["E402"] -"galleries/examples/userdemo/pgf_preamble_sgskip.py" = ["E402"] "lib/matplotlib/__init__.py" = ["F822"] "lib/matplotlib/_cm.py" = ["E202", "E203", "E302"] @@ -212,21 +201,17 @@ convention = "numpy" "lib/mpl_toolkits/axisartist/angle_helper.py" = ["E221"] "lib/mpl_toolkits/mplot3d/proj3d.py" = ["E201"] -"galleries/users_explain/artists/paths.py" = ["E402"] "galleries/users_explain/quick_start.py" = ["E402"] "galleries/users_explain/artists/patheffects_guide.py" = ["E402"] -"galleries/users_explain/artists/transforms_tutorial.py" = ["E402", "E501"] -"galleries/users_explain/colors/colormaps.py" = ["E501"] +"galleries/users_explain/artists/transforms_tutorial.py" = ["E402"] "galleries/users_explain/colors/colors.py" = ["E402"] "galleries/tutorials/artists.py" = ["E402"] "galleries/users_explain/axes/constrainedlayout_guide.py" = ["E402"] "galleries/users_explain/axes/legend_guide.py" = ["E402"] "galleries/users_explain/axes/tight_layout_guide.py" = ["E402"] "galleries/users_explain/animations/animations.py" = ["E501"] -"galleries/tutorials/images.py" = ["E501"] "galleries/tutorials/pyplot.py" = ["E402", "E501"] "galleries/users_explain/text/annotations.py" = ["E402", "E501"] -"galleries/users_explain/text/mathtext.py" = ["E501"] "galleries/users_explain/text/text_intro.py" = ["E402"] "galleries/users_explain/text/text_props.py" = ["E501"] @@ -237,18 +222,12 @@ enable_error_code = [ "redundant-expr", "truthy-bool", ] -enable_incomplete_feature = [ - "Unpack", -] exclude = [ #stubtest ".*/matplotlib/(sphinxext|backends|pylab|testing/jpl_units)", #mypy precommit "galleries/", "doc/", - "lib/matplotlib/backends/", - "lib/matplotlib/sphinxext", - "lib/matplotlib/testing/jpl_units", "lib/mpl_toolkits/", #removing tests causes errors in backends "lib/matplotlib/tests/", diff --git a/src/_backend_agg.h b/src/_backend_agg.h index 6ecbcba1df18..1ac3d4c06b13 100644 --- a/src/_backend_agg.h +++ b/src/_backend_agg.h @@ -11,6 +11,8 @@ #include #include #include +#include +#include #include "agg_alpha_mask_u8.h" #include "agg_conv_curve.h" @@ -102,8 +104,6 @@ class BufferRegion int stride; }; -#define MARKER_CACHE_SIZE 512 - // the renderer class RendererAgg { @@ -124,9 +124,6 @@ class RendererAgg typedef agg::renderer_base renderer_base_alpha_mask_type; typedef agg::renderer_scanline_aa_solid renderer_alpha_mask_type; - /* TODO: Remove facepair_t */ - typedef std::pair facepair_t; - RendererAgg(unsigned int width, unsigned int height, double dpi); virtual ~RendererAgg(); @@ -249,7 +246,7 @@ class RendererAgg bool render_clippath(mpl::PathIterator &clippath, const agg::trans_affine &clippath_trans, e_snap_mode snap_mode); template - void _draw_path(PathIteratorType &path, bool has_clippath, const facepair_t &face, GCAgg &gc); + void _draw_path(PathIteratorType &path, bool has_clippath, const std::optional &face, GCAgg &gc); template inline void -RendererAgg::_draw_path(path_t &path, bool has_clippath, const facepair_t &face, GCAgg &gc) +RendererAgg::_draw_path(path_t &path, bool has_clippath, const std::optional &face, GCAgg &gc) { typedef agg::conv_stroke stroke_t; typedef agg::conv_dash dash_t; @@ -307,7 +304,7 @@ RendererAgg::_draw_path(path_t &path, bool has_clippath, const facepair_t &face, typedef agg::renderer_scanline_bin_solid amask_bin_renderer_type; // Render face - if (face.first) { + if (face) { theRasterizer.add_path(path); if (gc.isaa) { @@ -315,10 +312,10 @@ RendererAgg::_draw_path(path_t &path, bool has_clippath, const facepair_t &face, pixfmt_amask_type pfa(pixFmt, alphaMask); amask_ren_type r(pfa); amask_aa_renderer_type ren(r); - ren.color(face.second); + ren.color(*face); agg::render_scanlines(theRasterizer, scanlineAlphaMask, ren); } else { - rendererAA.color(face.second); + rendererAA.color(*face); agg::render_scanlines(theRasterizer, slineP8, rendererAA); } } else { @@ -326,10 +323,10 @@ RendererAgg::_draw_path(path_t &path, bool has_clippath, const facepair_t &face, pixfmt_amask_type pfa(pixFmt, alphaMask); amask_ren_type r(pfa); amask_bin_renderer_type ren(r); - ren.color(face.second); + ren.color(*face); agg::render_scanlines(theRasterizer, scanlineAlphaMask, ren); } else { - rendererBin.color(face.second); + rendererBin.color(*face); agg::render_scanlines(theRasterizer, slineP8, rendererBin); } } @@ -459,7 +456,10 @@ RendererAgg::draw_path(GCAgg &gc, PathIterator &path, agg::trans_affine &trans, typedef agg::conv_curve curve_t; typedef Sketch sketch_t; - facepair_t face(color.a != 0.0, color); + std::optional face; + if (color.a != 0.0) { + face = color; + } theRasterizer.reset_clipping(); rendererBase.reset_clipping(true); @@ -468,7 +468,7 @@ RendererAgg::draw_path(GCAgg &gc, PathIterator &path, agg::trans_affine &trans, trans *= agg::trans_affine_scaling(1.0, -1.0); trans *= agg::trans_affine_translation(0.0, (double)height); - bool clip = !face.first && !gc.has_hatchpath(); + bool clip = !face && !gc.has_hatchpath(); bool simplify = path.should_simplify() && clip; double snapping_linewidth = points_to_pixels(gc.linewidth); if (gc.color.a == 0.0) { @@ -530,7 +530,10 @@ inline void RendererAgg::draw_markers(GCAgg &gc, curve_t path_curve(path_snapped); path_curve.rewind(0); - facepair_t face(color.a != 0.0, color); + std::optional face; + if (color.a != 0.0) { + face = color; + } // maxim's suggestions for cached scanlines agg::scanline_storage_aa8 scanlines; @@ -539,22 +542,14 @@ inline void RendererAgg::draw_markers(GCAgg &gc, rendererBase.reset_clipping(true); agg::rect_i marker_size(0x7FFFFFFF, 0x7FFFFFFF, -0x7FFFFFFF, -0x7FFFFFFF); - agg::int8u staticFillCache[MARKER_CACHE_SIZE]; - agg::int8u staticStrokeCache[MARKER_CACHE_SIZE]; - agg::int8u *fillCache = staticFillCache; - agg::int8u *strokeCache = staticStrokeCache; - try { - unsigned fillSize = 0; - if (face.first) { + std::vector fillBuffer; + if (face) { theRasterizer.add_path(marker_path_curve); agg::render_scanlines(theRasterizer, slineP8, scanlines); - fillSize = scanlines.byte_size(); - if (fillSize >= MARKER_CACHE_SIZE) { - fillCache = new agg::int8u[fillSize]; - } - scanlines.serialize(fillCache); + fillBuffer.resize(scanlines.byte_size()); + scanlines.serialize(fillBuffer.data()); marker_size = agg::rect_i(scanlines.min_x(), scanlines.min_y(), scanlines.max_x(), @@ -569,11 +564,8 @@ inline void RendererAgg::draw_markers(GCAgg &gc, theRasterizer.reset(); theRasterizer.add_path(stroke); agg::render_scanlines(theRasterizer, slineP8, scanlines); - unsigned strokeSize = scanlines.byte_size(); - if (strokeSize >= MARKER_CACHE_SIZE) { - strokeCache = new agg::int8u[strokeSize]; - } - scanlines.serialize(strokeCache); + std::vector strokeBuffer(scanlines.byte_size()); + scanlines.serialize(strokeBuffer.data()); marker_size = agg::rect_i(std::min(marker_size.x1, scanlines.min_x()), std::min(marker_size.y1, scanlines.min_y()), std::max(marker_size.x2, scanlines.max_x()), @@ -617,13 +609,13 @@ inline void RendererAgg::draw_markers(GCAgg &gc, amask_ren_type r(pfa); amask_aa_renderer_type ren(r); - if (face.first) { - ren.color(face.second); - sa.init(fillCache, fillSize, x, y); + if (face) { + ren.color(*face); + sa.init(fillBuffer.data(), fillBuffer.size(), x, y); agg::render_scanlines(sa, sl, ren); } ren.color(gc.color); - sa.init(strokeCache, strokeSize, x, y); + sa.init(strokeBuffer.data(), strokeBuffer.size(), x, y); agg::render_scanlines(sa, sl, ren); } } else { @@ -645,34 +637,25 @@ inline void RendererAgg::draw_markers(GCAgg &gc, continue; } - if (face.first) { - rendererAA.color(face.second); - sa.init(fillCache, fillSize, x, y); + if (face) { + rendererAA.color(*face); + sa.init(fillBuffer.data(), fillBuffer.size(), x, y); agg::render_scanlines(sa, sl, rendererAA); } rendererAA.color(gc.color); - sa.init(strokeCache, strokeSize, x, y); + sa.init(strokeBuffer.data(), strokeBuffer.size(), x, y); agg::render_scanlines(sa, sl, rendererAA); } } } catch (...) { - if (fillCache != staticFillCache) - delete[] fillCache; - if (strokeCache != staticStrokeCache) - delete[] strokeCache; theRasterizer.reset_clipping(); rendererBase.reset_clipping(true); throw; } - if (fillCache != staticFillCache) - delete[] fillCache; - if (strokeCache != staticStrokeCache) - delete[] strokeCache; - theRasterizer.reset_clipping(); rendererBase.reset_clipping(true); } @@ -957,10 +940,9 @@ inline void RendererAgg::_draw_path_collection_generic(GCAgg &gc, // Set some defaults, assuming no face or edge gc.linewidth = 0.0; - facepair_t face; - face.first = Nfacecolors != 0; + std::optional face; agg::trans_affine trans; - bool do_clip = !face.first && !gc.has_hatchpath(); + bool do_clip = Nfacecolors == 0 && !gc.has_hatchpath(); for (int i = 0; i < (int)N; ++i) { typename PathGenerator::path_iterator path = path_generator(i); @@ -991,7 +973,7 @@ inline void RendererAgg::_draw_path_collection_generic(GCAgg &gc, if (Nfacecolors) { int ic = i % Nfacecolors; - face.second = agg::rgba(facecolors(ic, 0), facecolors(ic, 1), facecolors(ic, 2), facecolors(ic, 3)); + face.emplace(facecolors(ic, 0), facecolors(ic, 1), facecolors(ic, 2), facecolors(ic, 3)); } if (Nedgecolors) { diff --git a/src/_macosx.m b/src/_macosx.m index aa2a6e68cda5..1372157bc80d 100755 --- a/src/_macosx.m +++ b/src/_macosx.m @@ -258,7 +258,7 @@ static void lazy_init(void) { } static PyObject* -stop(PyObject* self) +stop(PyObject* self, PyObject* _ /* ignored */) { stopWithEvent(); Py_RETURN_NONE; @@ -1863,7 +1863,7 @@ - (void)flagsChanged:(NSEvent *)event "written on the file descriptor given as argument.")}, {"stop", (PyCFunction)stop, - METH_NOARGS, + METH_VARARGS, PyDoc_STR("Stop the NSApp.")}, {"show", (PyCFunction)show, diff --git a/src/ft2font.cpp b/src/ft2font.cpp index 9726e96233ab..ca8881d98c50 100644 --- a/src/ft2font.cpp +++ b/src/ft2font.cpp @@ -1,5 +1,8 @@ /* -*- mode: c++; c-basic-offset: 4 -*- */ +#include "ft2font.h" +#include "mplutils.h" + #include #include #include @@ -9,9 +12,6 @@ #include #include -#include "ft2font.h" -#include "mplutils.h" - #ifndef M_PI #define M_PI 3.14159265358979323846264338328 #endif diff --git a/src/ft2font.h b/src/ft2font.h index 262ff395ac5d..0881693e7557 100644 --- a/src/ft2font.h +++ b/src/ft2font.h @@ -6,6 +6,9 @@ #ifndef MPL_FT2FONT_H #define MPL_FT2FONT_H +#include +#include + #include #include #include @@ -22,8 +25,6 @@ extern "C" { #include FT_TRUETYPE_TABLES_H } -#include -#include namespace py = pybind11; // By definition, FT_FIXED as 2 16bit values stored in a single long. diff --git a/tools/make_icons.py b/tools/make_icons.py index f09d40e92256..b253c0517c43 100755 --- a/tools/make_icons.py +++ b/tools/make_icons.py @@ -64,7 +64,7 @@ def make_icon(font_path, ccode): def make_matplotlib_icon(): fig = plt.figure(figsize=(1, 1)) fig.patch.set_alpha(0.0) - ax = fig.add_axes([0.025, 0.025, 0.95, 0.95], projection='polar') + ax = fig.add_axes((0.025, 0.025, 0.95, 0.95), projection='polar') ax.set_axisbelow(True) N = 7