Artificial Intelligence Getting --Matplotlib

@ (Matplotlib of data visualization)

Matplotlib a library (math graphics library)

mat mathematical plot plotting lib library

.matplotlib.pyplot (abbreviated mp)

.mp.plot (horizontal coordinate, vertical coordinate array)

X : [ 1 2 3 4 ]

Y: [5 6 7 8]

. mp.plot (X, Y)

Customized Drawing:

.mp.plot (xxx, linestyle = line, linewidth = line width, color = color)

Look at the manual functions:

Setting Icon range:

.mp. xlim (left boundary, right boundary)

.mp. ylim (bottom boundary of the top boundary)

If you set the maximum and minimum values ​​are all filled with

Show radians:

.mp.xticks (scale position in the array, the array scale text)

.mp.yticks (scale position in the array, the array scale text)

Scale text array escaped string writing:

[R '$ - \ pi $', r '$ - \ frac {molecule} {denominator} $', r '$ 0 $']

Cross cited coordinates

Action: get the border of the shaft

ax = mp.gca () # Get the current axis

ax.spines [ 'left'] .set_position (( 'data', 0)) # installation position

ax.spines [ 'left'] .set_color (color) border color setting position #

Show legend and location

mp.plot ( '' ', laber = r' $ y = sin (x) $ ') # Display Legend

mp.legend(loc='upper left') #左上

Some special point mark

Scatter (no connection)

mp.scatter (horizontal coordinate array, vertical coordinate array, marker =-point, s = size, edgecolor = Crochet color, facecolor = fill color, zorder = Z order)

Z order is the order of drawing, the greater the number zerder, the later the pressure points on the line

Matplotlib drawing order is to draw a line and then drawing points

Make notes on the map

mp.annotate (note text, xy = target position, xycoords = object coordinate system, xytext = text position, Textcoords = text coordinates, fontsize = font size, arrowprops = attribute arrow)

import numpy as np
import matplotlib.pyplot as mp

x=np.linspace(-np.pi,np.pi,1000)  # 线性空间的划分

cos_y = np.cos(x)/2
sin_y = np.sin(x)
xo = np.pi*3/4
yo_cos = np.cos(xo)/2
yo_sin = np.sin(xo)

mp.xlim(x.min(),x.max())  # 最小值做左边界  最大值做右边界
mp.ylim(sin_y.min(),sin_y.max())

mp.xticks([-np.pi,-np.pi / 2,0,np.pi/2,np.pi*3/4,np.pi],[r'$-\pi$',r'$-\frac{\pi}{2}$',
                                                         r'$0$',r'$\frac{\pi}{2}$',r'$\frac{3\pi}{4}$',r'$\pi$'])
mp.yticks([-1,-0.5,0,0.5,1])

ax=mp.gca()  #得到边框 ↓对边框的设置
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
ax.spines['right'].set_color(('none'))
ax.spines['top'].set_color(('none'))

#    linestyle='-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
mp.scatter([xo,xo],[yo_cos,yo_sin],s=60,edgecolors='limegreen',facecolor='white',zorder=3)

mp.annotate(r'$\frac{1}{2}cos(\frac{3\pi}{4})= -\frac{\sqrt{2}}{4}$',xy=(xo,yo_cos),xycoords='data',
            xytext=(-90,-40),textcoords='offset points',fontsize=14,arrowprops=dict(arrowstyle='->',
            connectionstyle='arc3,rad=.2'))  #rad 控制备注线条的弯度

mp.annotate(r'$sin(\frac{3\pi}{4})=-\frac{\sqrt{2}}{2}$',xy=(xo,yo_sin),xycoords='data',
            xytext=(20,20),textcoords='offset points',fontsize=14,arrowprops=dict(arrowstyle='->',
            connectionstyle='arc3,rad=.2'))

mp.plot([xo,xo],[yo_cos,yo_sin],linestyle='-',linewidth=1,color='dodgerblue')


mp.plot(x,cos_y,linestyle='-.',linewidth=2,color='dodgerblue',label=r'$y=cos(x)$')
mp.plot(x,sin_y,linestyle='--',linewidth=2,color='green',label=r'$y=sin(x)$')

mp.legend(loc='upper left')
mp.show()

Two graphic objects

  1. Specific wording:

mp.figure (image object name, figsize = window size, dpi = resolution, facecolor = fill color)

mp.figure () method: The first call is to create, to create a home for the second time again for the current window

mp.title ( 'Title name', fontsize = 20) to write the title

mp.xlaber axis tag ( 'x', fontsize = 12) for the first half of the tag name, the latter half of the font size

​ mp.ylabel('y',fontsize=12)

mp.tick_params (labelsize = 10) Sets the scale parameter value scale 10 two intervals

mp.grid (linestyle = ':') disposed gridlines

​ linestyle= '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'

例:
import numpy as np
import matplotlib.pyplot as mp

x=np.linspace(-np.pi,np.pi,1000)
cos_y = np.cos(x)/2
sin_y = np.sin(x)

mp.figure('Figure Object1',figsize=(6,4),dpi=120,facecolor='lightgray') #宽 8 高 6
mp.title('Figure Object1',fontsize='16')

mp.xlabel('x',fontsize=18)
mp.ylabel('y',fontsize=18)

mp.tick_params(labelsize=10)  #设置刻度参数  刻度值两个间隔为10
mp.grid(linestyle=':')

mp.figure('Figure Object1')
mp.plot(x,cos_y,label=r'$y=\frac{1}{2}cos(x)$')
mp.legend()

mp.figure('Figure Object2',figsize=(6,4),dpi=120,facecolor='lightgray') #宽 8 高 6
mp.title('Figure Object2',fontsize='16')

mp.xlabel('x',fontsize=18)
mp.ylabel('y',fontsize=18)

mp.tick_params(labelsize=10)  #设置刻度参数  刻度值两个间隔为10
mp.grid(linestyle=':')

mp.figure('Figure Object2')
mp.plot(x,sin_y,label=r'$y=sin(x)$')
mp.legend()

mp.show()
  1. Pattern

    1. Subgraph

      Create a child diagram, created in sub-graph to enlarge

      1. Default (default) layout

      mp.subplot (the number of rows, columns, FIG number)

      Column: mp.subplot (2, 3, 1) or mp.subplot (231)

      FIG display text 1.1 Sub

      mp.text (ratio corresponding to the center position, center position corresponding to the ratio of the value, ha = horizontal alignment centered, va = the middle horizontal alignment, size = size, alpha = transparency)

      mp.tight_layout () # make compact scale, not many empty cells, margins narrowed

      1. Grid layout

      ​ import matplotlib.gridspec as mg

      gs = mg.GridSpec (rows, columns) grid layout is #

      mp.subplot (gs [row, column])

      1. Free layout

      mp.axes ([bottom left horizontal coordinate, vertical coordinate of the lower left corner, width, height])

      Advantages: it is relative proportions size parameter

      Cons: several simultaneous input, a picture can at last another inside

      import matplotlib.pyplot as mp
      
      # ====方式一=========
      mp.figure(facecolor='lightgray')
      for i in range(2):  #2代表2行
          for j in range(3):  # 3 代表3 列
              k =i*3+j+1
              # mp.subplot(2, 3, 1)  2行3列 1张
              mp.subplot(2,3,k)
              mp.xticks(()) #不带刻度线值
              mp.yticks(())
              mp.text(0.5,0.5,str(k),ha='center',va='center',  #ha水平  居中  ,va 垂直  居中
                      size=36,alpha=0.5)
      
      mp.tight_layout()  #让刻度紧凑,不空很多格,边距变窄
      mp.show()
      
      # =====方式二====== 栅格布局
      import matplotlib.gridspec as  mg
      
      mp.figure(facecolor='blue')
      gs = mg.GridSpec(3,3)   #栅格布局器  3行3列
      mp.subplot(gs[0,:2])  # 0 代表第0行 :2 代表前2列
      mp.xticks(())
      mp.yticks(())
      mp.text(0.5,0.5,'1',ha='center',va='center',size=36,alpha=0.5)  #ha水平  居中  ,va 垂直  居中
      
      mp.subplot(gs[1:,0])
      mp.xticks(())
      mp.yticks(())
      mp.text(0.5,0.5,'2',ha='center',va='center', size=36,alpha=0.5)  #ha水平  居中  ,va 垂直  居中
      
      mp.subplot(gs[:2,2])
      mp.xticks(())
      mp.yticks(())
      mp.text(0.5,0.5,'3',ha='center',va='center',size=36,alpha=0.5)  #ha水平  居中  ,va 垂直  居中
      
      mp.subplot(gs[2,1:])
      mp.xticks(())
      mp.yticks(())
      mp.text(0.5,0.5,'4',ha='center',va='center', size=36,alpha=0.5) #ha水平  居中  ,va 垂直  居中
      
      mp.subplot(gs[1,1])
      mp.xticks(())
      mp.yticks(())
      mp.text(0.5,0.5,'s',ha='center',va='center', size=36,alpha=0.5)  #ha水平  居中  ,va 垂直  居中
      
      mp.tight_layout()
      mp.show()
      
      # ======方式三=======自由布局
      mp.figure(facecolor='blue')
      mp.axes([0.3,0.3,0.8,0.9])
      mp.xticks(())
      mp.yticks(())
      mp.text(0.5,0.5,'1',ha='center',va='center', size=36,alpha=0.5)
      
      mp.axes([0.001,0.001,0.7,0.7])
      mp.xticks(())
      mp.yticks(())
      mp.text(0.5,0.5,'2',ha='center',va='center', size=36,alpha=0.5)
      
      mp.show()
    2. Coordinate of the scale locator

      Positioning objects = mp.xxxLocator ( '' ')

      mp.gca ax = ()

      Main scale: ax.xaxis.set_major_locator (Locator Object) # x-axis, so that the object locator to help us define the scale

      Minor Ticks: ax.xaxis.set_minor_locator (Locator Object) # x-axis, so that the object locator to help us define the scale

      import numpy as np
      import matplotlib.pyplot as mp
      
      mp.figure()
      locators=['mp.NullLocator()',  #空定位器. 不需要参数
                'mp.MaxNLocator(nbins=3,steps=[1,3,5,7,9])',#最多分三段,从后续列表中选一个等分的点
                'mp.FixedLocator(locs=[0,2,5,5,7.6,10])',  #固定定位器  等价于直接调用xticks
                'mp.AutoLocator()',  #自动定位器, 特点:间隔不太密  也不太稀疏,自动匹配
                'mp.IndexLocator(offset=0.5,base=1.5)', #索引定位器.offset起始点,base是间隔
                'mp.MultipleLocator()', #次刻度定位器
                'mp.LinearLocator(numticks=21)', #线性均分定位器, 等分21-1份
                'mp.LogLocator(base=2,subs=[1.0])'  #指数定位器, base倍数 是2 间隔是 1
                ]
      
      n_locators=len(locators)  #查看有多少个刻度定位器
      # 循环放在不同的图里
      for i,locator in enumerate(locators):
          mp.subplot(n_locators,1,i+1)
          mp.xlim(0,10)
          mp.ylim(-1,1)
          mp.xticks(())
          mp.yticks(())
          ax = mp.gca()
          ax.spines['left'].set_color('red')
          ax.spines['top'].set_color('red')
          ax.spines['right'].set_color('red')
          ax.spines['bottom'].set_position(('data',0))# 底轴放中间因为 从 1 到-1 0 在中间
          ax.xaxis.set_major_locator(eval(locator)) #eval函数解释执行 产生类的对象,主刻度执行器
          ax.xaxis.set_minor_locator(mp.MultipleLocator(0.1))  #次刻度定位 0.1为间隔
      
          mp.plot(np.arange(11),np.zeros(11),c='none')  #zeros是全零 ,y坐标
          mp.text(5,0.3,locator[3:],ha='center',size=16)
      
      mp.tight_layout()
      mp.show()
    3. Scatter

      Scatter meaning:

      You can make a point that came with more information

      Always two coordinates x, y to represent

      x = np.random.normal (0,1, n) # This is a normal distribution of random numbers

      Average μ 0

      1 standard deviation σ σ concentration if larger, the smaller the value of [sigma] thin and flat

      The number n

      import numpy as np
      import matplotlib.pyplot as mp
      
      n=1000
      x=np.random.normal(0,1,n)
      y=np.random.normal(0,1,n)
      d=np.sqrt(x **2 +y**2)  #距离正下方的点
      mp.figure('Scatter',facecolor='lightgray')
      mp.title('Scatter',fontsize=20)
      mp.xlabel('x',fontsize=14)
      mp.ylabel('y',fontsize=14)
      mp.tick_params(labelsize=10)  #标签文本字体大小
      mp.grid(linestyle='-.')  #设置网格线
      mp.scatter(x,y,s=60,c=d,cmap='jet_r',alpha=0.5) #c=d,cmap='jctr'是用距离来做颜色,cmap是颜色映射,颜色和距离对应 s是尺寸60
      mp.show()

      Area filling

      mp.fill_between (horizontal coordinate array, an array of vertical coordinate, vertical coordinate of the end point array, condition, color = color, alpha = transparency)

      import numpy as np
      import matplotlib.pyplot as mp
      
      n=1000
      x=np.linspace(0,8*np.pi,n)
      sin_y=np.sin(x)
      cos_y=np.cos(x/2)/2
      mp.figure('Fill',facecolor='lightgray')
      mp.title('Fill',fontsize=20)
      mp.xlabel('x',fontsize=14)
      mp.ylabel('y',fontsize=14)
      mp.tick_params(labelsize=10)  #标签文本字体大小
      mp.grid(linestyle='-.')  #设置网格线
      mp.plot(x,sin_y,c='dodgerblue',label=r'$y=sin(x)$')
      mp.plot(x,cos_y,c='orangered',label=r'$y=\frac{1}{2}cos(\frac{x}{2})$')
      mp.fill_between(x,cos_y,sin_y,cos_y<sin_y,color='dodgerblue',alpha=0.5)
      mp.fill_between(x,cos_y,sin_y,cos_y>sin_y,color='orangered',alpha=0.5)
      mp.legend()
      mp.show()
    4. Histogram (bar chart)

      mp.bar (horizontal coordinate array, the height of the array, ec = edge color, fc = fill color, label = label text, alpha = transparency)

      # N generated random numbers between 0.5 and 1.0 y1 = np.random.uniform (0.5,1.0, n)

      import numpy as np
      import matplotlib.pyplot as mp
      
      n = 12
      x = np.arange(n)
      y1 = (1 - x / n) * np.random.uniform(0.5, 1.0, n)
      y2 = (1 - x / n) * np.random.uniform(0.5, 1.0, n)
      mp.figure('Bar', facecolor='lightgray')
      mp.title('Bar', fontsize=20)
      mp.ylim(-1.25, 1.25)
      mp.xlabel('x', fontsize=14)
      mp.ylabel('y', fontsize=14)
      mp.xticks(x, x + 1)
      mp.tick_params(labelsize=10)  # 标签文本字体大小
      mp.grid(axis='y', linestyle='-.')  # 设置网格线 只有水平方向的
      
      for _x, _y in zip(x, y1):  # 取矩形条的位置和宽度,显示文字,两位小数精度的浮点数来表示格式化占位符
          mp.text(_x, _y, '%.2f' % _y, ha='center', va='bottom')
      for _x, _y in zip(x, y2):
          mp.text(_x, -_y - 0.015, '%.2f' % _y, ha='center', va='bottom')
      mp.bar(x,y1,ec='white',fc='dodgerblue',label='Sample 1')
      mp.bar(x,-y2,ec='white',fc='yellow',alpha=0.5,label='Sample 2')
      
      mp.legend()
      mp.show()

      Second way: mp.bar (horizontal coordinate, height, width, color = color, alpha = transparency, label = label text)

    5. Pie

      mp.pie (, gap, labels, color, format, shadow = whether shaded, startangle = starting angle)

    6. Contour FIG.

      Purpose: to display a two-dimensional three-dimensional graphics data is used in geography
      mp.contour (x, y, z, the number of lines, colors = color, linewidths = width): a wire
      mp.contourf (x, y, z, the number of lines, cmap = color mapping): a root ribbon
      Note: the more the number of lines of n, n intervals, the interval, the more dense ribbon
      Import numpy AS NP
      Import matplotlib.pyplot AS MP

      n=1000

      x, y = np.meshgrid (np.linspace ( -3,3, n), np.linspace (-3,3, n)) #meshgrid into 999 parts of the grid lines, each row of -3 to 3 between
      Z = (. 1-X / X + 2 . 5 + Y . 3) * np.exp (the -X- 2 Y- 2) is a curved surface results #

      mp.figure('Contour',facecolor='lightgray')
      mp.title('Contour',fontsize=20)
      mp.xlabel('x',fontsize=14)
      mp.ylabel('y',fontsize=14)
      mp.tick_params(labelsize=10)
      mp.grid(linestyle=':')

      Color Fill Contour

      mp.contourf (X, Y, Z,. 8, CMap = 'Jet')
      CNTR = mp.contour (X, Y, Z,. 8, = Colors 'Black', LineWidths = 0.5)
      mp.clabel (CNTR, inline_spacing = 1, fmt = '.% 1f ', fontsize = 10) # fill digital
      mp.show () meshgrid function: for mesh type data, it is acceptable to generate two-dimensional array, a two-dimensional matrix, corresponding to two All the array (x, y) of
      meshgrid effect is to generate a list of two array elements in accordance with a two-dimensional array of incoming parameters

      In the two-dimensional coordinates, x-axis takes three values ​​1,2,3, y-axis two values ​​7,8

      Can be obtained (1,7) (2,7) (3,7) (1,8) (2,8) (3,8)

      import numpy as np

      Coordinate vector

      a=np.array([1,2,3])
      b=np.array([7,8])

      Returns the coordinates from the coordinate vector matrix

      The value returns a list, the first element is the value of the x-axis, the second element is the y-axis

      res=np.meshgrid(a,b)

      print(res)

      a=np.arange(5)
      b=np.arange(6)
      datalist=np.meshgrid(a,b)
      print(datalist)
      '''
      [array([[0, 1, 2, 3, 4],
             [0, 1, 2, 3, 4],
             [0, 1, 2, 3, 4],
             [0, 1, 2, 3, 4],
             [0, 1, 2, 3, 4],
             [0, 1, 2, 3, 4]]), array([[0, 0, 0, 0, 0],
             [1, 1, 1, 1, 1],
             [2, 2, 2, 2, 2],
             [3, 3, 3, 3, 3],
             [4, 4, 4, 4, 4],
             [5, 5, 5, 5, 5]])]
      '''

Guess you like

Origin www.cnblogs.com/clove7/p/11536401.html