Matplotlib Save Figures Write Over Each Other

Question:

I have two functions that create saved graphs, but the second graph always has the first graph laid over it – here is the code to reproduce the problem. In this case graph.png will be a combination of dendo.png and what was supposed to be graph.png by itself. Is this just way Matplotlib works or is there something I’m missing?

def dendo(): 
  # Create an array
  x = np.array([100., 200., 300., 400., 500., 250.,
              450., 280., 450., 750.])

  Z=linkage(x,'ward')
  dendrogram(Z, leaf_rotation=45., leaf_font_size=12.)
  plt.title('Hierarchical Clustering Dendrogram')
  plt.xlabel('Cluster Size')
  plt.ylabel('Distance')
  plt.rcParams["figure.figsize"] = (9,8)
  plt.savefig('dendo.png')

def stats():
  df = pd.DataFrame({'gmat':[ 580.0, 660.0, 740.0, 590.0, 660.0, 540.0, 690.0, 550.0, 580.0, 620.0, 710.0, 660.0, 780.0, 680.0, 680.0, 550.0, 580.0, 650.0, 620.0, 750.0, 730.0, 690.0, 570.0, 660.0, 690.0, 650.0, 670.0, 690.0, 690.0, 590.0],
'gpa': [2.7, 3.3, 3.3, 1.7, 4.0, 2.7, 2.3, 2.7, 2.3, 2.7, 3.7, 3.3, 4.0, 3.3, 3.9, 2.3, 3.3, 3.7, 3.3, 3.9, 3.7, 1.7, 3.0, 3.7, 3.3, 3.7, 3.3, 3.7, 3.7, 2.3],
'work_experience': [4.0, 6.0, 5.0, 4.0, 4.0, 2.0, 1.0, 1.0, 2.0, 2.0, 5.0, 5.0, 3.0, 4.0, 4.0, 4.0, 1.0, 6.0, 2.0, 4.0, 6.0, 1.0, 2.0, 4.0, 3.0, 6.0, 6.0, 5.0, 5.0, 3.0],
'admitted': [0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0]})
  Xtrain = df[['gmat', 'gpa', 'work_experience']]
  ytrain = df[['admitted']]
  log_reg = sm.Logit(ytrain, Xtrain).fit()
  stats1=log_reg.summary()
  plt.rc('figure', figsize=(12, 7))
  plt.text(0.01, 0.05, str(stats1), {'fontsize': 10}, fontproperties = 'monospace') 
  plt.axis('off')
  plt.tight_layout()
  plt.savefig('graph.png')


dendo()

stats()
Asked By: Allen

||

Answers:

There are two ways (can’t use your code since it’s not reproducible):

  1. Use plt.figure before drawing a new figure:
    # 1st figure
    plt.figure(0)
    plt.plot(range(10))
    plt.savefig('0.png')

    # 2nd figure
    plt.figure(1)
    plt.plot(sorted(range(10), reverse = True))
    plt.savefig('1.png')
  1. Use plt.subplots:
    # 1st figure
    fig1, ax1 = plt.subplots()
    ax1.plot(range(10))
    fig1.savefig('1.png')
    
    # 2nd figure
    fig2, ax2 = plt.subplots()
    ax2.plot(sorted(range(10), reverse = True))
    fig2.savefig('2.png')

For more details see documentation or matplotlib examples.

Answered By: Ivan Chernyshov
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.