How to plot data from multiple two column text files with legends in Matplotlib?

前端 未结 3 1603
眼角桃花
眼角桃花 2020-11-28 08:52

How do I open multiple text files from different directories and plot them on a single graph with legends?

3条回答
  •  佛祖请我去吃肉
    2020-11-28 09:35

    This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following:

    import pylab
    
    datalist = [ ( pylab.loadtxt(filename), label ) for filename, label in list_of_files ]
    
    for data, label in datalist:
        pylab.plot( data[:,0], data[:,1], label=label )
    
    pylab.legend()
    pylab.title("Title of Plot")
    pylab.xlabel("X Axis Label")
    pylab.ylabel("Y Axis Label")
    

    You also might want to add something like fmt='o' to the plot command, in order to change from a line to points. By default, matplotlib with pylab plots onto the same figure without clearing it, so you can just run the plot command multiple times.

提交回复
热议问题