Skip to content

[Bug]: matplotlib.pyplot.clf is very slow #23771

@eendebakpt

Description

@eendebakpt

Bug summary

For relatively simple plotting examples the plt.clf() command can take over 30% of the calculation time. One would expect that a clear command is relatively simple and takes a limited amount of time

Code for reproduction

import numpy as np
import time
import matplotlib
import matplotlib.pyplot as plt
print(matplotlib.__version__)

def profile_expression(expression):
    import cProfile  
    import tempfile
    import os
    import subprocess
    tmpdir = tempfile.mkdtemp()
    statsfile = os.path.join(tmpdir, "profile_expression_stats")
    print("profile_expression: running")
    t0 = time.perf_counter()
    cProfile.run(expression, statsfile)
    dt = time.perf_counter() - t0
    print(f"profiling: {dt:.2f} [s]")
    r = subprocess.Popen(["snakeviz", statsfile])
    return r

x=np.linspace(0, 10, 1000)
y=np.linspace(0, 20, 1000)**0.1

def go():
    for ii in range(5):
        plt.figure(100); 
        plt.clf()
        plt.plot(x, y, '.', label='n')
        plt.plot(x, y+x, '.-', label='m')
        plt.xlabel('dsf')
        plt.title('sdfs')
        plt.legend()
        plt.draw()

if __name__=='__main__':
    profile_expression('go()')

Actual outcome

The output of the minimal example (which requires https://github.com/jiffyclub/snakeviz to be installed) is a profiling graph of the code executed in the minimal example:

image

Expected outcome

The plt.clf() should be very fast compared to the actual plotting. Going into the details of the profiling results shows a large amount of time being spend in axis.reset_ticks.

Additional information

No response

Operating system

Windows

Matplotlib Version

3.6.0.dev3058+g87197156eb

Matplotlib Backend

Qt5Agg

Python version

3.10.0

Jupyter version

No response

Installation

git checkout

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions