News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

no datas

Python visualization - detailed explanation of basic parameters of matplotlib.pyplot drawing

posted on 2023-05-07 20:22     read(785)     comment(0)     like(29)     collect(4)


Table of contents

1. Introduction to matplotlib

2. Function usage of graphic components

2.1. figure(): background color

2.2 xlim() and ylim(): Set the numerical display range of the x and y axes

2.3 xlabel() and ylabel(): Set the label text of the x and y axes

2.4 grid(): Draw the grid lines of the tick marks

2.5 axhline(): Draw a horizontal reference line parallel to the x-axis

2.6 axvspan(): Draw a reference area perpendicular to the x-axis

2.7 xticks(),yticks()

2.8 annotate(): Add point-to-point annotation text for graphic content details

2.9 bbox: add a frame to the title

2.10 . text(): A non-pointing comment text (watermark) that adds graphic content details

2.11. title(): Add the title of the graphic content

2.12. legend(): Mark the text label legend of different graphics

2.13 table(): add a table to the subgraph

3. Complete code display

4. The line style of the line chart

5. Commonly used color abbreviations

6. Summary


1. Introduction to matplotlib

The matplotlib library is a data visualization tool for drawing 2D and 3D charts in Python

Features:
    Use simple drawing statements to achieve complex drawing effects  Use
    interactive operations to achieve progressively finer graphics effects 
    Use embedded LaTex to output charts, scientific expressions, and symbolic texts with printed grades
    Realize fine-grained control over the constituent elements of charts

Three drawing interfaces

        pyplot: face the current plot

        axes: object-oriented

        Pylab: follow the matlab style

This article uses plot drawing ( displaying the trend change of variables ) to display the basic parameters of the drawing, and uses the numpy library to obtain the drawing data (random). The final graphics are not carefully thought out, and everything is mainly to display the graphics parameters! ! !

Libraries used:

  1. import matplotlib.pyplot as plt
  2. import numpy as np

2. Function usage of graphic components

  plot(): Display the trend change of variables

   Usage: plt.plot(x, y, c, ls, lw, label, alpha, **kwargs)       
          x, y: the value on the x, y axis
          c: set the color
          ls: the line style of the line chart
          lw: the line width of the line chart
          label: the label text that marks the graphic content
          alpha: transparency
          **kwargs: specifies the use of the line2D attribute
        

 2.1. figure(): background color

        How to use: figure(num=None, figsize=None, dpi=None, facecolor=None,
edgecolor=None, frameon=True, FigureClass=Figure, clear=False, **kwargs)  
on one :
        If this parameter is not provided, a new figure object will be created and the figure count value will be incremented, which is stored in a number property of the figure object. If there is this parameter and there is a figure object corresponding to id, activate the figure object for id. If a figure object for id does not exist, create it and return it. If the value of num is a string, set the window title to this string
figsize: Width and height in inches, the default value is rc figure.figsize (1 inch is equal to 2.54 cm)
dpi: graphics resolution, the default value is rc figure.dpi
facecolor: background color
  1. plt.figure(figsize=(10, 10))
  2. x = np.linspace(0.05, 10, 1000) # 在0.05到10的区间中,等差选取1000个,端点不属于
  3. y = np.sin(x)
  4. plt.rcParams['font.sans-serif'] = ['SimHei']
  5. plt.rcParams['axes.unicode_minus'] = False
  6. plt.plot(x, y,
  7. color='red',
  8. ls='-',
  9. label='sinx')
  10. plt.show()

 2.2  xlim() and ylim(): Set the numerical display range of the x and y axes

 How to use: plt.xlim(xmin,xmax)
        xmin: the minimum value on the x-axis
        xmax: the maximum value on the x-axis

2.3  xlabel() and ylabel(): Set the label text of the x and y axes

How to use: plt.xlabel(fontsize, verticalalignment, horizontalalignment, rotation, bbox)
 
fontsize: number or (small, large, medium)
verticalalignment: the position from the coordinate axis (top, bottom, center, baseline)
hoizontalalignment: position (center, right, left)
ratio: position (vertical, horizontal, vertical)
bbox: add a border

2.4  grid(): Draw the grid lines of the tick marks

How to use: plt.grid(linestyle, color)

2.5  axhline(): Draw a horizontal reference line parallel to the x-axis

How to use: plt.axhline(y, c, ls, lw, label)
y: the starting point of the horizontal reference line
  1. plt.figure(figsize=(10, 10))
  2. x = np.linspace(0.05, 10, 1000) # 在0.05到10的区间中,等差选取1000个,端点不属于
  3. y = np.sin(x)
  4. plt.rcParams['font.sans-serif'] = ['SimHei']
  5. plt.rcParams['axes.unicode_minus'] = False
  6. plt.plot(x, y,
  7. color='red',
  8. ls='-',
  9. label='sinx')
  10. plt.xlim(1, 10)
  11. plt.ylim(-1, 1)
  12. plt.xlabel('x轴')
  13. plt.ylabel('y轴')
  14. plt.grid(ls=':',
  15. color='blue') # 设置网格,颜色为蓝色
  16. plt.axhline(0.5, color='green', lw=2, label="分割线") # 绘制平行于x轴的水平参考线,绿色,名称
  17. plt.show()

(The green line in the above figure is the reference line added by axjline())

2.6  axvspan(): Draw a reference area perpendicular to the x-axis

How to use: plt.axvspan( xmin, xmax ,facecolor, alpha)
xmin: the starting position of the reference area
xmax: the end position of the reference area
facecolor: the fill color of the reference area
alpha: the transparency of the fill color of the reference area, [0~1]
Note: Its usage method can also be used on axhspan()
In the previous code add
  1. plt.axvspan(xmin=2,
  2. xmax=5,
  3. facecolor='r',
  4. alpha=0.2) # 绘制垂直于x轴的参考区域

That is to get (note: this paragraph is the area)

 2.7 xticks(),yticks()

        Get or set the current x-axis or y-axis scale position and label (that is, set the label of the x or y axis)

It can be understood as setting the same effect as xilim and ylim, but you can specify the range and distance

plt.xticks(list(range(0, 12, 1)))  # 调整刻度范围和刻度标签

Pay attention to the x-axis, from the original 0~10 to the current 0~11, you can set the step size by setting the third parameter, here it is set to 1

2.8  annotate(): Add point-to-point annotation text for graphic content details

Function method: plt.annotate()

s: Comment text content

xy: the coordinate point to be annotated

xytext: the coordinate position of the annotation text
weight: Set font line style (Ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extrabold, black)
color: Set the font color; you can also set the color of RGB or RGBA type; but it must be a floating point number between [0,1]         
The xycoords= parameters are as follows
     figure points: the point in the lower left corner of the figure
     figure pixels: the pixels in the lower left corner of the figure
     figure fraction: the lower left part of the figure
     Axes points: the point at the lower left of the coordinate axis
     Axes pixels: the pixel at the bottom left of the coordinate axis
     data: use the coordinate system of the annotated object
     arrowprops: Arrow parameters, parameter type is dictionary dict
     width: the width of the arrow
     headwidth: the width in points of the bottom of the arrow
     headlength: the length of the arrow
     shrink: a portion of the total length that "shrinks" from both ends
     facecolor: arrow color (if the arrowstyle keyword is set, none of the above parameters can be used, you can
to use these:
                                -
                                ->
                                -[
                                |-|
                                -|>
                                <->
                                <|-
                                <|-|>
                                fancy
                                simple
                                wedge
  1. plt.annotate('local',
  2. xy=(2, 1),
  3. xytext=(0.5, 0.5),
  4. weight='bold',
  5. color='red',
  6. xycoords="data",
  7. arrowprops=
  8. dict(arrowstyle="->", connectionstyle='arc3', color='b'),
  9. bbox=
  10. dict(boxstyle="rarrow",
  11. pad=0.6,
  12. fc="yellow",
  13. ec='k',
  14. lw=1,
  15. alpha=0.5)
  16. )

 The yellow arrow and the blue slender line here are the parameters added by the parameter method. In the actual use process, it can be used according to your actual needs. It can be considered as adding some explanations to the image.

2.9  bbox: add a frame to the title

(boxstyle: box shape; circle: ellipse; darrow: two-way arrow; larrow: arrow to the left; rarrow: arrow

head to the right; round: rounded rectangle; round4: oval; roundtooth: wavy border 1; sawtooth:

Wavy border 2; square: rectangle)

2.10 . text(): A non-pointing comment text (watermark) that adds graphic content details

Function method: plt.text()

x, y: represent the value on the coordinate axis
weight:
            ultralightlight
            normal
            regular
            book
            medium
            roman
            semibold
            demibold
            sake
            bold
            heavy
            extrabold
            black
xycoodrds:
    figure points: the point in the lower left corner of the figure
    figure pixels: the pixels in the lower left corner of the figure
    figure fraction: the lower left part of the figure
    Axes points: the point at the lower left of the coordinate axis
    Axes pixels: the pixel at the bottom left of the coordinate axis
                        
data: use the coordinate system of the annotated object
                
bbox: add a frame to the title
           boxstyle: box shape
           circle: ellipse
           darrow: two-way arrow
           larrow: Arrow pointing left
           narrow: Arrow pointing to the right
           round: rounded rectangle
           round4: Ellipse
           roundtooth: wavy border 1
           sawtooth: wavy border 2
           square: rectangle         
  1. plt.text(1, 1,
  2. "y=sinx",
  3. weight='bold',
  4. color ='b')

    Here it is set on the coordinates (1, 1), which is the blue field of y=sinx below the text

2.11. title(): Add the title of the graphic content

plt.title("正弦函数")

2.12. legend(): Mark the text label legend of different graphics

How to use: plt.legeng()

The geographical position of the legend in the figure:
                        best
                        upper right
                        upper left
                        lower left
                        lower right
                        right
                        center left
                        center right
                        lower center
                        upper center
                        center
plt.legend(loc="lower left")  # 设置图例位置

2.13  table(): add a table to the subgraph

plt.table(cellText=None, cellColours=None, cellloc='right' ,colWidths=None,
rowLabels=None, rowColours=None, collLabels=None, colColours=None,
collloc='center', loc='bpttpm', bbox=None, edges='closed', **kwargs)
cellText:表格单元格文本。类型为二维字符串列表
cellColours:表格单元格背景色。类型为二位颜色值列表
cellloc:表格单元格文本的对齐方式。默认值为right
                                left
                                right
                                center
colWidths:表格单元格宽度。类型为浮点数列表
rowLabels:表格行表头文本。类型为字符串列表
rowColours:表格行表头背景色。类型为颜色列表
colLabels:表格列表头文本。类型为字符串列表
colLoc:表格行表头文本对齐方式。默认 right
                                left
                                right
                                center
colColours:表格列表头背景色。类型为颜色列表
loc:单元格相对于子图的位置
bbox:绘制表格的边界框,如果此参数不为 None,将会覆盖 loc 参数
      edges:单元格边线,该属性会影响各类单元格背景色
                        BRTL
                        open
                        closed
                        horizontal
                        vertical

3. Complete code display

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. plt.figure(figsize=(10, 10))
  4. x = np.linspace(0.05, 10, 1000) # 在0.05到10的区间中,等差选取1000个,端点不属于
  5. y = np.sin(x)
  6. plt.rcParams['font.sans-serif'] = ['SimHei']
  7. plt.rcParams['axes.unicode_minus'] = False
  8. plt.plot(x, y,
  9. color='red',
  10. ls='-',
  11. label='sinx')
  12. plt.xlim(1, 10)
  13. plt.ylim(-1, 1)
  14. plt.xlabel('x轴')
  15. plt.ylabel('y轴')
  16. plt.grid(ls=':',
  17. color='blue') # 设置网格,颜色为蓝色
  18. plt.axhline(0.5, color='green', lw=2, label="分割线") # 绘制平行于x轴的水平参考线,绿色,名称
  19. plt.axvspan(xmin=2,
  20. xmax=5,
  21. facecolor='r',
  22. alpha=0.2) # 绘制垂直于x轴的参考区域
  23. plt.axhspan(ymin=(-3**0.5)/2,
  24. ymax=(3**0.5)/2,
  25. facecolor='w',
  26. alpha=0.2)
  27. plt.legend(loc="lower left") # 设置图例位置
  28. plt.annotate('local',
  29. xy=(2, 1),
  30. xytext=(0.5, 0.5),
  31. weight='bold',
  32. color='red',
  33. xycoords="data",
  34. arrowprops=
  35. dict(arrowstyle="->", connectionstyle='arc3', color='b'),
  36. bbox=
  37. dict(boxstyle="rarrow",
  38. pad=0.6,
  39. fc="yellow",
  40. ec='k',
  41. lw=1,
  42. alpha=0.5)
  43. )
  44. plt.xticks(list(range(0, 12, 1))) # 调整刻度范围和刻度标签
  45. plt.text(1, 1,
  46. "y=sinx",
  47. weight='bold',
  48. color ='b')
  49. plt.title("正弦函数")
  50. plt.show()

This string of codes is used to display Chinese characters

  1. plt.rcParams['font.sans-serif'] = ['SimHei']
  2. plt.rcParams['axes.unicode_minus'] = False

No matter what picture is drawn, plt.show() must be used to display the picture at the end, otherwise the output is empty

4. The line style of the line chart

     
  1.    -:实线样式
  2.    --:短横线样式
  3.    -.:点划线样式
  4.    ::虚线样式
  5.     .:点标记
  6.     O:圆标记
  7.     V:倒三角标记
  8.     ^:正三角标记
  9.     <:左三角标记
  10.     >:右三角表示
  11.     1:下箭头标记13
  12.     2:上箭头标记
  13.     3:左箭头标记
  14.     4:右箭头标记
  15.     S:正方形标记
  16.     p:五边形标记
  17.     *:星形标记
  18.     H:六边形标记
  19.     +:加号标记
  20.     X:x 标记
  21.     D:菱形标记
  22.     |:竖直线标记
  23.     _:水平线标记

5. Commonly used color abbreviations

  1. b 蓝色
  2. g 绿色
  3. r 红色
  4. c 青色
  5. m 品红色·
  6. y 黄色
  7. k 黑色
  8. w 白色

6. Summary

        Many parameters are sometimes unusable, but you must know that there are, and it is reasonable to exist. Different parameters have different functions and functions. Do not add too many parameters to any graph. Generally, there are legends, titles, and xy-axis ranges.

        No matter which one you use, it is recommended to try it first, practice is the only criterion for testing truth! ! !

        I hope readers will forgive me for the bad writing. I am also groping step by step. If you have any questions, please discuss them in the comment area.



Category of website: technical article > Blog

Author:Ineverleft

link:http://www.pythonblackhole.com/blog/article/342/59b087c740f6776a301f/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

29 0
collect article
collected

Comment content: (supports up to 255 characters)