Python读取多个.txt并以相同的图形绘制

时间:2018-12-19 20:33:37

标签: python matplotlib plot

我有两个具有数千行格式的.txt文件

episode:2840  score:6.0  memory length:700345  epsilon:0.5576491831247304   steps:359    recent reward:5.95
episode:2841  score:4.0  memory length:700629  epsilon:0.5574965123606621   steps:284    recent reward:5.96
episode:2842  score:5.0  memory length:700911  epsilon:0.5573449596383373   steps:282    recent reward:5.93
Max lifes :5
episode:2800  score:7.0  memory length:687331  epsilon:0.5646918805492361   steps:268    recent reward:6.04
episode:2801  score:5.0  memory length:687678  epsilon:0.5645029051613243   steps:347    recent reward:6.03
episode:2802  score:6.0  memory length:688027  epsilon:0.564312906709082   steps:349    recent reward:6.03

我想绘制recent_reward列如何在episodes上变化。删除Max lifes :5和重复行episode的某些行后,结果得到两个不同的图,每个文件一个。但是,目标是将它们一起绘制在一个图中,以显示两个文件rewardsepisodes的区别。有人可以帮忙吗?

这是我的代码:

import matplotlib.pyplot as plt
import glob


# Read any .txt output file
path = '/home/plots/*.txt' 
files = glob.glob(path)


for name in files:
    # Read lines from file
    with open(name) as f:
        lines = f.readlines()

    # Extract episode/reward data points
    episodes = []
    rewards = []
    for line in lines:
        columns = line.split()
        if not columns[0].startswith("episode"):
            # Not a line with episode/reward data
            continue
        try:
            episode = int(columns[0].split(":")[1])
            reward = float(columns[7].split(":")[1])
        except:
            # Not a number
            continue
        if episode in episodes:
            # We don't want repeated episodes
            continue
        episodes.append(episode)
        rewards.append(reward)


    print(episodes,rewards)
    
    #plot both in the same figure
    #plt.plot(episodes, rewards, episodes, rewards)
    #plt.show()
    
    # Plot data every 1000 steps
    N = 1000
    for i in range(int(len(l_episodes)/N)+1):
        plt.plot(l_episodes[i*N:i*N+N], l_rewards[i*N:i*N+N])
        plt.xlabel('episodes', fontsize=12)
        plt.ylabel('rewards', fontsize=12)
        plt.savefig("plot{}.png".format(i))
        plt.close()

输出数字

enter image description here

1 个答案:

答案 0 :(得分:2)

如何创建列表列表并一一列出?以下解决方案也适用于多个文件。

import matplotlib.pyplot as plt
import glob


# Read any .txt output file
path = '/home/plots/*.txt' 
files = glob.glob(path)

######################################################
# Create a list of episodes and reward from all files
l_episodes = []
l_rewards = []
######################################################
for name in files:
    # Read lines from file
    with open(name) as f:
        lines = f.readlines()

    # Extract episode/reward data points
    episodes = []
    rewards = []
    for line in lines:
        columns = line.split()
        if not columns[0].startswith("episode"):
            # Not a line with episode/reward data
            continue
        try:
            episode = int(columns[0].split(":")[1])
            reward = float(columns[7].split(":")[1])
        except:
            # Not a number
            continue
        if episode in episodes:
            # We don't want repeated episodes
            continue
        episodes.append(episode)
        rewards.append(reward)

    print(episodes,rewards)
    #################################
    # Append to the lists
    l_episodes.append(episodes)
    l_rewards.append(rewards)
    #################################

###########################################    
#plot both in the same figure
for i in range(len(l_episodes)):
    plt.plot(l_episodes[i], l_rewards[i])
###########################################
plt.show()