【问题标题】:Is there a way to read files with different filenames and plot them on the same graph?有没有办法读取具有不同文件名的文件并将它们绘制在同一个图表上?
【发布时间】:2019-12-16 03:55:35
【问题描述】:

我想绘制由点云(格式化的点数据)组成的多个几何图形。我设法只在图形上绘制几何图形,但无法为我拥有的所有 4 个几何图形绘制。

我尝试过使用 glob 函数,但我不知道如何让它解决我的问题。

import matplotlib.pyplot as plt
import os
os.chdir(os.getcwd())
plt.close()
f = open('Geom_0_geo.fpd','r')
lines = f.readlines()
x,y=[],[]
x_int,y_int=[],[]
for line in lines:
    line = line.split()
    if len(line) == 3:
        x_int.append(line[0])
        y_int.append(line[1])
    else:
        x.append(x_int)
        y.append(y_int)
        x_int,y_int=[],[]
    if line == lines[-1].split():
        x.append(x_int)
        y.append(y_int)


f.close()

for i in range(len(x)):
    plt.plot(x[i],y[i],'k',lw=1.5)
    axes = plt.gca()
    axes.set_xlim([-2,3.5])
    axes.set_ylim([0,3])

几何文件名类似于 Geom_0.geo.fpd、Geom_1.geo.fpd、Geom_2.geo.fpd 等。我想将它们全部绘制在同一张图上,但使用不同的线条颜色和分配给每个的标签。最好的方法是什么?我展示的代码仅适用于一种有效的几何图形。

【问题讨论】:

    标签: python plot


    【解决方案1】:

    下面试试,

    import matplotlib.pyplot as plt
    #import glob
    #file = glob.glob("/path/*.fpd")
    file = ['Geom_0.geo.fpd','Geom_1.geo.fpd', 'Geom_2.geo.fpd',... ]
    # set up the line style, make sure len(mark)= len(file)
    ls = ['-', '--', ':' , ...]
    # set up color make sure len(color)= len(file)
    color = ['r','g','b',...]
    # set up labels
    tag = ['tag1',...]
    for i in range(0, len(file)):
        f = open(file[i],'r')
        lines = f.readlines()
        x,y=[],[]
        x_int,y_int=[],[]
        for line in lines:
            line = line.split()
            if len(line) == 3:
                x_int.append(line[0])
                y_int.append(line[1])
            else:
                x.append(x_int)
                y.append(y_int)
                x_int,y_int=[],[]
            if line == lines[-1].split():
                x.append(x_int)
                y.append(y_int)
    
    
        f.close()
    
        for i in range(len(x)):
            plt.plot(x[i],y[i],lw=1.5, linestyle=ls[i], color[i], label = tag[i])
            axes = plt.gca()
            axes.set_xlim([-2,3.5])
            axes.set_ylim([0,3])
    plt.show()
    

    【讨论】:

    • 这完全符合我的要求。如果我想用不同的线型和线条颜色绘制每个几何图形,我应该怎么做?最后,分配标签的最佳方式是什么?
    • 再次感谢您的回复。但是,运行 yoru 代码时出现以下错误: plt.plot(x[i],y[i],'k',lw=1.5, mark[i], color[i], label = tag[i] ) SyntaxError: 关键字 arg 后的非关键字 arg
    • @Mason 等一下。
    • @Mason plt.plot(x[i],y[i],'k',lw=1.5, mark[i], label = tag[i]) 是否有错误
    猜你喜欢
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 2017-08-31
    相关资源
    最近更新 更多