Pandas.plot Multiple plot same figure

11,474

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()
Share:
11,474
Boat
Author by

Boat

** informatic is a tool like a pen or a brush. **

Updated on June 19, 2022

Comments

  • Boat
    Boat almost 2 years

    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?

  • Boat
    Boat over 6 years
    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.
  • ImportanceOfBeingErnest
    ImportanceOfBeingErnest over 6 years
    In the code from my answer there is only one single figure and that figure is saved.
  • Boat
    Boat over 6 years
    weird using the exact same code keeps showing me 10 figures.
  • Boat
    Boat over 6 years
    Okay got it forgot the ax=ax for the first plot. Thanks again.