(转)matplotlib实战 matplotlib常用操作2 matplotlib 常用操作

原文:https://www.cnblogs.com/ws0751/p/8361330.html

https://www.cnblogs.com/ws0751/p/8313017.html---matplotlib常用操作2

https://www.cnblogs.com/ws0751/p/8312980.html---matplotlib 常用操作

https://blog.csdn.net/u014453898/article/details/73395522----python3 的 matplotlib绘图库的使用

plt.imshow(face_image.mean(axis=2),cmap='gray') 

图片灰度处理

 

size = (m,n,3) 图片的一般形式就是这样的

rgb 0-255 jpg图片 166,255,89 0.0-1.0 png图片 0.1,0.2,0.6

灰度处理以后 rgb---->gray 166,255,89 ---> 190 0.1,0.2,0.6 -- > 0.4

size = (m,n)

import scipy.misc as misc

import numpy as np
import pandas as pd
from pandas import Series,DataFrame

import matplotlib.pyplot as plt
%matplotlib inline

扫描二维码关注公众号,回复: 6139816 查看本文章

face_image = misc.face()
plt.imshow(face_image)

face_gray = misc.face(gray=True)
plt.imshow(face_gray,cmap='gray')

三种方法

  • 最大值法
  • 平均值法
  • RGB权重法[0.299,0.587,0.114]

plt.imshow(face_image.max(axis=2),cmap='gray')

plt.imshow(face_image.mean(axis=2),cmap='gray')

n = np.array([0.299,0.587,0.114])
plt.imshow(np.dot(face_image,n),cmap='gray')

matplotlib

一、Matplotlib基础知识

 

Matplotlib中的基本图表包括的元素

  • x轴和y轴 axis 水平和垂直的轴线
  • x轴和y轴刻度 tick 刻度标示坐标轴的分隔,包括最小刻度和最大刻度
  • x轴和y轴刻度标签 tick label 表示特定坐标轴的值
  • 绘图区域 axes 实际绘图的区域

只含单一曲线的图

x = np.arange(-np.pi,np.pi,0.1)
y = np.sin(x)
plt.plot(x,y)

包含多个曲线的图

plt.plot(x,np.sin(x),x,np.cos(x))

设置子画布

axes = plt.subplot()

plt.figure(figsize=(8,8))
# 设置字画布,返回的值就是当前字画布的坐标系对象
axes1 = plt.subplot(2,2,1)
axes2 = plt.subplot(222)
axes3 = plt.subplot(223)
axes4 = plt.subplot(224)

网格线

绘制正弦余弦

 

设置grid参数(参数与plot函数相同),使用plt面向对象的方法,创建多个子图显示不同网格线

  • lw代表linewidth,线的粗细
  • alpha表示线的明暗程度
  • color代表颜色
  • axis显示轴向
  • # 对不同的坐标系分别设置网格线
    plt.figure(figsize=(16,4))
    axes1 = plt.subplot(141)
    axes2 = plt.subplot(142)
    axes3 = plt.subplot(143)
    axes4 = plt.subplot(144)

    axes1.grid(True)
    axes3.grid(True)

    # axis参数设置网格线显示横纵
    axes2.grid(axis='x')
    axes4.grid(axis='y')

    # 设置线宽、透明度、颜色
    # red green yellow blue black orange pink gray white purple cyan
    axes1.grid(color='red')
    axes2.grid(lw = 2)
    axes3.grid(alpha = 0.5)

  • 坐标轴界限

     

    plt.axis([xmin,xmax,ymin,ymax])

  • plt.figure(figsize=(4,4))


    x = np.linspace(-1,1,100)
    y = (1-x**2)**0.5
    plt.plot(x,y)
    plt.axis([-4,4,-3,3])

  • 坐标轴标签

    xlabel方法和ylabel方法
    plt.ylabel('y = x^2 + 5',rotation = 60)旋转

    • color 标签颜色
    • fontsize 字体大小
    • rotation 旋转角度
  • loc参数可以是2元素的元组,表示图例左下角的坐标

    • [0,0] 左下
    • [0,1] 左上
    • [1,0] 右下
    • [1,1] 右上
    In [122]:
     
     
     
     
     
    plt.plot(x,x,x,x*2,x,x*0.5)
    # 使用loc参数设置图例位置
    plt.legend(['nomral','fast','slow'],loc=[-0.3,0.3])
     
     
    Out[122]:
    <matplotlib.legend.Legend at 0x1bee4870>
     
     

    图例也可以超过图的界限loc = (-0.1,0.9)

     

    ncol参数

    ncol控制图例中有几列,在legend中设置ncol,需要设置loc

    In [124]:
     
     
     
     
     
    plt.plot(x,x,x,x*2,x,x*0.5)
    # 使用nloc参数设置图例的列数
    plt.legend(['nomral','fast','slow'],loc=9,ncol=3)
     
     
    Out[124]:
    <matplotlib.legend.Legend at 0x1bf93870>
     
     

    linestyle、color、marker

    修改线条样式

    In [139]:
     
     
     
     
     
    x = np.random.randint(-20,30,size=(100,3))
    df = DataFrame(x)
    df
     
    . . .
    In [142]:
     
     
     
     
     
    plt.plot(df.index,df[0].cumsum(),linestyle='--',color='red',marker='o')
    plt.plot(df.index,df[1].cumsum(),linestyle='-.',color='blue',marker='H')
    plt.plot(df.index,df[2].cumsum(),ls=':',color='green',marker='d')
    plt.legend(['one','two','three'])
     
     
    Out[142]:
    <matplotlib.legend.Legend at 0x1d43e550>
     
     

    保存图片

     

    使用figure对象的savefig的函数

    • filename
      含有文件路径的字符串或Python的文件型对象。图像格式由文件扩展名推断得出,例如,.pdf推断出PDF,.png推断出PNG (“png”、“pdf”、“svg”、“ps”、“eps”……)
    • dpi
      图像分辨率(每英寸点数),默认为100
    • facecolor
      图像的背景色,默认为“w”(白色)
    In [148]:
     
     
     
     
     
    # 获取fig对象
    fig = plt.figure()
    x = np.arange(-np.pi,np.pi,0.1)
    plt.plot(x,np.sin(x))
    fig.savefig('dancer.png',dpi=100,facecolor='blue')
    fig.savefig('dancer.jpg',dpi=100,facecolor='green')
     
     
     
    In [147]:
     
     
     
     
     
    png = plt.imread('dancer.png')
    jpg = plt.imread('dancer.jpg')
    display(png,jpg)
     
    . . .
     

    二、设置plot的风格和样式

    plot语句中支持除X,Y以外的参数,以字符串形式存在,来控制颜色、线型、点型等要素,语法形式为:
    plt.plot(X, Y, 'format', ...)

     

    点和线的样式

     

    颜色

    参数color或c

    In [153]:
     
     
     
     
     
    x = np.arange(0,100)
    plt.plot(x,x**2,c = 'm')
     
     
    Out[153]:
    [<matplotlib.lines.Line2D at 0x1d76b770>]
     
     
    颜色值的方式
    • 别名
      • 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)
    • jpg png 区别
    In [156]:
     
     
     
     
     
    plt.plot(x,x,color='#0000ff')
    plt.plot(x,2*x,color = '#00ff00')
    plt.plot(x,x/2,color = '#ff0000')
     
     
    Out[156]:
    [<matplotlib.lines.Line2D at 0x1a81b3f0>]
     
    In [157]:
     
     
     
     
     
    plt.plot(x,x,color=(0.3,0.3,0.4))
     
     
    Out[157]:
    [<matplotlib.lines.Line2D at 0x1a859830>]
     
     
    透明度

    alpha参数

    In [158]:
     
     
     
     
     
    plt.plot(x,x,color=(0.3,0.3,0.4),alpha=0.1)
     
     
    Out[158]:
    [<matplotlib.lines.Line2D at 0x1a88aa90>]
     
     
    背景色

    设置背景色,通过plt.subplot()方法传入facecolor参数,来设置坐标系的背景色

    In [163]:
     
     
     
     
     
    # 使用坐标系对象绘制图形
    # fig = plt.figure() # 通过此方法能得到画布对象
    axes = plt.subplot(facecolor='c')
    axes.plot(x,x,color = 'g')
     
     
    Out[163]:
    [<matplotlib.lines.Line2D at 0x1d8b3e90>]
     
    In [164]:
     
     
     
     
     
    plt.subplot(facecolor = 'yellow')
    plt.plot(x,np.sin(x),color='red')
     
     
    Out[164]:
    [<matplotlib.lines.Line2D at 0x1efd02b0>]
     
     

    线型

    参数linestyle或ls

     
    线条风格 描述 线条风格 描述
    '-' 实线 ':' 虚线
    '--' 破折线 'steps' 阶梯线
    '-.' 点划线 'None' / ',' 什么都不画
    In [169]:
     
     
     
     
     
    x = np.arange(0,100,5)
    plt.plot(x,x,linestyle = '-',linewidth=1)
    plt.plot(x,x*2,linestyle = '--',linewidth=2)
    plt.plot(x,x*3,ls = '-.',lw=3)
    plt.plot(x,x*4,ls = ':',lw=4)
    plt.plot(x,x*5,ls = 'steps',lw=5)
     
     
    Out[169]:
    [<matplotlib.lines.Line2D at 0x1d44e730>]
     
     
    线宽

    linewidth或lw参数

     
    不同宽度的破折线

    dashes参数 eg.dashes = [20,50,5,2,10,5]

    设置破折号序列各段的宽度

    In [174]:
     
     
     
     
     
    x = np.arange(-np.pi,np.pi,0.1)
    plt.plot(x,np.sin(x),dashes=[5,1,10,2,20,4])
     
    . . .
     

    点型

    • marker 设置点形
    • markersize 设置点形大小
     
    标记 描述 标记 描述
    '1' 一角朝下的三脚架 '3' 一角朝左的三脚架
    '2' 一角朝上的三脚架 '4' 一角朝右的三脚架
    In [182]:
     
     
     
     
     
    x = np.arange(0,10,1)
    plt.plot(x,x,marker = '3',markersize=15)
    plt.plot(x,2*x,marker = '4',markersize=15)
     
     
    Out[182]:
    [<matplotlib.lines.Line2D at 0x1f342c30>]
     
     
    标记 描述 标记 描述
    's' 正方形 'p' 五边形
    'h' 六边形1 'H' 六边形2
    '8' 八边形
    In [191]:
     
     
     
     
     
    plt.plot(x,x,marker = 's',markersize = 30)
    plt.plot(x,2*x,marker = 'p',markersize = 40)
    plt.plot(x,3*x,marker = 'h',markersize = 30)
    plt.plot(x,4*x,marker = '8',markersize = 30)
     
     
    Out[191]:
    [<matplotlib.lines.Line2D at 0x20555f70>]
     
     
    标记 描述 标记 描述
    '.' 'x' X
    '*' 星号 '+' 加号
    ',' 像素
    In [196]:
     
     
     
     
     
    plt.plot(x,x,marker = '.',markersize = 30)
    plt.plot(x,2*x,marker = 'x',markersize = 30)
    plt.plot(x,3*x,marker = '*',markersize = 30)
    plt.plot(x,4*x,marker = ',',markersize = 30)
     
     
    Out[196]:
    [<matplotlib.lines.Line2D at 0x2068d430>]
     
     
    标记 描述 标记 描述
    'o' 圆圈 'D' 菱形
    'd' 小菱形 '','None',' ',None
    In [199]:
     
     
     
     
     
    plt.plot(x,x,marker = 'o',markersize = 30)
    plt.plot(x,2*x,marker = 'D',markersize = 30)
    plt.plot(x,3*x,marker = 'd',markersize = 30)
     
     
    Out[199]:
    [<matplotlib.lines.Line2D at 0x20748290>]
     
     
    标记 描述 标记 描述
    '_' 水平线 '|' 竖线

    In [201]:
     
     
     
     
     
    plt.plot(x,x,marker = '|',markersize = 30)
    plt.plot(x,2*x,marker = '_',markersize = 30)
     
     
    Out[201]:
    [<matplotlib.lines.Line2D at 0x207affb0>]
     
     
    标记 描述 标记 描述
    'v' 一角朝下的三角形 '<' 一角朝左的三角形
    '^' 一角朝上的三角形 '>' 一角朝右的三角形
    In [203]:
     
     
     
     
     
    plt.plot(x,x,marker = 'v',markersize = 30)
    plt.plot(x,2*x,marker = '<',markersize = 30)
    plt.plot(x,3*x,marker = '>',markersize = 30)
    plt.plot(x,4*x,marker = '^',markersize = 30)
     
     
    Out[203]:
    [<matplotlib.lines.Line2D at 0x20830d10>]
     
     

    多参数连用

    颜色、点型、线型,可以把几种参数写在一个字符串内进行设置 'r-.o'

    In [204]:
     
     
     
     
     
    plt.plot(x,x,'r-.o')
     
     
    Out[204]:
    [<matplotlib.lines.Line2D at 0x20867e70>]
     
     

    更多点和线的设置

    • markeredgecolor = 'green',
    • markeredgewidth = 2,
    • markerfacecolor = 'purple'
     
    参数 描述 参数 描述
    color或c 线的颜色 linestyle或ls 线型
    linewidth或lw 线宽 marker 点型
    markeredgecolor 点边缘的颜色 markeredgewidth 点边缘的宽度
    markerfacecolor 点内部的颜色 markersize 点的大小

    In [216]:
     
     
     
     
     
    plt.plot(x,x,marker = 'H',markersize = 30,markeredgecolor = 'm',markeredgewidth=2,markerfacecolor='b',lw=10,c='blue')
     
     
    Out[216]:
    [<matplotlib.lines.Line2D at 0x21b05430>]
     
     

    在一条语句中为多个曲线进行设置

     
    多个曲线同一设置

    属性名声明,不可以多参数连用

    plt.plot(x1, y1, x2, y2, fmt, ...)

    In [217]:
     
     
     
     
     
    plt.plot(x,x,x,2*x,color = 'c',ls='--',marker='d')
     
     
    Out[217]:
    [<matplotlib.lines.Line2D at 0x21b40090>,
     <matplotlib.lines.Line2D at 0x21b40190>]
     
     
    多个曲线不同设置

    多个都进行设置时,多参数连用 plt.plot(x1, y1, fmt1, x2, y2, fmt2, ...)

    In [219]:
     
     
     
     
     
    plt.plot(x,x,'r-.h',x,2*x,'b-->')
     
     
    Out[219]:
    [<matplotlib.lines.Line2D at 0x209bd190>,
     <matplotlib.lines.Line2D at 0x209bdbd0>]
     
     

    三种设置方式

     
    向方法传入关键字参数
    • import matplotlib as mpl
     
    对实例使用一系列的setter方法
    • plt.plot()方法返回一个包含所有线的列表,设置每一个线需要获取该线对象
      • eg: lines = plt.plot(); line = lines[0]
      • line.set_linewith()
      • line.set_linestyle()
      • line.set_color()
    对坐标系使用一系列的setter方法
    • axes = plt.subplot()获取坐标系
      • set_title()
      • set_facecolor()
      • set_xticks、set_yticks 设置刻度值
      • set_xticklabels、set_yticklabels 设置刻度名称
    In [223]:
     
     
     
     
     
    # plt.plot函数,返回值的呗绘制的包含每一条线对象的列表
    lines = plt.plot(x,x,x,x*2,x,x*3)
    # 可以通过line对象进行设置外观
    lines[0].set_linewidth(10)
    lines[1].set_linestyle('--')
    lines[2].set_color('red')
     
     
     
    In [237]:
     
     
     
     
     
    axes = plt.subplot(111)
    axes.set_title('axes_title')
    axes.set_xlabel('X-Label')
    axes.set_ylabel('Y-Label')
    axes.set_facecolor('yellow')
    axes.set_xticklabels(['-pi',0,'pi'])
    axes.set_yticklabels(['min',0,'max'])
    axes.set_xticks([-np.pi,0,np.pi])
    axes.set_yticks([-1,0,1])
    x = np.arange(-np.pi,np.pi,0.1)
    axes.plot(x,np.sin(x))
     
     
    Out[237]:
    [<matplotlib.lines.Line2D at 0x220aa8b0>]
     
     
    使用plt.setp()方法
    • plt.setp(line2,linestyle='--',linewidth = 3,marker = 'o')
    • plt.setp(axes,title='title')
    In [241]:
     
     
     
     
     
    lines = plt.plot(x,x,x,x*2,x,np.sin(x))
    plt.setp(lines[0],color='red',ls='--',lw=4)
    axes = plt.subplot()
    # p->> property属性
    plt.setp(axes,title='title')
     
    . . .
     

    X、Y轴坐标刻度

    plt.xticks()和plt.yticks()方法

    • 需指定刻度值和刻度名称 plt.xticks([刻度列表],[名称列表])
    • 支持fontsize、rotation、color等参数设置
    In [245]:
     
     
     
     
     
    x = np.arange(0,10,1)
    plt.plot(x,x*2)
    # 使用plt来设置坐标轴刻度
    # 新的刻度标签最好与原始的刻度标签保持一致
    # eg1:使用原始刻度
    plt.xticks([0,2,4,6,8],list('abcde'))
    # 在matplotlib里显示汉字的方法
    # eg2:修改原始刻度
    plt.yticks([0,4,8,12,16],['ok','good','very good','good good','vv good'])
     
     
    Out[245]:
    ([<matplotlib.axis.YTick at 0x21c57090>,
      <matplotlib.axis.YTick at 0x221fb8d0>,
      <matplotlib.axis.YTick at 0x21c6c690>,
      <matplotlib.axis.YTick at 0x21c74390>,
      <matplotlib.axis.YTick at 0x21c74790>],
     <a list of 5 Text yticklabel objects>)
     
     

    正弦余弦

    LaTex语法,用ππ、σσ等表达式在图表上写上希腊字母

    In [250]:
     
     
     
     
     
    x = np.arange(-np.pi,np.pi,0.1)
    plt.plot(x,np.sin(x),x,np.cos(x))
    # 第一个列表写新的刻度值,注意不要越界(可能会显示不出来)
    plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],['-$\pi$','-$\pi$/2',0,'$\pi$/2','$\pi$'])
    plt.yticks([-1,0,1],['min',0,'max'])
     
     
    Out[250]:
    ([<matplotlib.axis.YTick at 0x21da52d0>,
      <matplotlib.axis.YTick at 0x231e75b0>,
      <matplotlib.axis.YTick at 0x21da5390>],
     <a list of 3 Text yticklabel objects>)
     
     

    三、2D图形

     

    直方图

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

    hist()的参数

    • bins
      可以是一个bin数量的整数值,也可以是表示bin的一个序列。默认值为10
    • normed
      如果值为True,直方图的值将进行归一化处理,形成概率密度,默认值为False
    • color
      指定直方图的颜色。可以是单一颜色值或颜色的序列。如果指定了多个数据集合,颜色序列将会设置为相同的顺序。如果未指定,将会使用一个默认的线条颜色
    • orientation
      通过设置orientation为horizontal创建水平直方图。默认值为vertical
    In [266]:
     
     
     
     
     
    x = np.random.randint(1,100,50)
    x
     
     
    Out[266]:
    array([71, 51, 44, 82, 16, 32, 94, 27, 39, 35, 23, 57, 35, 55, 17, 54, 19,
           25,  2, 38, 46, 26, 57, 46, 69, 14, 79, 27, 77, 83, 98, 67, 97, 90,
           21, 83, 22, 66, 10, 37, 94, 94, 17, 38,  7, 68, 72, 76, 54, 23])
    In [268]:
     
     
     
     
     
    plt.hist(x,bins=10,normed=True,color = 'r',orientation='horizontal')
     
     
    Out[268]:
    (array([ 0.00625   ,  0.0125    ,  0.01458333,  0.01458333,  0.00625   ,
             0.0125    ,  0.00833333,  0.00833333,  0.00833333,  0.0125    ]),
     array([  2. ,  11.6,  21.2,  30.8,  40.4,  50. ,  59.6,  69.2,  78.8,
             88.4,  98. ]),
     <a list of 10 Patch objects>)
     
     

    条形图

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

    • width 纵向设置条形宽度
    • height 横向设置条形高度

    bar()、barh()

    In [262]:
     
     
     
     
     
    x = Series(np.array([3,5,7,8,9,2,4]))
    plt.bar(x.index,height = x.values)
     
     
    Out[262]:
    <Container object of 7 artists>
     
    In [263]:
     
     
     
     
     
    plt.barh(x.index,width=x.values)
     
     
    Out[263]:
    <Container object of 7 artists>
     
     

    饼图

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

    pie()
    饼图适合展示各部分占总体的比例,条形图适合比较各部分的大小

     

    普通各部分占满饼图

    In [269]:
     
     
     
     
     
    x = [89,45,32,16]
    plt.pie(x)
     
    . . .
     

    普通未占满饼图

    In [270]:
     
     
     
     
     
    x = [0.1,0.3,0.5]
    plt.pie(x)
     
    . . .
     

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

    • labels参数设置每一块的标签;
    • labeldistance参数设置标签距离圆心的距离(比例值,只能设置一个浮点小数)
    • autopct参数设置比例值的显示格式(%1.1f%%);
    • pctdistance参数设置比例值文字距离圆心的距离
    • explode参数设置每一块顶点距圆形的长度(比例值,列表);
    • colors参数设置每一块的颜色(列表);
    • shadow参数为布尔值,设置是否绘制阴影
    • startangle参数设置饼图起始角度
    In [283]:
     
     
     
     
     
    x = [89,45,32,16]
    plt.pie(x,labels=['boy','girl','bgirl','gboy'],labeldistance=0.3,autopct='%1.1f%%',pctdistance=0.8,
           explode=[0,0,0,0.2],colors=['m','c','purple','yellow'],shadow=True,startangle=90)
     
     
    Out[283]:
    ([<matplotlib.patches.Wedge at 0x24aa4ab0>,
      <matplotlib.patches.Wedge at 0x24aad0d0>,
      <matplotlib.patches.Wedge at 0x24aad6d0>,
      <matplotlib.patches.Wedge at 0x24aadd10>],
     [Text(-0.299821,0.0103548,'boy'),
      Text(0.195031,-0.227954,'girl'),
      Text(0.268004,0.134811,'bgirl'),
      Text(0.136343,0.481052,'gboy')],
     [Text(-0.799523,0.0276129,'48.9%'),
      Text(0.520083,-0.607876,'24.7%'),
      Text(0.714676,0.359496,'17.6%'),
      Text(0.272686,0.962103,'8.8%')])
     
     

    散点图

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

    scatter()

    In [289]:
     
     
     
     
     
    x = np.random.normal(size = 1000)
    y = np.random.normal(size = 1000)
    # [0.3,0.6,0.8] 这样的一个数就可以表示一个颜色
    # 随机生成1000个颜色
    color = np.random.random(size = (1000,3))
    # s表示marker的大小
    plt.scatter(x,y,marker='d',color=color,s = 30)
     
     
    Out[289]:
    <matplotlib.collections.PathCollection at 0x21bbcc90>
     
     

    四、图形内的文字、注释、箭头(自学)

     

    控制文字属性的方法:

    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对象

    In [314]:
     
     
     
     
     
    x = np.arange(-np.pi,np.pi,0.1)
    plt.plot(x,np.sin(x))
    # 画布  fig = plt.figure()
    # 坐标系 axes = plt.subplot()
    axes = plt.subplot()
    axes.text(0.5,0.4,'test')
    axes.set_xlabel('X-Label')
    axes.set_ylabel('Ylabel')
    axes.set_title('title')
     
    . . .
    In [313]:
     
     
     
     
     
    fig = plt.figure(figsize=(8,4))
    axes1 = plt.subplot(1,2,1)
    axes2 = plt.subplot(1,2,2)
    axes1.plot(x,np.sin(x))
    axes2.plot(x,np.cos(x))
    fig.text(0.4,0.5,'test')
    fig.suptitle('suptitle')
    axes1.set_title('title1')
    axes2.set_title('title2')
     
     
    Out[313]:
    Text(0.5,1,'title2')
     
     

    图形内的文字

    text()

     

    注释

    annotate()

    • xy参数设置箭头指示的位置
    • xytext参数设置注释文字的位置
    • arrowprops参数以字典的形式设置箭头的样式
    • width参数设置箭头长方形部分的宽度
    • headlength参数设置箭头尖端的长度,
    • headwidth参数设置箭头尖端底部的宽度
    • shrink参数设置箭头顶点、尾部与指示点、注释文字的距离(比例值),可以理解为控制箭头的长度
     
    如下都是arrowstyle可以选择的风格样式
    
    ``'->'``       head_length=0.4,head_width=0.2 ``'-['`` widthB=1.0,lengthB=0.2,angleB=None ``'|-|'`` widthA=1.0,widthB=1.0 ``'-|>'`` head_length=0.4,head_width=0.2 ``'<-'`` head_length=0.4,head_width=0.2 ``'<->'`` head_length=0.4,head_width=0.2 ``'<|-'`` head_length=0.4,head_width=0.2 ``'<|-|>'`` head_length=0.4,head_width=0.2 ``'fancy'`` head_length=0.4,head_width=0.4,tail_width=0.4 ``'simple'`` head_length=0.5,head_width=0.5,tail_width=0.2 ``'wedge'`` tail_width=0.3,shrink_factor=0.5 
    In [337]:
     
     
     
     
     
    x = np.arange(-np.pi,np.pi,0.1)
    axes = plt.subplot()
    plt.plot(x,np.sin(x))
    # 模式1:使用arrowstyle键,可以选择如上几种预定义的箭头样式
    axes.annotate(s='annotation2',xy=[-1.7,-1],xytext=[0.5,-0.5],arrowprops = {'arrowstyle':'fancy'})
    # 模式2:不适用arrowstyle键,可以使用{'headlength':10,'headwidth':16,'shrink':0.1来自定义样式
    axes.annotate(s='annotation1',xy=[1.7,1],xytext=[-0.5,0.5],arrowprops = {'headlength':10,'headwidth':16,'shrink':0.1})
     
    . . .
     

    练习
    三个随机正太分布数据

    In [359]:
     
     
     
     
     
    index = np.arange(100)
    x = np.random.normal(loc=10,scale=3,size=100)
    y = np.random.normal(loc=20,scale=3,size=100)
    z = np.random.normal(loc=30,scale=3,size=100)
    axes = plt.subplot()
    axes.plot(index,x,index,y,index,z)
    axes.legend(['plot','2nd plot','last plot'],loc=[0,1.05],ncol=3)
    axes.annotate(s='Important value',xy=[50,20],xytext=[15,35],fontsize=15,arrowprops={'arrowstyle':'->'})
     
     
    Out[359]:
    Text(15,35,'Important value')
     
     

    五、3D图

     

    曲面图

     

    导包

    • from mpl_toolkits.mplot3d.axes3d import Axes3D

    使用mershgrid函数切割x,y轴

    • X,Y = np.meshgrid(x, y)

    创建3d坐标系

    • axes = plt.subplot(projection='3d')

    绘制3d图形

    • p = axes.plot_surface(X,Y,Z,color='red',cmap='summer',rstride=5,cstride=5)

    添加colorbar

    • plt.colorbar(p,shrink=0.5)
    In [361]:
     
     
     
     
     
    from mpl_toolkits.mplot3d.axes3d import Axes3D
     
     
    In [376]:
     
     
     
     
     
    x = np.arange(100)
    y = np.arange(100)
    xx,yy = np.meshgrid(x,y)
    def create_z(xx,yy):
        return np.cos(xx)+np.sin(yy)
    z = create_z(xx,yy)
    print(z.shape)
    axes = plt.subplot(projection = '3d')
    p = axes.plot_surface(xx,yy,z,cmap='summer')
    plt.colorbar(p,shrink=0.5)
     
     
     
    (100, 100)
    
    Out[376]:
    <matplotlib.colorbar.Colorbar at 0x27fcc930>
     
    In [360]:
     
     
     
     
     
    x = np.array([1,2,3])
    y = np.array([4,5,6])
    xx,yy = np.meshgrid(x,y)
    display(xx,yy)
     
    . . .
     

    玫瑰图/极坐标条形图

     

    创建极坐标,设置polar属性

    • plt.axes(polar = True)

    绘制极坐标条形图

    • index = np.arange(-np.pi,np.pi,2*np.pi/6)
    • plt.bar(x=index ,height = [1,2,3,4,5,6] ,width = 2*np.pi/6)
    In [379]:
     
     
     
     
     
    plt.axes(polar=True)
    index = np.arange(-np.pi,np.pi,2*np.pi/6)
    plt.bar(x=index,height=[2,3,4,5,6,7],width = 2*np.pi/6)
     
     
    Out[379]:
    <Container object of 6 artists>
     

猜你喜欢

转载自www.cnblogs.com/liujiacai/p/10820771.html