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
    – Boat
    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()
4
  • 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.
    – Boat
    Commented Nov 28, 2017 at 22:29
  • In the code from my answer there is only one single figure and that figure is saved. Commented Nov 28, 2017 at 22:31
  • weird using the exact same code keeps showing me 10 figures.
    – Boat
    Commented Nov 28, 2017 at 22:34
  • Okay got it forgot the ax=ax for the first plot. Thanks again.
    – Boat
    Commented Nov 28, 2017 at 22:45

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.