Search code examples
listmatplotlibplotlist-comprehensionfigure

Plotting separate figures using list comprehension


My current code produces overlapping figures for each element in the list test. How can I produce two separate figures using list comprehension? (Preferably using just one line of code).

test=[[1, 2, 3, 4],[5, 6, 7, 8]]
[plt.plot(test[k]) for k in range(0,2)]

Current output looks like this:

Current output


Solution

  • As explained in the Matplotlib Usage Guide, plt.plot works the same way as the ax.plot graphing method:

    for each Axes graphing method, there is a corresponding function in the matplotlib.pyplot module that performs that plot on the "current" axes, creating that axes (and its parent figure) if they don't exist yet.

    So when you run the list comprehension you have given as an example, the first plt.plot method call in the for loop creates a new figure object containing a child Axes object. Then, as noted in the Matplotlib Pyplot tutorial section on working with multiple figures and axes:

    MATLAB, and pyplot, have the concept of the current figure and the current axes. All plotting functions apply to the current axes.

    This is why all the subsequent plt.plot calls in the loop are being plotted in the same figure. To draw the lines in separate figures, a new figure must be created for each plt.plot call, like so:

    test = [[1, 2, 3, 4],[5, 6, 7, 8]]
    for k in range(len(test)): plt.figure(), plt.plot(test[k])
    

    Edit: based on the comment by JohanC (on the question), replaced list comprehension with a single-line compound statement. Even though this goes against PEP 8 recommendations, it does indeed make the code more readable while meeting the one-line requirement.