遍历数据并创建单个图形 [英] Looping over data and creating individual figures

查看:49
本文介绍了遍历数据并创建单个图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

任何帮助将不胜感激!

推荐答案

尝试使用更多的 OOP 方法,使用图形和子图.例如,

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.

一个更好的选择是在循环外创建图形和轴,并在每次绘制前清除循环.谢谢@Rutger Kassies

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

编辑 2:

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

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]

这篇关于遍历数据并创建单个图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆