美文网首页
matplotlib

matplotlib

作者: caokai001 | 来源:发表于2019-07-20 19:52 被阅读0次

    matplotlib 入门

    1. plt.plot画线

    • plt.plot(x, y)可以根据x、y轴的坐标画出对应的连线。 plt.show()用来显示作出的图线。
    • plt.plot(y)则默认输入变量表示纵坐标,而横坐标为range(len(y))
    • 安装横坐标顺序画图, 用zip函数
    import matplotlib.pyplot as plt
    plt.plot([1, 2, 3, 4], [1, 2, 5, 4])
    plt.plot([0, 1, 2, 4, 8])
    
    x = [1, 5, 3, 2, 7, 4]
    y = [1, 2, 5, 0, 6, 2]
    plt.plot(x, y)
    
    xs, ys = zip(*sorted(zip(x, y)))
    plt.plot(xs, ys)
    
    

    2.图像大小范围设置

    • plt.figure(figsize=(a, b)),a表示宽度,b表示高度。
    • plt.axis([x_min, x_max, y_min, y_max])
    • plt.xlim(x_min, x_max), plt.ylim(y_min, y_max)
    plt.figure(figsize=(4, 3))
    plt.ylim(-0.5, 1.5)
    plt.plot(x1, y1)
    plt.plot(x2, y2)
    

    3. plot参数设置

    • plt.plot(x,y,lw,color,alpha,ls,marker)
    • w表示图线的粗细,数值越大表示图线越粗。
    • color表示颜色,- g: green - r: red - c: cyan - m: magenta - y: yellow - k: black - w: white
    • alpha表示透明度,取值0到1之间,1表示不透明。
    • ls,我们可以画出不同线性的折线。 - '-'表示实线 - '--'表示虚线 - '-.'表示点划线 - ':'表示虚点线 - ''表示不显示
    • marker,我们可以画出每个点,并设置点的外形。 - 'o'表示圆点 - 's'表示方点 - ','表示小像素点 - '^'表示上三角 - 'v'表示下三角
    plt.figure(figsize=(5, 3))
    plt.plot(x1, y1, lw=3, color='g', alpha=0.6, ls='', marker='o')
    plt.plot(x2, y2, lw=3, color='b', alpha=0.6, ls='-', marker='s')
    plt.plot(x2, x2, lw=3, color='r', alpha=0.6, ls='', marker='v')
    plt.show()
    
    
    image.png

    4.图像的标注

    • plt.title(my_string)将会把plot的标题改为my_string
    • plt.xlabel(x_axis_name)可将x-轴的名称改为x_axis_name。
    • plt.ylabel(y_axis_name)可将y-轴的名称改为y_axis_name。
    • plt.legend()中的参数loc来移动图例的位置
    my_title = 'I moved the legend.'
    plt.figure(figsize=(5, 3))
    plt.plot(x1, y1, lw=3, color='#32bab5', alpha=0.2, label='square')
    plt.plot(x2, y2, lw=6, color='#32bab5', alpha=0.6, label='root')
    plt.plot(x2, x2, lw=10, color='#32bab5', alpha=1.0, label='identity')
    plt.title(my_title)
    plt.xlabel('this is x-axis')
    plt.ylabel('this is y-axis')
    plt.legend(loc=[1.1, 0.5])
    plt.show()
    
    image.png

    5. plt.hist直方图

    • plt.hist(x, color='g', lw=0.2, alpha=0.5,bins=5)
    • bins=5 ,用来设定直方图中分组的数量
    • bins设定为一个list或者numpy.ndarray的形式,按照list中的元素,划定每个bin的上下界。
    plt.figure(figsize=(5, 3))
    plt.hist(x, bins=[-4, -2, -1, -0.5, 0, 0.5, 2, 5])
    plt.show()
    
    image.png

    6. plt.scatter散点图

    • plt.scatter(x, y, s=50) ,s用来表示每个散点的大小。
    plt.figure(figsize=(5, 3))
    plt.scatter(x, y, s=sizes, color='g', alpha=0.3, lw=0)
    plt.title('My green scatter plot.')
    plt.show()
    
    image.png

    7. 作图样式模板的设定

    plt支持各种类型的作图样式模板,常用的比如ggplot,能达到R中ggplot一样的效果

    plt.style.use('ggplot')
    x = np.random.normal(0, 1, 1000)
    plt.figure(figsize=(5, 3))
    plt.hist(x)
    plt.show()
    
    ggplot 模板

    相关文章

      网友评论

          本文标题:matplotlib

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