Matplotlib:Get_started

作者: ACphart | 来源:发表于2018-08-04 13:48 被阅读13次

    Loading data for plotting

    • There are several common data structures we will keep coming across.
    1. list eg: data = [1, 2, 3, 4, 5, 6]
    2. numpy array eg: array = np.array(data)
    3. pandas DataFrame eg: df = pd.DataFrame(data)
    • Loading data from files
    1. The basic Python way
    evens = []
    with open('file_path') as f:
        for line in f.readlines():
            evens.append(line.split()[1])
    
    2. The Numpy way
    import numpy as np
    np.loadtxt('file_path', delimiter='\t', usecols=1, dtype=np.int32)
    
    • The first parameter is the path of the data file. The delimiter parameter specifies the string used to separate values, which is a tab here. Because numpy.loadtxt() by default separate values separated by any whitespace into columns by default, this argument can be omitted here. We have set it for demonstration.
    • For usecols and dtype that specify which columns to read and what data type each column corresponds to, you may pass a single value to each, or a sequence (such as list) for reading multiple columns.
    3. The Pandas way(main way)
    import pandas as pd
    pd.read_csv('file_path', sep='\t', usecols=1)
    

    Plotting

    import matplotlib.pylot as plt
    plt.plot(data)
    plt.plot(data, data**2)
    plt.plot(data, data**2, label='x^2')
    plt.legend()       #To label the curve with a legend
    
    • To label the curve with a legend by plt.legend()

    Viewing and saving the figure

    plt.savefig('output.png')        #save before show
    plt.show()
    
    • If you want to both view the image on screen and save it in file, remember to call plt.savefig() before plt.show() to make sure you don't save a blank canvas.

    相关文章

      网友评论

        本文标题:Matplotlib:Get_started

        本文链接:https://www.haomeiwen.com/subject/kfqmvftx.html