-1

I'm trying to plot different dataframes in a plot (each dataframe is a subplot).

I'm doing:

plt.figure(figsize=(20,20))

for i,name in enumerate(names):
    df = pd.read_excel(myPath+name)
    df['Datetime'] = pd.to_datetime(df['Datetime'])
    df = df.set_index('Datetime')
    
    plt.subplot(4, 1, i+1) # I have 4 dataframes
    df.plot()
plt.show()

But I obtain this...

enter image description here

How can I do it correctly?

Thank you!

Lleims
  • 1,275
  • 12
  • 39

1 Answers1

1

df.plot doesn't integrate too well in more complex plotting patterns. It's meant more as a shortcut to get a quick plot from your Dataframe while doing data exploration.

Thus, you end up creating 4 empty subplots and 4 df.plot(). I imagine that the first 3 df.plot results plots are overridden by the last one. This is probably due to the figure/axes handling of df.plot which is outside the scope of this question.

Try something like this instead.

fig, axes = plt.subplots(4, 1)


for i,name in enumerate(names):
    df = pd.read_excel(myPath+name)
    df['Datetime'] = pd.to_datetime(df['Datetime'])
    df = df.set_index('Datetime')
    axes[i].plot(df)
    
plt.show()

For more information on proper use of subplots, have a look at these examples: https://matplotlib.org/3.1.0/gallery/subplots_axes_and_figures/subplots_demo.html

EDIT: I had misread your code and my previous comments about specifying the keys were probably erroneous. I have updated my answer now. Hope it works for you

Mazata
  • 73
  • 6