【问题标题】:How to make subplots from multiple files? Python matplot lib如何从多个文件制作子图? Python matplotlib
【发布时间】:2021-02-06 03:13:12
【问题描述】:

我是一名学生研究员,正在对系外行星进行模拟,以确定它们是否适合生命存在。我正在使用的软件输出一个包含多列各种类型数据的文件。到目前为止,我已经编写了一个 python 脚本,它遍历一个文件并获取两列数据。在这种情况下,地球的时间和全球温度。

我想做的是:

  1. 编写一个遍历多个文件的 python 脚本,并抓取与我当前脚本相同的两列。
  2. 然后,我想为所有这些文件创建子图

在所有文件中保持一致的是,时间不会改变,x 轴始终是时间(从 0 到 100 万年)。不过,y 轴值会在模拟中发生变化。

这是我到目前为止的代码:

import math as m
import matplotlib.pylab as plt
import numpy as np



## Set datafile equal to the file I plan on using for data, and then open it
datafile = r"C:\Users\sasuk\OneDrive\Desktop\GJ 229 Planet Data\Gj 229 b - [SemiMajor 0.867][Ecc][Mass][Luminosity]\solarsys.Earth.forward"
file = open(datafile, "r")

# Create two empty arrays for my x and y axis of my graphs
years = [ ]
GlobalT = [ ]

# A for loop that looks in my file, and grabs only the 1st and 8th column adding them to the respective arrays
for line in file:
    data = line.split(' ')
    years.append(float(data[0]))
    GlobalT.append(float(data[7]))

# Close the file
file.close()


# Plot my graph
fig = plt.matplotlib.pyplot.gcf()

plt.plot(years, GlobalT)
plt.title('Global Temperature of GJ 229 b over time')
fig.set_size_inches(10, 6, forward=True)
plt.figtext(0.5, 0.0002, "This shows the global temperature of GJ 229 b when it's semi-major axis is 0.929 au, \n"
                         " and it's actual mass relative to the sun (~8 Earth Masses)", wrap=True, horizontalalignment='center', fontsize=12)
plt.xlabel(" Years ")
plt.ylabel("Global Temp")

plt.show()

【问题讨论】:

    标签: python file matplotlib graph


    【解决方案1】:

    我认为最简单的做法是将一个文件的代码转换为一个函数,然后在一个循环中调用它来遍历文件。

    from pathlib import Path
    
    
    def parse_datafile(pth):
        """Parses datafile"""
        results = []
        with pth.open('r') as f:
            for line in f:
                data = line.split(' ')
                results.append({'f': pth.stem,
                                'y': data[0],
                                't': data[7]}) 
        return results
    
    basedir = Path(r'C:\Users\sasuk\OneDrive\Desktop\GJ 229 Planet Data\Gj 229 b - [SemiMajor 0.867][Ecc][Mass][Luminosity]')
    
    # assuming you want to parse all files in directory
    # if not, can change glob string for files you want
    all_results = [parse_datafile(pth) for pth in basedir.glob('*')]
    
    df = pd.DataFrame(all_results)
    
    df['y'] = pd.to_numeric(df['y'], errors='coerce')
    df['t'] = pd.to_numeric(df['t'], errors='coerce')
    

    这将为您提供一个包含三列的数据框 - f(文件名)、y(年份)和 t(温度)。然后,您必须将 y 和 t 转换为数字 dtypes。这将比您的代码更快并更优雅地处理错误,这将引发任何格式错误的数据的错误。

    您可以根据需要进一步操作它来生成您的绘图。绝对检查是否有任何 NaN 值并相应地处理它们,方法是删除这些行或使用 fillna。

    【讨论】:

    • 好吧,有趣。那么我会把你的代码放在哪里呢?这会取代我的 for 循环以及我调用 plt.plot() 函数之前的所有内容吗?
    猜你喜欢
    • 1970-01-01
    • 2013-05-10
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 2018-11-13
    • 2016-11-15
    • 2022-12-17
    相关资源
    最近更新 更多