Skip to content

[Bug]: Large file size when using fill_between() #22803

Open

Description

@tgrohens

Bug summary

Hi,

I am trying to save a plot to PDF (or SVG) that uses the fill_between function between two time series, and the resulting file is much larger than when plotting each series individually.

Code for reproduction

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(seed=424242)

t_max = int(1e5)
t = np.arange(1, t_max+1, dtype=int)

data = rng.normal(size=(10, t_max))

# Lightweight figure (266 kb)
plt.figure(dpi=200)

plt.plot(t, np.min(data, axis=0), color='tab:blue', alpha=0.75)
plt.plot(t, np.max(data, axis=0), color='tab:blue', alpha=0.75)

plt.xlim(1, t_max)
plt.savefig(f"plot_minmax_{t_max}.svg")

# Large figure (1.1 Mb)
plt.figure(dpi=200)
plt.fill_between(t, np.min(data, axis=0), np.max(data, axis=0), color='tab:blue', alpha=0.5)
plt.xlim(1, t_max)
plt.savefig(f"plot_fill_{t_max}.svg")

Actual outcome

plot_minmax_2e+04
plot_fill_2e+04

Expected outcome

The file size of the file drawn with fill_between() should stay roughly the same as the file drawing the min and the max only.

Additional information

I have plotted the resulting file sizes for different numbers of data points.
The file size of the file generated with fill_between() grows linearly with the number of data points (as could be expected), but not the file size of the file plotting the min and the max directly: maybe there's an optimization in plot() that's not being used in fill_between() ?
download

Operating system

macOS

Matplotlib Version

3.4.3

Matplotlib Backend

module://matplotlib_inline.backend_inline

Python version

Python 3.9.7

Jupyter version

No response

Installation

pip

Activity

  1. jklymak commented on Apr 8, 2022

    @jklymak
    Member

    Yes, Line2D starts subsampling un-resolved data. https://matplotlib.org/stable/users/explain/performance.html#line-segment-simplification. OTOH, I don't see this rcParam mentioned at all in the docstring for Line2D, nor in the docstring for plot, which is a pretty big oversight in my opinion. Labelling as a documentation issue and good first issue, as it just requires mentioning the rcParams and linking to the explanation.

  2. tgrohens commented on Apr 8, 2022

    @tgrohens
    Author

    Thanks for the additional information!

    From looking at the performance page and the code of fill_between, the function generates a polygon, so I understand the line segments it comprises should be simplified as well?

  3. jklymak commented on Apr 8, 2022

    @jklymak
    Member

    I don't think so - Polygons derive from Patch and do not have the Path logic in them.

  4. tgrohens commented on Apr 8, 2022

    @tgrohens
    Author

    Ah, I see; in this case, maybe the documentation should be updated to reflect that?

    It currently states (emphasis mine):

    For plots that have line segments (e.g. typical line plots, outlines of polygons, etc.),

  5. jklymak commented on Apr 8, 2022

    @jklymak
    Member

    Maybe? I could be wrong, but I don't think it applies to polygons.

  6. tgrohens commented on Apr 8, 2022

    @tgrohens
    Author

    Do you mean the outline of a polygon is different than a polygon?
    In this case, my bad!

  7. jklymak commented on Apr 8, 2022

    @jklymak
    Member

    Well there are "polygons" and then there are instances of the Polygon class. I am pretty sure instances of the Polygon class cannot simplify. I agree that the docs shouldn't make it sound like Polygons will simplify, and that may have just been a mistake?

  8. tacaswell commented on Apr 9, 2022

    @tacaswell
    Member

    I agree with Jody, I think in that prose we are using "polygon" in the colloquial sense (in that we all look at the screen and agree it is "the outline of a ploygon") rather than a claim "that is a Polygon instance that is rendering the (thing we look at and call a polygon in english) on the screen".

    It is probably worth looking into if we do not use the path simplifiaction logic in drawing patches because we can not (at least with clipping there are good reasons we can not clip filled shapes) or because no one has tried to write the code to use the simplification logic.

    I think the steps here are:

    1. sort out if we are already trying to use Path Simplification when drawing patches
    2. if we are, sort out why it is not being used in this case and if there is a good reason for that
    3. if we are not, implement its usage (and see what breaks ;) ) This should follow the same configuration knobs as Line2D
    4. write tests !

    I'm going to label this a good first issue as it should involve no new API design (public API has to stay the same, we already have the path simplification code used else where in the code base, use the same rcparams), but medium difficulty because it will require reading and understanding where we do the path simplification in Line2D and than adapting it for use in Patch (or its subclasses)

  9. added
    Difficulty: Mediumhttps://matplotlib.org/devdocs/devel/contribute.html#good-first-issues
    on Apr 9, 2022
  10. Nishantppanchal commented on Apr 10, 2022

    @Nishantppanchal

    Hey @tacaswell, could I be assigned to this issue? I am a first-year computer science student looking to take on a project to gain so experience and for fun of course. Just note, It may take me a bit of time however as I have to balance with uni.

  11. jklymak commented on Apr 10, 2022

    @jklymak
    Member

    @Nishantppanchal We do not assign or reserve issues. Thanks for your understanding.

  12. Nishantppanchal commented on Apr 10, 2022

    @Nishantppanchal

    @jklymak No problem.

  13. wannieman98 commented on Apr 28, 2022

    @wannieman98

    Hi, I wanted to give this issue a try but wanted to clarify the tasks. My understanding with the comment @tacaswell has written. Is this simply a documentation issue or should the implementation of the simplification logic completed as well?

  14. 20 remaining items

  15. tacaswell commented on Oct 7, 2025

    @tacaswell
    Member

    Yes, feel free to work on this issue.

  16. tacaswell commented on Nov 19, 2025

    @tacaswell
    Member

    @cinocefalia Please see #22803 (comment) for the broad path of work here. I would add the additional first step of summarizing all of @tgrohens 's comments into a single post.

  17. gigoiy commented on Dec 9, 2025

    @gigoiy

    Thank you @cinocefalia for the summarization of the thread for newcomers. I'll happily take this issue if it's still in limbo with no PR or contributors actively working on it. I'm starting work on it now. Actually, just read through the whole summary, is this issue about to be resolved?

  18. gigoiy commented on Dec 12, 2025

    @gigoiy

    @cinocefalia I actually picked up a different issue that I've been working on, but I may try and tackle this one afterwards

  19. added a commit that references this issue on Jan 23, 2026
    e69454f
  20. Silvio-Re commented on Feb 27, 2026

    @Silvio-Re

    Hello,

    Thank you very much cinocefalia for providing a fix.
    As I needed it now (some publication plots and the resulting files were really heavy), I made an AI make a monkey patch, and as it seems to work, I feel like I had to share if others need it now.
    The test is made by hand and also tested on other plots. Not tested on pdf.
    Below the "after.svg" (175.8 Kio), whereas the "before.svg" is 4.8 Mio and nearly identical (I will not upload it here, enough wasted resources for today).

    Image

    Code
    import matplotlib as mpl
    from matplotlib.collections import FillBetweenPolyCollection
    from matplotlib.backends.backend_svg import RendererSVG
    from matplotlib.backends.backend_pdf import RendererPdf
    from matplotlib import transforms as mtransforms
    
    def apply_matplotlib_simplify_patches():
        """
        Apply monkeypatches to matplotlib to enable path simplification for fill_between in SVG/PDF backends.
        /!\ : AI generated :( 
        """
    
        # =============================================================================
        # 1. Patch FillBetweenPolyCollection to mark paths as simplifiable
        # =============================================================================
        def patched_set_verts(self, verts, closed=True):
            super(FillBetweenPolyCollection, self).set_verts(verts, closed=closed)
            if self._paths is not None:
                for p in self._paths:
                    setattr(p, "should_simplify", True)
    
        if not hasattr(FillBetweenPolyCollection, "_is_patched"):
            FillBetweenPolyCollection.set_verts = patched_set_verts
            FillBetweenPolyCollection.set_paths = FillBetweenPolyCollection.set_verts
            FillBetweenPolyCollection._is_patched = True
    
        # =============================================================================
        # 2. Patch SVG backend's draw_path in RendererSVG to use should_simplify flag
        # =============================================================================
        def patched_draw_path(self, gc, path, transform, rgbFace=None):
            should = getattr(path, "should_simplify", False)
            simplify = (
                should
                and mpl.rcParams.get("path.simplify", False)
                and mpl.rcParams.get("path.simplify_threshold", 0) > 0
            )
    
            if simplify:
                try:
                    path = path.cleaned(transform=transform, simplify=True)
                    transform = mtransforms.IdentityTransform()
                except Exception:
                    pass
    
            return RendererSVG.draw_path_original(self, gc, path, transform, rgbFace)
    
        if not hasattr(RendererSVG, "_is_draw_path_patched"):
            RendererSVG.draw_path_original = RendererSVG.draw_path
            RendererSVG.draw_path = patched_draw_path
            RendererSVG._is_draw_path_patched = True
    
        # =============================================================================
        # 3. Patch PDF backend's draw_path_collection to respect should_simplify flag
        # =============================================================================
        def patched_draw_path_collection(self, gc, path_collection, transform):
            paths = path_collection.get_paths()
            transforms = path_collection.get_transforms()
            if transforms is None:
                transforms = [transform] * len(paths)
    
            any_should_simplify = any(getattr(p, "should_simplify", False) for p in paths)
            if any_should_simplify:
                simplify = (
                    mpl.rcParams.get("path.simplify", False)
                    and mpl.rcParams.get("path.simplify_threshold", 0) > 0
                )
                for i, path in enumerate(paths):
                    if getattr(path, "should_simplify", False):
                        try:
                            cleaned = path.cleaned(transform=transforms[i], simplify=simplify)
                            paths[i] = cleaned
                            transforms[i] = mtransforms.IdentityTransform()
                        except Exception:
                            pass
                path_collection.set_paths(paths)
                path_collection.set_transforms(transforms)
    
            return RendererPdf.draw_path_collection_original(self, gc, path_collection, transform)
    
        if not hasattr(RendererPdf, "_is_draw_path_collection_patched"):
            RendererPdf.draw_path_collection_original = RendererPdf.draw_path_collection
            RendererPdf.draw_path_collection = patched_draw_path_collection
            RendererPdf._is_draw_path_collection_patched = True
    
        print("Monkeypatches applied to matplotlib SVG/PDF backends.")
    
    import numpy as np
    import matplotlib.pyplot as plt
    
    def test(name):
        x = np.linspace(0, 2, 50000)
        y = np.sin(x**10)
        
        fig, ax = plt.subplots(figsize=(10, 4))
        
        theta = x*np.pi/4
        r = y + 1.5 
        x_spiral = r * np.cos(theta)
        y_spiral = r * np.sin(theta)
        
        ax.plot(x, y,)
        ax.plot(x, y+1)
        ax.plot(x_spiral,y_spiral )
        ax.fill_betweenx(y_spiral, x_spiral, 0, alpha=0.5)
        x_spiral
        
        ax.fill_between(x, y,y+1, alpha=0.2)
        ax.set_xlabel("x")
        ax.set_ylabel("y")
        ax.set_title("test")
        ax.grid(True)
        # ax.set_xlim([0, ])
        fig.savefig(name+".svg")
    
    test("before")
    apply_matplotlib_simplify_patches()
    test("after")
  21. saitejaponnam12 commented on Mar 23, 2026

    @saitejaponnam12

    Hi, I'd like to work on this issue.
    I can start by reproducing the problem and investigating a possible fix.
    Please let me know if it's available.

  22. saitejaponnam12 commented on Mar 25, 2026

    @saitejaponnam12

    Thanks for the feedback and discussion.

    I noticed there are ongoing PRs (#31354, #31359) addressing similar path simplification
    for fill_between in the vector backends.

    If those approaches are preferred, I’m happy to step back or adjust this PR accordingly.
    This was a useful exploration for me to understand how collections and path simplification
    work in Matplotlib.

    Please let me know if there’s a related follow-up or smaller improvement I could work on.

  23. saitejaponnam12 commented on Mar 26, 2026

    @saitejaponnam12

    Thanks for the clarification!
    Glad to hear the approach looks less intrusive. I'll continue refining the solution and ensure it passes the full checks. Let me know if you'd like me to adjust anything specific.

  24. Abhijeet-Kanungo commented on Mar 29, 2026

    @Abhijeet-Kanungo

    Hi! I am a 3rd-year Mechanical Engineering student from OUTR Bhubaneswar, and I am currently drafting a GSoC 2026 proposal to enhance mplot3d. I would like to work on this issue to familiarize myself with the 3D axis rendering logic. Is it okay if I take this up?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Difficulty: Mediumhttps://matplotlib.org/devdocs/devel/contribute.html#good-first-issues🌱 Good first issueOpen a pull request against these issues if there are no active ones!

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions