python基础知识——matplotlib

来自:http://cs231n.github.io/python-numpy-tutorial/#scipy
更多:https://matplotlib.org/api/index.html

plot:
    matplotlib中最重要的函数是plot,它可以使你绘制二维数据。例子:

    import numpy as np
    import matplotlib.pyplot as plt

    # Compute the x and y coordinates for points on a sine curve
    x = np.arange(0, 3 * np.pi, 0.1)
    y = np.sin(x)

    # Plot the points using matplotlib
    plt.plot(x, y)
    plt.show()  # You must call plt.show() to make graphics appear.

    只需一点点额外工作,我们就可以轻松地一次绘制多行,并添加标题,图例和轴标签:

    import numpy as np
    import matplotlib.pyplot as plt

    # Compute the x and y coordinates for points on sine and cosine curves
    x = np.arange(0, 3 * np.pi, 0.1)
    y_sin = np.sin(x)
    y_cos = np.cos(x)

    # Plot the points using matplotlib
    plt.plot(x, y_sin)
    plt.plot(x, y_cos)
    plt.xlabel('x axis label')
    plt.ylabel('y axis label')
    plt.title('Sine and Cosine')
    plt.legend(['Sine', 'Cosine'])
    plt.show()

subplot:
    可以通过subplot函数在同一个图中绘制不同的图:
    import numpy as np
    import matplotlib.pyplot as plt

    # Compute the x and y coordinates for points on sine and cosine curves
    x = np.arange(0, 3 * np.pi, 0.1)
    y_sin = np.sin(x)
    y_cos = np.cos(x)

    # Set up a subplot grid that has height 2 and width 1,
    # and set the first such subplot as active.
    plt.subplot(2, 1, 1)

    # Make the first plot
    plt.plot(x, y_sin)
    plt.title('Sine')

    # Set the second subplot as active, and make the second plot.
    plt.subplot(2, 1, 2)
    plt.plot(x, y_cos)
    plt.title('Cosine')

    # Show the figure.
    plt.show()

图片:
    可以通过imshow函数来显示图片:

    import numpy as np
    from scipy.misc import imread, imresize
    import matplotlib.pyplot as plt

    img = imread('assets/cat.jpg')
    img_tinted = img * [1, 0.95, 0.9]

    # Show the original image
    plt.subplot(1, 2, 1)
    plt.imshow(img)

    # Show the tinted image
    plt.subplot(1, 2, 2)

    # A slight gotcha with imshow is that it might give strange results
    # if presented with data that is not uint8. To work around this, we
    # explicitly cast the image to uint8 before displaying it.
    plt.imshow(np.uint8(img_tinted))
    plt.show()

猜你喜欢

转载自blog.csdn.net/qq_32652679/article/details/80977397