美文网首页
matplotlib使用

matplotlib使用

作者: 萌木盖 | 来源:发表于2018-12-25 00:12 被阅读0次

    import matplotlib.pyplot as plt

    figure.savefig的选项

    • filename
      • 含有文件路径的字符串或Python的文件型对象。图像格式由文件扩展名推断得出,例如,.pdf推断出PDF,.png推断出PNG
        (“png”、“pdf”、“svg”、“ps”、“eps”……)
    • dpi
      • 图像分辨率(每英寸点数),默认为100
    • facecolor
      图像的背景色,默认为“w”(白色)
    !mkdir "./img"
    plt.plot(x,y)
    plt.savefig("./img/fig.jpg")
    
    • plt.imread("./source/girl.jpg")
      • 图片数组化
    • plt.imshow(girl)
      • 将数组对象放入
    • axes.set_xscale("log")
      • X轴按照log形式显示
    • plt.show()
      • 显示图片
    • figure = img.get_figure()
      • 获取图片的图层
    • figure.set_size_inches((20,16))
      • 设置图层的大小
    • plt.plot(x,y)
      • plot()创建一个2D线型图,并且返回该图的对象
    • lines[1].set_linewidth(5)
      • 设置线宽,图对象是一个数组,所以[1]
    • plt.grid(lw=1,color='red',alpha=0.1)
      • 设置网格线
      • lw代表linewidth,线的粗细
      • alpha表示线的明暗程度
      • color代表颜色
    • 轴面

    # 添加子轴面,
    #一个图层里面可以方多个图像,每一个图像都是该图层的一个子轴面
    # 1、取出plt的图层对象
    figure = plt.figure(figsize=(12,3))
    # 2、向图层中增加子轴面
    axes1 = figure.add_subplot(1,3,1) 
    # 获取到子轴面对象,可以把图像画在里面
    axes1.plot(x,y)
    # 三个参数分别多少行、多少列、第几个(从左到右,从上到下)
    # 3、在子轴面中绘制图像
    axes2 = figure.add_subplot(1,3,2)
    
    axes3 = figure.add_subplot(1,3,3)
    
    axes2.plot(x,np.cos(x),color="m",linestyle="-.")
    
    axes3.plot(x,np.tan(x),color='g',linestyle=":")
    
    #加网格
    axes1.grid(b=True,c="g",linestyle=":")
    axes2.grid(c='r',linestyle="--")
    
    
    • plt.axis([-15,8,-2,2])
      • 参数是一个列表,有四个元素分别代表x轴上下限和y轴上下限
      • 'tight'、'off'、'equal'……
    • plt.xlim(-4,6)
    • plt.ylim(-1,0.5)
      • 指定x轴和y轴的坐标的上下限
    • plt.xlabel("x_value",rotation=0,horizontalalignment="left")
    • plt.ylabel("sin(x)",rotation=0,horizontalalignment="center")
      • 设置坐标轴标签
    • plt.legend(["y=x^2","y=2x","y=cos(x)"])
      • 设置图例,分别对应三条线
    • loc参数
    字符串 数值 字符串 数值
    best 0 center left 6
    upper right 1 center right 7
    upper left 2 lower center 8
    lower left 3 upper center 9
    lower right 4 center 10
    right 5
    - plt.legend(["y=x^2","y=2x","y=cos(x)"],loc="best")
    
    • plt.legend(loc=(0,0.5),ncol=2)
      • 元组第一个元素代表x方向上图例方的位置,第二个元素y方向上图例的位置
      • ncol代表图例的列数

    设置plot的风格和样式

    • axes1.plot(x,y1,ls="--",color="r",marker="o")

    • plt.plot(x,y,color=(0.3,0.4,0.3,0.1))

      • rgb alpha

    颜色值的方式

    • 别名
      • color='r'
    • 合法的HTML颜色名
      • color = 'red'
    颜色 别名 HTML颜色名 颜色 别名 HTML颜色名
    蓝色 b blue 绿色 g green
    红色 r red 黄色 y yellow
    青色 c cyan 黑色 k black
    洋红色 m magenta 白色 w white
    • HTML十六进制字符串
      • color = '#eeefff'
    • 归一化到[0, 1]的RGB元组
      • color = (0.3, 0.3, 0.4)
    • plt.subplot(facecolor=(0.2,0.3,0.5))
      • 设置坐标轴面的背景颜色
    • plt.plot(x,y,facecolor="r")
      • plot函数是用于绘制线形图的,线形图没有背景颜色
    • plt.plot(x,x**3,c=(0.5,0.6,0.3),linestyle = "-.",lw=10)
    • plt.plot(x,x**2,dashes=[4,5,8,6])
      • dashes里面分别是 长度 宽度 第二个长度,第二个宽度

    线条风格设置

    线条风格 描述 线条风格 描述
    '-' 实线 ':' 虚线
    '--' 破折线 'steps' 阶梯线
    '-.' 点划线 'None' / ',' 什么都不画
    • marker参数
    • plt.plot([1,2,4,6,7,9],[1,1,4,9,10,20],marker="4")
    标记 描述 标记 描述
    '1' 一角朝下的三脚架 '3' 一角朝左的三脚架
    '2' 一角朝上的三脚架 '4' 一角朝右的三脚架
    • plt.plot(x,y,marker="o",markersize=10)
      • markersize代表点的大小
        | 标记 | 描述 | 标记 | 描述 |
        | :-------------: |:-----------:| :----:| :-----:|
        | 's' | 正方形 | 'p' | 五边形 |
        | 'h' | 六边形1 | 'H' | 六边形2 |
        | '8' | 八边形 |
    标记 描述 标记 描述
    '.' 'x' X
    '*' 星号 '+' 加号
    ',' 像素
    标记 描述 标记 描述
    'o' 圆圈 'D' 菱形
    'd' 小菱形 '','None',' ',None
    标记 描述 标记 描述
    '_' 水平线 '|' 水平线
    • 更多点线设置
    • plt.plot(x,y,"-.g",x,x2,"--or",x,x2,"--",x,x)
    • plt.plot(x,x**2,c='r',ls='-.',marker='o',markeredgecolor='g',
      markerfacecolor='m',markeredgewidth=3,markersize=10)
    • plt.plot(x,x*2,ls="-.",x,x4,marker="o")
      • 属性设置不能把属性夹杂在曲线之间,会报错
    • line, = plt.plot(x,y)
    • plt.setp(line,marker="*",ls="-.",c="g")
      • setp方法传参
    • setter方法
    lines = plt.plot(x,y,x,x**2)
    # 通过setter方法对属性进行设置
    lines[0].set_color("r")
    lines[0].set_marker(">")
    lines[1].set_ls("-.")
    lines[1].set_lw(10)
    
    参数 描述 参数 描述
    color或c 线的颜色 linestyle或ls 线型
    linewidth或lw 线宽 marker 点型
    markeredgecolor 点边缘的颜色 markeredgewidth 点边缘的宽度
    markerfacecolor 点内部的颜色 markersize 点的大小

    X、Y轴坐标刻度

    x = np.linspace(-5,5,50)
    y = np.sin(x)
    plt.plot(x,y,c='r')
    # 设置x轴坐标的标记
    plt.xticks(np.linspace(-np.pi,np.pi,5),
               ("-pi","-pi/2","0","pi/2","pi"),size=20,rotation=60)
    # y轴留三个
    plt.yticks([-1,0,1],["min",0,'max'])
    

    面向对象方法设置刻度

    # 坐标标签与刻度属于图层面板
    figure = plt.figure(figsize=(12,5))
    
    axes = figure.add_subplot(111)
    
    axes.plot(x,y,c="m")
    
    axes.set_xticks(np.linspace(-np.pi,np.pi,5)) # 这个方法设置下标的位置
    axes.set_xticklabels(["-pi","-pi/2",0,"pi/2","pi"],size=10)
    
    • LaTex语法,用 ππ 等表达式在图表上写上希腊字母
    plt.plot(x,y)
    plt.xticks(np.linspace(-np.pi,np.pi,5),
               ["-$\pi$","-$\pi$/2",0,"$\pi$/2","$\pi$"])
    

    其他2D图形

    直方图

    【直方图的参数只有一个x!!!不像条形图需要传入x,y】

    hist()的参数

    • bins
      可以是一个bin数量的整数值,也可以是表示bin的一个序列。默认值为10
    • normed
      如果值为True,直方图的值将进行归一化处理,形成概率密度,默认值为False
    • color
      指定直方图的颜色。可以是单一颜色值或颜色的序列。如果指定了多个数据集合,颜色序列将会设置为相同的顺序。如果未指定,将会使用一个默认的线条颜色
    • orientation
      通过设置orientation为horizontal创建水平直方图。默认值为vertical
    x = np.random.randint(0,10,size=100)
    print(x)
    plt.hist(x,bins=20,normed=True,color='r',orientation="vertical")
    # bins参数代表是划分多少个区间,normed参数代表是否归一化
    

    条形图

    【条形图有两个参数x,y!】

    bar()、barh()

    • plt.bar(x,x,width=0.1)
      • 条形图适合样本量比较小的统计量,如果比较大会自动选取某些代表点
      • barh()为水平的条形图

    饼图

    【饼图也只有一个参数x!】

    • pie()
      • 饼图适合展示各部分占总体的比例,条形图适合比较各部分的大小
      • 普通各部分占满饼图
      • 普通未占满饼图
    labels = ["China","USA","EU","Japan","UK","France","Others"]
    data = np.array([0.12,0.18,0.15,0.06,0.03,0.025,0.465])
    
    plt.pie(data,labels=labels,labeldistance=1,autopct="%0.2f%%",
            pctdistance=0.8,explode=[0.2,0.2,0,0,0.5,0.1,0.1],shadow=True,
           startangle=180
           )
    

    饼图阴影、分裂等属性设置

    • labels参数设置每一块的标签;labeldistance参数设置标签距离圆心的距离(比例值)
    • autopct参数设置比例值的显示格式(%1.1f%%);pctdistance参数设置比例值文字距离圆心的距离
    • explode参数设置每一块顶点距圆形的长度(比例值);colors参数设置每一块的颜色;
    • shadow参数为布尔值,设置是否绘制阴影
    • startangle设置旋转角度

    散点图

    【散点图需要两个参数x,y,但此时x不是表示x轴的刻度,而是每个点的横坐标!】

    • scatter()
    x = np.random.randn(1000)
    y = np.random.randn(1000)
    
    # 随机生成1000中颜色
    colors = np.random.rand(3000).reshape((1000,3))
    # 随机生成1000个大小
    size = np.random.randint(1,100,size=1000)
    
    plt.scatter(x,y,color=colors,s=size,marker="d")
    

    图形内的文字、注释、箭头

    控制文字属性的方法:

    Pyplot函数 API方法 描述
    text() mpl.axes.Axes.text() 在Axes对象的任意位置添加文字
    xlabel() mpl.axes.Axes.set_xlabel() 为X轴添加标签
    ylabel() mpl.axes.Axes.set_ylabel() 为Y轴添加标签
    title() mpl.axes.Axes.set_title() 为Axes对象添加标题
    legend() mpl.axes.Axes.legend() 为Axes对象添加图例
    figtext() mpl.figure.Figure.text() 在Figure对象的任意位置添加文字
    suptitle() mpl.figure.Figure.suptitle() 为Figure对象添加中心化的标题
    annnotate() mpl.axes.Axes.annotate() 为Axes对象添加注释(箭头可选)

    所有的方法会返回一个matplotlib.text.Text对象

    • plt.text(2,2,"xxx",size=20)
      plt.figtext(1,0.5,"sss")#相对位置
    • annotate(text,xy=(tx0,ty0),xytext=(tx1,ty1),arrowprops=dict(arrowstyle="->",connectionstyle="arc3"))

    注释

    annotate()
    xy参数设置箭头指示的位置,xytext参数设置注释文字的位置
    arrowprops参数以字典的形式设置箭头的样式
    width参数设置箭头长方形部分的宽度,headlength参数设置箭头尖端的长度,
    headwidth参数设置箭头尖端底部的宽度,
    facecolor设置箭头颜色
    shrink参数设置箭头顶点、尾部与指示点、注释文字的距离(比例值)

    3D图

    from mpl_toolkits.mplot3d import Axes3D
    ax = plt.subplot(projection="3d")
    ax.scatter3D(samples["2006世界杯"],samples["2010世界杯"],samples["2007亚洲杯"],c=y_)
    centers = km.cluster_centers_
    ax.scatter3D(centers[:,0],centers[:,1],centers[:,2],c='r')
    

    相关文章

      网友评论

          本文标题:matplotlib使用

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