How do I get multiple subplots in matplotlib?

后端 未结 6 857
自闭症患者
自闭症患者 2020-11-22 06:49

I am a little confused about how this code works:

fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()

How does the fig, axes work in this

6条回答
  •  终归单人心
    2020-11-22 06:59

    There are several ways to do it. The subplots method creates the figure along with the subplots that are then stored in the ax array. For example:

    import matplotlib.pyplot as plt
    
    x = range(10)
    y = range(10)
    
    fig, ax = plt.subplots(nrows=2, ncols=2)
    
    for row in ax:
        for col in row:
            col.plot(x, y)
    
    plt.show()
    

    However, something like this will also work, it's not so "clean" though since you are creating a figure with subplots and then add on top of them:

    fig = plt.figure()
    
    plt.subplot(2, 2, 1)
    plt.plot(x, y)
    
    plt.subplot(2, 2, 2)
    plt.plot(x, y)
    
    plt.subplot(2, 2, 3)
    plt.plot(x, y)
    
    plt.subplot(2, 2, 4)
    plt.plot(x, y)
    
    plt.show()
    

提交回复
热议问题