4

I have multiple CSV files that I am trying to plot in same the figure to have a comparison between them. I already read some information about pandas problem not keeping memory plot and creating the new one every time. People were talking about using an ax var, but I do not understand it...

For now I have:

def scatter_plot(csvfile,param,exp):
    for i in range (1,10):
        df = pd.read_csv('{}{}.csv'.format(csvfile,i))
        ax = df.plot(kind='scatter',x=param,y ='Adjusted')
        df.plot.line(x=param,y='Adjusted',ax=ax,style='b')
    plt.show()
    plt.savefig('plot/{}/{}'.format(exp,param),dpi=100)

But it's showing me ten plot and only save the last one. Any idea?

2
  • (1) plt.savefig needs to come before plt.show. (2) plt.show() should be outside the loop. (3) You can create an axes to plot to outside the loop, ax=plt.gca(); for i in range(1,10): ... df.plot(ax=ax) Commented Nov 28, 2017 at 21:26
  • still not getting it Commented Nov 28, 2017 at 21:31

1 Answer 1

10

The structure is

  1. create an axes to plot to
  2. run the loop to populate the axes
  3. save and/or show (save before show)

In terms of code:

import matplotlib.pyplot as plt
import pandas as pd

ax = plt.gca()
for i in range (1,10):
    df = pd.read_csv(...)
    df.plot(..., ax=ax)
    df.plot.line(..., ax=ax)

plt.savefig(...)
plt.show()
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for that really appreciate. One thing remains is that when I save the figure it only select the last one. And only the figure one has all the plot.
In the code from my answer there is only one single figure and that figure is saved.
weird using the exact same code keeps showing me 10 figures.
Okay got it forgot the ax=ax for the first plot. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.