首页 > 解决方案 > 用python绘制多数据框图

问题描述

我是编码新手。我的任务是使用来自多个数据框的数据绘制图表。要使用的数据帧的数量是不确定的 (n)。将在整个数据框中绘制相同的 X 和 Y 轴。你能指导我完成这个吗?我的导师已经编写了第一部分的代码(从轨道文件中提取数据,然后将它们导入 Python)。我只需要绘制图表。

import subprocess
import pandas as pd
import os
import matplotlib.pyplot as plt
#folder where the .tracks files are
main_path = r"N:\Projects\Misc\Joint geometry analysis"
file_list = [each for each in os.listdir(main_path) if each.endswith('.tracks')]
print (file_list)
opera_app = r"readtrac.exe" #utility for converting track files to ascii fwf
os.chdir( main_path )
#put readtrac.exe and library files into the working directory

utility_path = r"C:\Program Files\Vector Fields\Opera 15R3 x64\bin"
utilities = [opera_app, "libifcoremd.dll", "libmmd.dll"]

for u in utilities:
    f = os.path.join(main_path,u)
    if not os.path.exists(f):
        s = os.path.join(utility_path,u)
        print ( "copy " + s + " " + f)
        status = subprocess.check_output(['copy', s, f], shell=True)
        print("status: ", status.decode('utf-8'))
header = 9 #line where the columns start
widths = [6,16,16,16,16,16,16] # format of the .fwf file - column widths

df = [] #list of data frames

for f in file_list:
    trac_name_ip = f
    trac_name_op = trac_name_ip[:-6] + "fwf"
    print ('converting a track file called '  + trac_name_ip + ' to an ascii fwf file called ' + trac_name_op)
    subprocess.run([opera_app, trac_name_ip, 'B', trac_name_op])  # NB this won't overwrite a .fwf file
    df.append(pd.read_fwf(trac_name_op, header = header, widths = widths)) #read the fwf file into a pandas dataframe
df[0].head()

我知道如何绘制基本图,但我不知道应该使用哪些命令来绘制具有无限数量数据框的图 - 假设我想将df[['XP', 'ZP']]每个数据框绘制到一个图上,我该怎么办?理想情况下,我想要一个 XY 散点图,每个单独数据框的名称作为图例中的系列名称。

谢谢

标签: pythondataframeplotchartsdata-visualization

解决方案


您可以多次使用 plt.scatter() 将许多 DataFrame 绘制到同一个图中。虽然您不调用 plt.show() 每个 DataFrame 都将使用相同的轴显示。

这是您可以执行的操作的示例:

import pandas as pd
import matplotlib.pyplot as plt
import random

n = 4

# Generating DataFrames
df_names = [f'df{i}' for i in range(n)]
data = []

for i in range(n):
    data.append(pd.DataFrame(
        [[random.randint(1, 10), random.randint(1, 10)] for j in
         range(random.randint(1, 10))], columns=["A", "B"]))

# Plot DFDataFrames
for i, df in enumerate(data): # i is DataFrame number and df the DataFrame itself
    plt.scatter(df["A"], df["B"], label=df_names[i])

plt.title("Title")
plt.xlabel("X stuff")
plt.ylabel("Y stuff")
plt.legend()
plt.show()

它将创建一个如下图,我希望这就是你想要做的。

在此处输入图像描述

如果您有大量数据要显示,您可能需要使用子图以便在同一图像上显示多个图。您可以在此处找到有关子图的文档(和一些示例):https ://matplotlib.org/stable/gallery/subplots_axes_and_figures/subplots_demo.html


推荐阅读