Jsg91
Jsg91

Reputation: 465

Looping over data and creating individual figures

I'm looping over a list of names of different molecules and trying to generate individual figs for each of them. But for each successive molecule the new figures have all the previous data on as well. I've printed the data after I've gathered it and for each loop it's showing the correct amount. Here's my full code

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

mols = ["P_Z1", "P_Z2", "TT_Z1", "TT_Z2", "TP_Z1", "TP_Z2"]


for mol in mols:
    en = []
    den = []
    with open (mol+"clustered.txt") as f:
        for line in f:
            e = line.strip().split()[1]
            en.append(e)
    with open (mol+"densities.txt") as g:
        for line in g:
            d = line.strip()
            den.append(d)
    data = zip(en,den)
    print data
    for energy, density in data:
        plt.xlabel("Density g/cubic cm")
        plt.ylabel("Energy kJ/mol")
        ax = plt.gca()
        ax.spines["right"].set_color('none')
        ax.xaxis.set_ticks_position('top')
        ax.yaxis.set_ticks_position('left')
        ax.spines["bottom"].set_color('none')
        ax.xaxis.set_label_position('top')
        ax.spines['left'].set_color('black')
        ax.spines['top'].set_color('black')
        ax.xaxis.label.set_color('black')
        ax.yaxis.label.set_color('black')
        ax.tick_params(colors='black')
        plt.plot(density, energy, "ro")
        plt.savefig(mol+".png", bbox_inches="tight", dpi=200, transparent=True)

Any help would be greatly appreciated!

Upvotes: 2

Views: 6916

Answers (1)

wflynny
wflynny

Reputation: 18521

Try using the more OOP approach using figures and subplots. For example,

for mol in mols:
    for energy, density in data:
        fig = plt.figure()
        ax = fig.addsubplot(111)
        ax.plot(density, energy, 'ro')

        ax.set_xlabel(...)
        ax.set_ylabel(...)
        [a.label.set_color('black') for a in (ax.xaxis, ax.yaxis)]
        # more spines and axis tinkering


        fig.savefig(mol+".png")

This way, you create a new figure for each energy/density plot.

Edit:

An even better alternative is to create the figure and axis outside the loop and just clear the loop before each plot. Thanks @Rutger Kassies

fig = plt.figure()
ax = fig.addsubplot(111)
for mol in mols:
    for energy, density in data:
        ax.cla() # or ax.clear()
        ax.plot(density, energy, 'ro')

        ax.set_xlabel(...)
        ax.set_ylabel(...)
        [a.label.set_color('black') for a in (ax.xaxis, ax.yaxis)]
        # more spines and axis tinkering

        fig.savefig(mol+".png")

Edit2:

Updating with @tcaswell's suggestions.

# Create the figure and subplot
fig = plt.figure()
ax = fig.addsubplot(111)

# Tinker with labels and spines
ax.set_xlabel(...)
ax.set_ylabel(...)
[a.label.set_color('black') for a in (ax.xaxis, ax.yaxis)]
...

# Plot data and save figures
for mol in mols:
    for energy, density in data:
        ax.cla() # or ax.clear()
        p, = ax.plot(density, energy, 'ro')

        fig.savefig(mol+".png")
        p.remove() # removes specific plot from figure

Note that this will only render one density/energy line per figure. If you want to have multiple lines per figure, do something like

# same preamble
for mol in mols:
    lines = []
    for energy, density in data:
        ax.cla() # or ax.clear()
        p, = ax.plot(density, energy, 'ro')
        lines.append(p)

        fig.savefig(mol+".png")
    [p.remove() for p in lines]

Upvotes: 3

Related Questions