1

Hello I am having a problem plotting data from pandas dataframes. Within a few for loops I would like to create one large scatter plot (multiplots.png), to which new data is added in every loop, while also creating separate plots that are plotted and saved in every j loop (plot_i_j.png).

In my code the plots_i_j.png figures are produced correctly, but multiplots.png always ends up being the last plot_i_j.png figure. As you can see, I am trying to plot multiplots.png on axComb, while the plot_i_j.png figures are plotted on ax. Can anyone help me on this please?

import pandas as pd
import matplotlib.pyplot as plt

columnNames = ['a','b']
scatterColors = ['red','blue','green','black']

figComb, axComb = plt.subplots(figsize=(8,6))

for i in range(4): # this is turbine number
    df1 = pd.DataFrame(np.random.randn(5, 2), columns=columnNames)
    df2 = pd.DataFrame(np.random.randn(5, 2), columns=columnNames)
    print(df1)
    for j in range(2):
        fig, ax = plt.subplots(figsize=(8,6))
        fig.suptitle(str(i)+'_'+str(j), fontsize=16)
        df1.plot(columnNames[j], ax=ax, color='blue', ls="--")
        plt.savefig('plot_'+str(i)+'_'+str(j)+'.png')
        df1.reset_index().plot.scatter('index',columnNames[j],3,ax=axComb,color=scatterColors[j])
        df2.reset_index().plot.scatter('index',columnNames[j],100,ax=axComb,color=scatterColors[j])   
plt.savefig('multiPlots.png')
RichardMc
  • 13
  • 3
  • It doesn't look that hard to do have a look here: https://stackoverflow.com/questions/17788685/python-saving-multiple-figures-into-one-pdf-file wouldn't that give you what you want? – cardamom Aug 08 '18 at 10:00
  • @cardamom not at all the issue. – Mathieu Aug 08 '18 at 10:04

1 Answers1

0

Really a small error. When you do plt.savefig, matplotlib looks for the last called figure.

Replace the plt.savefig('plot_'+str(i)+'_'+str(j)+'.png') with fig.savefig('plot_'+str(i)+'_'+str(j)+'.png').

And replace plt.savefig('multiPlots.png') by figComb.savefig('multiPlots.png').

Mathieu
  • 5,410
  • 6
  • 28
  • 55