Python进阶(三十九)-数据可视化の使用matplotlib进行绘图分析数据

网友投稿 1137 2022-05-30

#Python进阶(三十九)-数据可视化の使用matplotlib进行绘图分析数据

matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图。而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中。

它的文档相当完备,并且 Gallery页面 中有上百幅缩略图,打开之后都有源程序。因此如果你需要绘制某种类型的图,只需要在这个页面中浏览/复制/粘贴一下,基本上都能搞定。

在Linux下比较著名的数据图工具还有gnuplot,这个是免费的,Python有一个包可以调用gnuplot,但是语法比较不习惯,而且画图质量不高。

而 Matplotlib则比较强:Matlab的语法、python语言、latex的画图质量(还可以使用内嵌的latex引擎绘制的数学公式)。

matplotlib中的快速绘图的函数库可以通过如下语句载入:

import matplotlib.pyplot as plt

1

matplotlib还提供了名为pylab的模块,其中包括了许多numpy和pyplot中常用的函数,方便用户快速进行计算和绘图,可以用于IPython中的快速交互式使用。

接下来调用figure创建一个绘图对象,并且使它成为当前的绘图对象。

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

1

也可以不创建绘图对象直接调用接下来的plot函数直接绘图,matplotlib会为我们自动创建一个绘图对象。如果需要同时绘制多幅图表的话,可以是给figure传递一个整数参数指定图标的序号,如果所指定序号的绘图对象已经存在的话,将不创建新的对象,而只是让它成为当前绘图对象。

通过figsize参数可以指定绘图对象的宽度和高度,单位为英寸;dpi参数指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80。因此本例中所创建的图表窗口的宽度为880 = 640像素。

但是用工具栏中的保存按钮保存下来的png图像的大小是800400像素。这是因为保存图表用的函数savefig使用不同的DPI配置,savefig函数也有一个dpi参数,如果不设置的话,将使用matplotlib配置文件中的配置,此配置可以通过如下语句进行查看:

import matplotlib matplotlib.rcParams[savefig.dpi]

1

2

下面的两行程序通过调用plot函数在当前的绘图对象中进行绘图:

plt.plot(years, price, 'b*')#,label=$cos(x^2)$) plt.plot(years, price, 'r')

Python进阶(三十九)-数据可视化の使用matplotlib进行绘图分析数据

1

2

plot函数的调用方式很灵活,第一句将x,y数组传递给plot之后,用关键字参数指定各种属性:

label : 给所绘制的曲线一个名字,此名字在图示(legend)中显示。只要在字符串前后添加$符号,matplotlib就会使用其内嵌的latex引擎绘制的数学公式。

color : 指定曲线的颜色

linewidth : 指定曲线的宽度

第一句直接通过第三个参数b–指定曲线的颜色和线型,这个参数称为格式化参数,它能够通过一些易记的符号快速指定曲线的样式。其中b表示蓝色,–表示线型为虚线。

在IPython中输入 plt.plot? 可以查看格式化字符串的详细配置。

接下来通过一系列函数设置绘图对象的各个属性:

plt.xlabel(years(+2000)) plt.ylabel(housing average price(*2000 yuan)) plt.ylim(0, 15) plt.title('line_regression & gradient decrease') plt.legend()

1

2

3

4

5

xlabel : 设置X轴的文字

ylabel : 设置Y轴的文字

title : 设置图表的标题

ylim : 设置Y轴的范围

legend : 显示图示

最后调用plt.show()显示出我们创建的所有绘图对象。

##配置属性

matplotlib所绘制的图的每个组成部分都对应有一个对象,我们可以通过调用这些对象的属性设置方法set_*或者pyplot的属性设置函数setp设置其属性值。例如plot函数返回一个 matplotlib.lines.Line2D 对象的列表,下面的例子显示如何设置Line2D对象的属性:

import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1) line, = plt.plot(x, x*x) # plot返回一个列表,通过line,获取其第一个元素 # 调用Line2D对象的set_*方法设置属性值 line.set_antialiased(False) # 同时绘制sin和cos两条曲线,lines是一个有两个Line2D对象的列表 lines = plt.plot(x, np.sin(x), x, np.cos(x)) # 调用setp函数同时配置多个Line2D对象的多个属性值 plt.setp(lines, color=r, linewidth=2.0)

1

2

3

4

5

6

7

8

9

10

这段例子中,通过调用Line2D对象line的set_antialiased方法,关闭对象的反锯齿效果。或者通过调用plt.setp函数配置多个Line2D对象的颜色和线宽属性。

同样我们可以通过调用Line2D对象的get_*方法,或者plt.getp函数获取对象的属性值:

line.get_linewidth() plt.getp(lines[0], color) # 返回color属性 plt.getp(lines[1]) # 输出全部属性 alpha = 1.0 animated = False antialiased or aa = True axes = Axes(0.125,0.1;0.775x0.8)

1

2

3

4

5

6

7

注意getp函数只能对一个对象进行操作,它有两种用法:

指定属性名:返回对象的指定属性的值

不指定属性名:打印出对象的所有属性和其值

matplotlib的整个图表为一个Figure对象,此对象在调用plt.figure函数时返回,我们也可以通过plt.gcf函数获取当前的绘图对象:

f = plt.gcf() plt.getp(f) alpha = 1.0 animated = False

1

2

3

4

Figure对象有一个axes属性,其值为AxesSubplot对象的列表,每个AxesSubplot对象代表图表中的一个子图,前面所绘制的图表只包含一个子图,当前子图也可以通过plt.gca获得:

plt.getp(f, axes) plt.gca()

1

2

用plt.getp可以发现AxesSubplot对象有很多属性,例如它的lines属性为此子图所包括的 Line2D 对象列表:

alllines = plt.getp(plt.gca(), lines) alllines[0] == line # 其中的第一条曲线就是最开始绘制的那条曲线

1

2

通过这种方法我们可以很容易地查看对象的属性和它们之间的包含关系,找到需要配置的属性。

##配置文件

绘制一幅图需要对许多对象的属性进行配置,例如颜色、字体、线型等等。我们在绘图时,并没有逐一对这些属性进行配置,许多都直接采用了matplotlib的缺省配置。

matplotlib将这些缺省配置保存在一个名为“matplotlibrc”的配置文件中,通过修改配置文件,我们可以修改图表的缺省样式。配置文件的读入可以使用rc_params(),它返回一个配置字典;在matplotlib模块载入时会调用rc_params(),并把得到的配置字典保存到rcParams变量中;matplotlib将使用rcParams字典中的配置进行绘图;用户可以直接修改此字典中的配置,所做的改变会反映到此后创建的绘图元素。

##绘制多子图(快速绘图)

Matplotlib 里的常用类的包含关系为 Figure -> Axes -> (Line2D, Text, etc.)一个Figure对象可以包含多个子图(Axes),在matplotlib中用Axes对象表示一个绘图区域,可以理解为子图。

可以使用subplot()快速绘制包含多个子图的图表,它的调用形式如下:

subplot(numRows, numCols, plotNum)

1

subplot将整个绘图区域等分为numRows行* numCols列个子区域,然后按照从左到右,从上到下的顺序对每个子区域进行编号,左上的子区域的编号为1。如果numRows,numCols和plotNum这三个数都小于10的话,可以把它们缩写为一个整数,例如subplot(323)和subplot(3,2,3)是相同的。subplot在plotNum指定的区域中创建一个轴对象。如果新创建的轴和之前创建的轴重叠的话,之前的轴将被删除。

subplot()返回它所创建的Axes对象,我们可以将它用变量保存起来,然后用sca()交替让它们成为当前Axes对象,并调用plot()在其中绘图。

##绘制多图表(快速绘图)

如果需要同时绘制多幅图表,可以给figure()传递一个整数参数指定Figure对象的序号,如果序号所指定的Figure对象已经存在,将不创建新的对象,而只是让它成为当前的Figure对象。

import numpy as np import matplotlib.pyplot as plt plt.figure(1) # 创建图表1 plt.figure(2) # 创建图表2 ax1 = plt.subplot(211) # 在图表2中创建子图1 ax2 = plt.subplot(212) # 在图表2中创建子图2 x = np.linspace(0, 3, 100) for i in xrange(5): plt.figure(1) #? # 选择图表1 plt.plot(x, np.exp(i*x/3)) plt.sca(ax1) #? # 选择图表2的子图1 plt.plot(x, np.sin(i*x)) plt.sca(ax2) # 选择图表2的子图2 plt.plot(x, np.cos(i*x)) plt.show()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

##在图表中显示中文

matplotlib的缺省配置文件中所使用的字体无法正确显示中文。为了让图表能正确显示中文,可以有几种解决方案

在程序中直接指定字体。

在程序开头修改配置字典rcParams。

修改配置文件。

比较简便的方式是,中文字符串用unicode格式,例如:u’‘测试中文显示’’,代码文件编码使用utf-8 加上 # coding = utf-8。

但以上方法只是解决了标题部分显示中文的问题,并未解决图例中文显示的问题。可采用修改配置字典的方式设置图例显示中文,代码如下:

# 指定中文字体 mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体

1

2

配置好配置字典之后即可实现图例显示中文。

![这里写图片描述](https://img-blog.csdnimg.cn/img_convert/b753f298918e8eff2f45fd7c6abeb162.png)   matplotlib API包含有三层,Artist层处理所有的高层结构,例如处理图表、文字和曲线等的绘制和布局。通常我们只和Artist打交道,而不需要关心底层的绘制细节。   直接使用Artists创建图表的标准流程如下:

创建Figure对象

用Figure对象创建一个或者多个Axes或者Subplot对象

调用Axies等对象的方法创建各种简单类型的Artists

import matplotlib.pyplot as plt X1 = range(0, 50) # y = x^2 X2 = [0, 1] Y2 = [0, 1] # y = x Y1 = [num**2 for num in X1] # Create a `figure' instance Fig = plt.figure(figsize=(8,4)) # Create a `axes' instance in the figure Ax = Fig.add_subplot(111) # Create a Line2D instance in the axes Ax.plot(X1, Y1, X2, Y2) Fig.show() Fig.savefig(test.pdf)

1

2

3

4

5

6

7

8

9

10

11

12

matplotlib还提供了一个名为pylab的模块,其中包括了许多NumPy和pyplot模块中常用的函数,方便用户快速进行计算和绘图,十分适合在IPython交互式环境中使用。这里使用下面的方式载入pylab模块:

import pylab as pl import numpy numpy.__version__ import matplotlib matplotlib.__version__

1

2

3

4

5

##折线图 Line plots(关联一组x和y值的直线)

import numpy as np import pylab as pl x = [1, 2, 3, 4, 5]# Make an array of x values y = [1, 4, 9, 16, 25]# Make an array of y values for each x value pl.plot(x, y)# use pylab to plot x and y pl.show()# show the plot on the screen

1

2

3

4

5

6

##散点图 Scatter plots

把pl.plot(x, y)改成pl.plot(x, y, ‘o’)即可,下图的蓝色版本

##美化 Making things look pretty

###线条颜色 Changing the line color

红色:把pl.plot(x, y, ‘o’)改成pl.plot(x, y, ’or’)

###线条样式 Changing the line style

虚线:plot(x,y, ‘–’)

###marker样式 Changing the marker style

蓝色星型markers:plot(x,y, ’b*’)

###图和轴标题以及轴坐标限度 Plot and axis titles and limits

import numpy as np import pylab as pl x = [1, 2, 3, 4, 5]# Make an array of x values y = [1, 4, 9, 16, 25]# Make an array of y values for each x value pl.plot(x, y)# use pylab to plot x and y pl.title(’Plot of y vs. x’)# give plot a title pl.xlabel(’x axis’)# make axis labels pl.ylabel(’y axis’) pl.xlim(0.0, 7.0)# set axis limits pl.ylim(0.0, 30.) pl.show()# show the plot on the screen

1

2

3

4

5

6

7

8

9

10

11

###在一个坐标系上绘制多个图 Plotting more than one plot on the same set of axes

做法是很直接的,依次作图即可:

import numpy as np import pylab as pl x1 = [1, 2, 3, 4, 5]# Make x, y arrays for each graph y1 = [1, 4, 9, 16, 25] x2 = [1, 2, 4, 6, 8] y2 = [2, 4, 8, 12, 16] pl.plot(x1, y1, ’r’)# use pylab to plot x and y pl.plot(x2, y2, ’g’) pl.title(’Plot of y vs. x’)# give plot a title pl.xlabel(’x axis’)# make axis labels pl.ylabel(’y axis’) pl.xlim(0.0, 9.0)# set axis limits pl.ylim(0.0, 30.) pl.show()# show the plot on the screen

1

2

3

4

5

6

7

8

9

10

11

12

13

14

###图例 Figure legends

pl.legend((plot1, plot2), (’label1, label2’), 'best’, numpoints=1)

其中第三个参数表示图例放置的位置:'best’‘upper right’, ‘upper left’, ‘center’, ‘lower left’, ‘lower right’.

如果在当前figure里plot的时候已经指定了label,如plt.plot(x,z,label=cos(x2)),直接调用plt.legend()就可以了哦。

import numpy as np import pylab as pl x1 = [1, 2, 3, 4, 5]# Make x, y arrays for each graph y1 = [1, 4, 9, 16, 25] x2 = [1, 2, 4, 6, 8] y2 = [2, 4, 8, 12, 16] plot1 = pl.plot(x1, y1, ’r’)# use pylab to plot x and y : Give your plots names plot2 = pl.plot(x2, y2, ’go’) pl.title(’Plot of y vs. x’)# give plot a title pl.xlabel(’x axis’)# make axis labels pl.ylabel(’y axis’) pl.xlim(0.0, 9.0)# set axis limits pl.ylim(0.0, 30.) pl.legend([plot1, plot2], (’red line’, ’green circles’), ’best’, numpoints=1)# make legend pl.show()# show the plot on the screen

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

##直方图 Histograms

import numpy as np import pylab as pl # make an array of random numbers with a gaussian distribution with # mean = 5.0 # rms = 3.0 # number of points = 1000 data = np.random.normal(5.0, 3.0, 1000) # make a histogram of the data array pl.hist(data) # make plot labels pl.xlabel(’data’) pl.show()

1

2

3

4

5

6

7

8

9

10

11

12

如果不想要黑色轮廓可以改为pl.hist(data, histtype=’stepfilled’)

###自定义直方图bin宽度 Setting the width of the histogram bins manually

增加这两行

bins = np.arange(-5., 16., 1.) #浮点数版本的range pl.hist(data, bins, histtype=’stepfilled’)

1

2

##绘制文件中的数据Plotting data contained in files

###从Ascii文件中读取数据 Reading data from ascii files

读取文件的方法很多,这里只介绍一种简单的方法,更多的可以参考官方文档和NumPy快速处理数据(文件存取)。

numpy的loadtxt方法可以直接读取如下文本数据到numpy二维数组

********************************************** # fakedata.txt 0 0 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 0 0 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 ********************************************** import numpy as np import pylab as pl # Use numpy to load the data contained in the file # ’fakedata.txt’ into a 2-D array called data data = np.loadtxt(’fakedata.txt’) # plot the first column as x, and second column as y pl.plot(data[:,0], data[:,1], ’ro’) pl.xlabel(’x’) pl.ylabel(’y’) pl.xlim(0.0, 10.) pl.show()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

###写入数据到文件 Writing data to a text file

写文件的方法也很多,这里只介绍一种可用的写入文本文件的方法,更多的可以参考官方文档。

import numpy as np # Let’s make 2 arrays (x, y) which we will write to a file # x is an array containing numbers 0 to 10, with intervals of 1 x = np.arange(0.0, 10., 1.) # y is an array containing the values in x, squared y = x*x print ’x = ’, x print ’y = ’, y # Now open a file to write the data to # ’w’ means open for ’writing’ file = open(’testdata.txt’, ’w’) # loop over each line you want to write to file for i in range(len(x)): # make a string for each line you want to write # ’ ’ means ’tab’ # ’’ means ’newline’ # ’str()’ means you are converting the quantity in brackets to a string type txt = str(x[i]) + ’ ’ + str(y[i]) + ’ ’ # write the txt to the file file.write(txt) # Close your file file.close()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

##对LaTeX数学公式的支持

Matlplotlib对LaTeX有一定的支持,如果记得使用raw字符串语法会很自然:xlabel(rx2y4)

在matplotlib里面,可以使用LaTex的命令来编辑公式,只需要在字符串前面加一个“r”即可

这里给大家看一个简单的例子。

import matplotlib.pyplot as plt x = arange(1,1000,1) r = -2 c = 5 y = [5*(a**r) for a in x] fig = plt.figure() ax = fig.add_subplot(111) ax.loglog(x,y,label = ry=12σ21,c=5,σ1=−2) ax.legend() ax.set_xlabel(rx) ax.set_ylabel(ry)

1

2

3

4

5

6

7

8

9

10

11

再看一个《用Python做科学计算》中的简单例子,下面的两行程序通过调用plot函数在当前的绘图对象中进行绘图:

plt.plot(x,y,label=sin(x),color=red,linewidth=2) plt.plot(x,z,b--,label=cos(x2))

1

2

##matplotlib.rcParams属性字典

想要它正常工作,在matplotlibrc配置文件中需要设置text.markup = tex。

如果你希望图表中所有的文字(包括坐标轴刻度标记)都是LaTeX,需要在matplotlibrc中设置text.usetex = True。如果你使用LaTeX撰写论文,那么这一点对于使图表和论文中其余部分保持一致是很有用的。

##matplotlib使用小结

在实际中,我们可能经常会用到对数坐标轴,这时可以用下面的三个函数来实现。

ax.semilogx(x,y) #x轴为对数坐标轴

ax.semilogy(x,y) #y轴为对数坐标轴

ax.loglog(x,y) #双对数坐标轴

##学习资源

利用matplotlib 进行折线图,直方图和饼图的绘制

matplotlib图表中图例大小及字体相关问题

matplotlib绘图库入门

http://sebug.net/paper/books/scipydoc/matplotlib_intro.html

使用 python Matplotlib 库绘图

![这里写图片描述](https://img-blog.csdnimg.cn/img_convert/f9c024e20306fb0e4e3e84a15aab3217.png)

Python 数据可视化

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:用 Kubernetes 部署 Crawlab 爬虫管理节点集群
下一篇:软件工程之思系列---初窥门径
相关文章