Python—matplotlib library series learning (1): plot function (including title, xlabel, ylabel, legend function)

Table of contents

introduction

plot function

(1) A simple example

(2) Parameter description

         1. marker (marker style string)

         2. color (color)

         3. linestyle 和 linewidth

(3) A simple way of writing

(4) Draw multiple lines on a graph

(5) Beautification supplements for general graphics

        1. Title

        2. x-axis - y-axis naming

        3. Legend 

Summarize


Series of articles to learn:

Python—matplotlib library series learning (1): plot function


introduction

        When I was studying, I mainly referred to the following websites, and you can also learn by yourself! And this article is biased towards novices to learn. The content of this article must be pediatrics~~, of course, this article is also more convenient for me to directly find parameters when I follow up drawing pictures. It is a comparison System articles. I hope it can help everyone. If you have any questions, please criticize and correct me. I am also making continuous progress.

        The content of the article may be more, you can better find what you want according to the catalog, if there is any reprint, please indicate the source, thank you~

         As a series of articles, I will continue to update. Otherwise, I have to write too much at one time, and some functions will be added with subsequent updates.

matplotlib — Matplotlib 3.7.1 documentationhttps://matplotlib.org/stable/api/matplotlib_configuration_api.html

plot function

(1) A simple example

        Let's look at a simple code first:

import matplotlib.pyplot as plt
plt.plot([1,2])
plt.show()

        This draws a very simple image. Note that the [1,2] inside represents the vertical coordinate from 1 to 2, so in fact, only one y parameter is needed in the plot function to draw the picture.

        Then we have given the y coordinate, how is the x coordinate determined? You can observe that the x-axis starts from 0, and there are two numbers in the array, so it reaches 1. Let's give an example, if there are 8 numbers in the array:

import matplotlib.pyplot as plt
plt.plot([1,2,5,10,19,56,64,80])
plt.show()

        We found that the x-axis does start from 0 according to the number of elements in the array. Of course, if you want to define the coordinates of the x-axis yourself, we can add it in front. The first parameter represents the x-axis, and the latter parameter represents the y- axis :

import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[1,2,3,8])
plt.show()

         But such a graph is too ugly, we can add various parameters to it to beautify and perfect our graph~ The following code:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4],[1,2,3,8],color='green', marker='o', linestyle='dashed',
     linewidth=2, markersize=12)
plt.show()

        Does it look much better than last time? Here I added a lot of parameters contained in the plot function. I will explain to you one by one next, and there are also many parameters that are also applicable to other plotting functions in matplotlib.

(2) Parameter description

        In addition to the x and y mentioned above, the more commonly used parameters are marker, color, linestyle, etc. Let's talk about them one by one

import matplotlib.pyplot as plt
x = [1,2,3]
y = [1,2,3]
plt.plot(x,y, marker='o',color='r')
plt.show()

 1. marker (marker style string)

        He can define the style of each point. For example, the above 'o' represents a circle, and it has many other styles:

'.'

point marker

','

pixel marker

'o'

circle marker

'v'

triangle_down marker (inverted triangle mark)

'^'

triangle_up marker (regular triangle mark)

'<'

triangle_left marker (left triangle mark)

'>'

triangle_right marker (right triangle mark)

'1'

tri_down marker

'2'

tri_up marker

'3'

tri_left marker

'4'

tri_right marker

'8'

octagon marker

's'

square marker

'p'

pentagon marker

'P'

plus (filled) marker

'*'

star marker (star triangle logo)

'h'

hexagon1 marker

'H'

hexagon2 marker

'+'

plus fields

'x'

x marker

'X'

x (filled) marker

'D'

diamond marker (diamond.....is actually a diamond logo)

'd'

thin_diamond marker

'|'

vline marker

'_'

clay marker

        For the rest, try to match ~ with the marker and there are many parameters below:

markeredgecolor or mec

color (the color of the border)

markeredgewidth or mew

float (width of border)

markerfacecolor or mfc

color (inner color)

markerfacecoloralt or mfcalt

color (I don't know what it means, but you can ignore it if you don't use it much)

markersize or ms

float (size of the marker style)

        For example, you can see it at a glance by combining the above meanings:

import matplotlib.pyplot as plt
x = [1,2,3]
y = [1,2,3]
plt.plot(x,y, marker='o',color='black',
         markersize=10,markeredgecolor='red',
         markerfacecolor='blue',markeredgewidth=3,
         )
plt.show()

2. color (color)

        matplotlib gives several basic colors in the reference documentation:

'b'

blue

'g'

green

'r'

red

'c'

cyan

'm'

magenta

'y'

yellow

'k'

black

'w'

white

        But in fact, I don’t use these color schemes when I’m playing games or doing scientific research. We can find other colors by ourselves. The following article is very good . is allowed!

Hexadecimal comparison table         about colors

import matplotlib.pyplot as plt
x = [1,2,3]
y = [1,2,3]
plt.plot(x,y, marker='s',color='MediumSpringGreen') #适中的春天的绿色~~
plt.show()

 3. linestyle 和 linewidth

        You can understand these two parameters literally. One is to adjust the style of the drawn line, and the other is to adjust the thickness of the line. Let's give an example:

import matplotlib.pyplot as plt
x = [1,2,3]
y = [1,2,3]
plt.plot(x,y, marker='o', linestyle='-.' , linewidth = 3)
plt.show()

        The following are the specific line styles:

'-'

solid line style

'--'

dashed line style

'-.'

dash-dot line style (dot line style)

':'

dotted line style (square dot style)

(3) A simple way of writing

        我们可以把上述参数中的marker、color和linestyle写在一起,或者他们之间的两两组合,此时他们的的参数名可以省略,并写在一个' '中,我们看下面的例子

import matplotlib.pyplot as plt
x = [1,2,3]
y = [1,2,3]
plt.plot(x,y,'r>--')
plt.show()

         上述是把颜色红色、点的样式右三角形和虚线风格放在一起。注意:如果要这么去写,颜色必须要写上述matplotlib在参考文档给出的,否则你就单独把color拿出来写!!!点的风格和线的风格我也都在上面给出了,大家根据需要自己选择。

(4)一个图上画多条线

        我们使用plot函数,也可以在一个图上画多条线的,如下:

mport numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"]=["SimHei"] #设置字体
plt.rcParams["axes.unicode_minus"]=False #该语句解决图像中的“-”负号的乱码问题
a = [0,1,2,3,4]
b = [10,9,8,7,6]
c = [1,2,3,4,5]
d = [9,1,8,2,5]
font = {                      #设置一个后续xy轴和标题使用的字体(包括大小、颜色等)
        'color':  'black',
        'weight': 'normal',
        'size': 20,
        }
plt.plot(a, b, 'k--' , a, c, 'k:', a, d, 'k')  #重点! 三个线的代码写在一起
plt.legend(('NO.1', 'NO.2', 'NO.3'),     #图例
           loc='best', shadow=True, fontsize=16)
plt.xlabel('x轴',fontdict=font)
plt.ylabel('y轴',fontdict=font)
plt.title('一张图',fontdict=font)
plt.show()

 

(5)通用的图形的美化补充

        要画出一个比较美观的图像,单靠上面的调整肯定是不够的,我们还可以给图像加上标题、图例、横纵坐标含义等等,我们接下来就说几个常用的!

1. 标题

        先说明一下其中包含的参数,我们在给出代码及说明:

import matplotlib.pyplot as plt
plt.title(label, fontdict=None, loc=None, pad=None , y=None, **kwargs)
#label      指的是你输入标题的名称
#fontdict   指的是使用字典控制文本的外观,例如文本大小,文本对齐方式等
#           {fontdict = {‘fontsize’:rcParams [‘axes.titlesize’],
#           ‘fontweight’:rcParams [‘axes.titleweight’],
#           ‘verticalalignment’:‘baseline’,
#           ‘horizontalalignment’:loc}

#loc        指的是标题的位置,例如'center','left','right'等
#pad        指的是标题距轴顶部的偏移量(以磅为单位)  float型
#y          指的是标题的垂直轴位置(1.0为顶部),可以为负值,标题会跑到图的底下  float型
#**kwargs   指的是使用其他关键字参数作为文本属性,比如color、fonstyle、linespacing、background等

        接下来我们以具体的例子来实践一下: 

import matplotlib.pyplot as plt
x = [1,2,3]
y = [1,2,6]
plt.plot(x,y,'c>--')
#plt.title(label="hello world")
plt.title("hello world")
plt.show()

         其实,正常情况下,很多都直接定个标题就完事了,上方代码注释部分和下面的代码是一个意思,只是下面把label省略了。在举个例子:

import matplotlib.pyplot as plt
x = [1,2,3]
y = [1,2,6]
plt.plot(x,y,'c>--')
plt.title(label="hello world",loc="left",fontdict={'fontsize':50})
plt.show()

         另一个例子:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0.0, 5.0, 100)
y = np.cos(2*np.pi*x) * np.exp(-x)

font = {'family': 'serif',
        'color':  'darkred',
        'weight': 'normal',
        'size': 16,
        }
plt.plot(x,y)
plt.title(label="Damped exponential decay",loc="right",fontdict=font)
plt.show()

         其他的参数大家也可以自己多去尝试,有什么问题随时可以跟我讨论(评论区私信都可以~)

2. x轴 - y轴命名

        它们分别是xlabel和ylabel!我们还是先说一下他们中的常用参数:

import matplotlib.pyplot as plt
plt.xlabel(xlabel, fontdict=None, labelpad=None, loc=None, **kwargs))
plt.ylabel(ylabel, fontdict=None, labelpad=None, loc=None, **kwargs))
#xlabel或ylabel  指的是你输入x轴或y轴的名称
#labelpad   类型为浮点数,默认值为None,即标签与坐标轴的距离
#loc        指的是x或y轴名称的位置,例如:针对x轴为'center','left','right';针对y轴为'center','top','bottom'
#**kwargs   指的是Text对象关键字属性,用于控制文本的外观属性,如字体、文本颜色等

        举个栗子!

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

plt.plot(t, s)
plt.title(r'$\mathcal{A}\sin(\omega t)$', fontsize=20)
plt.xlabel('Time [s]')
plt.ylabel('Voltage [mV]')
plt.show()

3. 图例 

        老规矩,看一下它的参数,这里matplotlib说明文档里面给了一大堆,感觉有一些也用不上,我也参考了一些资料选出一些比较常用的:

(2 messages) Python: Detailed Explanation of the Parameters of plt.legend or ax.legend Setting the Legendicon-default.png?t=N3I4

import matplotlib.pyplot as plt
plt.legend(loc='lower right', fontsize=12, frameon=True, fancybox=True, framealpha=0.2, borderpad=0.3,ncol=1, markerfirst=True, markerscale=1, numpoints=1, handlelength=3.5)

#loc:图例位置,可取(‘best’, ‘upper right’, ‘upper left’, ‘lower left’, ‘lower right’, ‘right’, ‘center left’, ‘center , right’, ‘lower center’, ‘upper center’, ‘center’) ;若是使用了bbox_to_anchor,则这项就无效了
#fontsize:代表字体大小,int或float或{‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}
#frameon:是否显示图例边框,
#ncol:图例的列的数量,默认为1,
#title:为图例添加标题
#shadow:是否为图例边框添加阴影,
#markerfirst:True表示图例标签在句柄右侧,false反之,
#markerscale:图例标记为原图标记中的多少倍大小,
#numpoints:表示图例中的句柄上的标记点的个数,一般设为1,
#fancybox:是否将图例框的边角设为圆形
#framealpha:控制图例框的透明度
#borderpad:图例框内边距
#labelspacing:图例中条目之间的距离
#andlelength:图例句柄的长度
#bbox_to_anchor:(横向看右,纵向看下),如果要自定义图例位置或者将图例画在坐标外边,用它

For example, the picture         I drew above (below) is an example of a legend, where best refers to placing the legend in the best position in the picture. You can also experiment with the remaining parameters, so that you can understand more deeply!

Summarize

        Of course, there are still many functions in the above learning that can improve our graphics. We will leave it for the next article to explain, and we will talk about a new graphics function.

        I hope that you can point out the problems in time if you find any problems. I am also constantly learning and improving~~~ Thank you for watching, if it helps you, please give it a thumbs up~

Guess you like

Origin blog.csdn.net/m0_51440939/article/details/130600205