How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

前端 未结 4 1918
执念已碎
执念已碎 2020-11-30 17:03

I want to plot data, then create a new figure and plot data2, and finally come back to the original plot and plot data3, kinda like this:

import numpy as np
         


        
4条回答
  •  情深已故
    2020-11-30 17:28

    If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.arange(5)
    y = np.exp(x)
    fig1, ax1 = plt.subplots()
    ax1.plot(x, y)
    ax1.set_title("Axis 1 title")
    ax1.set_xlabel("X-label for axis 1")
    
    z = np.sin(x)
    fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
    ax2.plot(x, z)
    ax3.plot(x, -z)
    
    w = np.cos(x)
    ax1.plot(x, w) # can continue plotting on the first axis
    

    It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.

提交回复
热议问题