循环数据并创建个人数据

时间:2013-09-27 14:19:08

标签: python matplotlib

我正在循环查看不同分子的名单,并尝试为每个分子生成单独的无花果。但对于每个连续的分子,新数据也包含所有先前的数据。我收集完数据后打印数据,每个循环显示数据正确。这是我的完整代码

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)

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

尝试使用更多OOP方法使用数字和子图。例如,

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")

这样,您可以为每个能量/密度图创建一个新图。

修改

更好的选择是在循环外创建图形和轴,并在每个绘图之前清除循环。谢谢@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:

使用@ tcaswell的建议进行更新。

# 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

请注意,这只会为每个数字渲染一条密度/能量线。如果你想在每个数字上有多行,请执行类似

的操作
# 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]