Search code examples
pythonmatplotlibperfplot

How to prevent perfplot (matplotlib) graph labels from being truncated?


I'm working with the perfplot library (which you can pip-install) which benchmarks functions and plots their performance.

When observing the plotted graphs, the labels are truncated. How can I prevent this?

Here's a simple MCVE:

import perfplot 
from itertools import chain

perfplot.__version__
# '0.8.8'

perfplot.show(
    setup=lambda n: [[1] * 100] * n,
    kernels=[
        lambda L: sum(L, []),
        lambda L: list(chain.from_iterable(L))
    ],
    labels=['list_concat_sum', 'list_concat_chain'],
    n_range=range(1, 500, 100),
    xlabel='# lists',
    logy=True,
    logx=True)

This produces:

You'll notice the graph labels are truncated. Is there a way to prevent this, or change the graph to output a Legend?


Solution

  • perfplot seems to use matplotlib for the display. According to the github site, you can separate calculation and plotting, giving you the possibility to inject an autoformat (basically plt.tight_layout()) with rcParams for this graph.

    You can add the following before your script:

    from matplotlib import pyplot as plt
    plt.rcParams["figure.autolayout"] = True
    

    Sample output: enter image description here

    Possible interactions with other graphs, though, when using this approach.