Search code examples
pythonmatplotlibsubplot

Why are my subplots plotting only to the last ax?


So in Spyder IPython and in Jupyter notebook, the following code is failing to create subplots:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
mydict = {'a': [1,2,3,4], 'b':[2,3,4,5], 'c':[3,4,5,6]}
df = pd.DataFrame(mydict)
fig, axes = plt.subplots(3,1)
axes[0] = plt.plot(df.a)
axes[1] = plt.plot(df.b)
axes[2] = plt.plot(df.c)
plt.show(fig)

and it gives back the following plot: enter image description here

this also happens when I copy-c copy-vd the example code from the matplotlib webpage

what I would like is the three columns in the three different subplots to be plotted


Solution

  • If you create your axes using plt.subplots you are using the object oriented approach in matplotlib. Then you have to call plot() on the axes object, so axes[0].plot(df.a), not plt.plot.

    What you are doing is a weird hybrid between the procedural and object oriented approach and you also overwrite the axes objects that you created when you write axes[0] = plt.plot(....

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    mydict = {'a': [1,2,3,4], 'b':[2,3,4,5], 'c':[3,4,5,6]}
    df = pd.DataFrame(mydict)
    fig, axes = plt.subplots(3,1)
    axes[0].plot(df.a)
    axes[1].plot(df.b)
    axes[2].plot(df.c)
    plt.show()