2

我正在遍历不同分子的名称列表,并尝试为每个分子生成单独的无花果。但是对于每个连续的分子,新数字也包含所有以前的数据。我在收集数据后打印了数据,并且每个循环都显示了正确的数量。这是我的完整代码

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)

任何帮助将不胜感激!

4

1 回答 1

3

尝试使用使用图形和子图的更多 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")

编辑2:

更新@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]
于 2013-09-27T14:22:28.930 回答