机械学习:Jupyter Notebook中Matplotlib的使用

一、matplotlib绘制折线图

  • matplotlib绘图的实质是折线图,将所有的点用直线连接起来,由于距离比较密,看起来像是个平滑的曲线;
  1. import matplotlib as mpl:加载matplotlib模块;
  2. from matplotlib import pyplot as plt:一般多用matplotlib的子模块pyplot,然后直接调用pyplot的相应函数即可;
  3. 最简单的绘图:
    from matplotlib import pyplot as plt
    import numpy as np
    
    # 从[0, 10]区间内,等分取出100个点(包含0和10);
    x = np.linspace(0, 10, 100)
    y = np.sin(x)
    
    # 绘制以x为横轴,y为纵轴,绘图,生成matplotlib.lines.Line2D对象
    plt.plot(x, y)
    
    # 使用plt的show函数显示图线对象
    plt.show()
  4. 一个图内绘制多条曲线:
    from matplotlib import pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 10, 100)
    siny = np.sin(x)
    cosy = np.cos(x)
    
    # 绘制多条曲线后再显示所有的线,才可以在同一个图内显示多条线
    plt.plot(x, siny)
    plt.plot(x, cosy)
    plt.show()
  5. 改变线条颜色、线型、坐标轴范围(x轴、y轴的范围):具体颜色种类和线型的种类可查matplotliib文档;“:”:表示"...."点虚线、“-.”:表示“-.-.-.-.-.”横杠 + 点、“--”:两个横杠表示“------”横杠虚线、“-”:一个横杠表示默认实线;
    plt.plot(x, siny)
    
    # 将cosy曲线的颜色调整为红色,线型为虚线
    plt.plot(x, cosy, color = 'red', linestyle = '--')
    
    # 分别限定横纵坐标范围:横轴在[5, 8],纵轴在[0, 1]
    plt.xlim(5, 8)
    plt.ylim(0, 1)
    
    # 也可以同时限定两个坐标轴的范围,默认两面两个参数为横坐标范围,后面两个参数为纵坐标范围
    plt.axis([5, 8, 0, 1])
    
    plt.show()
  6. 添加坐标轴的label、曲线的图式、图标的title:
    from matplotlib import pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 10, 100)
    siny = np.sin(x)
    cosy = np.cos(x)
    
    # 添加图式:label
    plt.plot(x, siny, label = 'sin(x)')
    plt.plot(x, cosy, color = 'red', linestyle = '--', label = 'cos(x)')
    
    # 添加横、纵左边的名称
    plt.xlabel("x axis")
    plt.ylabel("y value")
    
    # 添加图表标题:title
    plt.title('Welcome to the Machine-Learn World')
    
    # 显示图式label
    plt.legend()
    
    plt.show()

二、matplotlib绘制散点图:Scatter Plot

  • 直接调用plt.scatter()函数即可,和plt.plot()用法一样
  • 对于折现图,横轴表示特征,纵轴表示取值;
  • 对于散点图,通常横、纵两个轴均表示特征,对用于绘制二维特征:将特征点打在图像上,用不同的颜色代替label;
  1. 绘制简单散点图:
    from matplotlib import pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 10, 100)
    siny = np.sin(x)
    cosy = np.cos(x)
    
    # 添加图式:label
    plt.scatter(x, siny)
    plt.scatter(x, cosy, color = "red")
    plt.show()
  2. 设置散点的透明度:0~1,0表示全透明,1表示完全不透明;
    x = np.random.normal(0, 1, 10000)
    y = np.random.normal(0, 1, 10000)
    
    # 透明度设置为0.5
    plt.scatter(x, y, alpha = 0.5)
  3. 散点图有很多样式,可查看matplotlib文档了解;

猜你喜欢

转载自www.cnblogs.com/volcao/p/9071530.html