使用python中的matplotlib进行绘图分析数据

matplotlib 是一个 Python 的 2D绘图库,用于数据可视化。它可以函数的方式操作各个绘图命令(类似Matlab软件,Matplotlib名字的含义就是Matlab风格的绘图库),也可以以面向对象的方式。

它有以下优点:

绘图质量高,可绘制出版物质量级别的图形。

代码够简单,易于理解和扩展,使绘图变得轻松。

兼容Tex 文本,可编写复杂的数学公式(如带上标下标,希腊字母)。

可嵌入图形用户界面,用于应用程序开发。 免费和开源

导包

import matplotlib.pyplot as plt

一、快速绘图

# 准备绘图数据

import numpy as np

x=np.arange(0,1,0.05)

print(x)

[0. 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65

0.7 0.75 0.8 0.85 0.9 0.95]

#y=sin(2*pi*x)

y=np.sin(2*np.pi*x)

print(y)

[ 0.00000000e+00 3.09016994e-01 5.87785252e-01 8.09016994e-01

9.51056516e-01 1.00000000e+00 9.51056516e-01 8.09016994e-01

5.87785252e-01 3.09016994e-01 1.22464680e-16 -3.09016994e-01

-5.87785252e-01 -8.09016994e-01 -9.51056516e-01 -1.00000000e+00

-9.51056516e-01 -8.09016994e-01 -5.87785252e-01 -3.09016994e-01]

#plt.plot

plt.plot(x,y)

plt.show()

# 修改线条颜色,线型

plt.plot(x,y,'b--')#设置蓝色,虚线--

plt.show()

plt.plot(x,y,'b--*')

plt.show()

#添加标题

plt.plot(x,y,'b--*')

plt.title('My first plot')

plt.show()

#添加横纵坐标

plt.plot(x,y,'b--*')

plt.title('My first plot')

plt.xlabel('x lable')

plt.ylabel('y lable')

plt.show()

#添加图例 两步:添加label='sin';调用plt.legend函数

plt.plot(x,y,'b--*',label='sin')

plt.title('My first plot')

plt.xlabel('x lable')

plt.ylabel('y lable')

plt.legend(loc='best')

plt.show()

二、添加多个图表 figure和subplot

#添加多个图表 figure和subplot

fig=plt.figure()#创建figure对象

ax1=fig.add_subplot(221) #221代表两行、两列、第一个图

ax2=fig.add_subplot(222)

ax3=fig.add_subplot(223)

plt.show()

#添加多个图表 figure和subplot

#绘制某个图表

fig=plt.figure()#创建figure对象

ax1=fig.add_subplot(221) #221代表两行、两列、第一个图

ax2=fig.add_subplot(222)

ax3=fig.add_subplot(223)

ax2.plot(x,y)

plt.show()

三、颜色、线条、标记

#颜色、线型、标记

#方法一:

fig=plt.figure()

ax=fig.add_subplot(111)

ax.plot(x,y,'r--*')

plt.show()

# 方法二:根据对象参数设置

fig=plt.figure()

ax=fig.add_subplot(111)

ax.plot(x,y,color='b',line,marker='*')

#添加多个图表 :简写方法subplots

# 方法一:

fig=plt.figure()#创建figure对象

ax1=fig.add_subplot(221) #221代表两行、两列、第一个图

ax2=fig.add_subplot(222)

ax3=fig.add_subplot(223)

ax2.plot(x,y)

plt.show()

#方法二:简写方法subplots

fig,ax=plt.subplots(2,2)

#根据索引定位

ax[0,1].plot(x,y)

plt.show()

#标题、标签、图例

fig,ax=plt.subplots()

ax.plot(x,y,'g--o')

ax.set(title='my first plot',xlabel='x',ylabel='y')

ax.legend(loc='best') #设置位置

ax.grid()#添加网格线

plt.show()

#y2=cos(2*pi*x)

y2=np.cos(2*np.pi*x)

print(y2)

[ 1.00000000e+00 9.51056516e-01 8.09016994e-01 5.87785252e-01

3.09016994e-01 6.12323400e-17 -3.09016994e-01 -5.87785252e-01

-8.09016994e-01 -9.51056516e-01 -1.00000000e+00 -9.51056516e-01

-8.09016994e-01 -5.87785252e-01 -3.09016994e-01 -1.83697020e-16

3.09016994e-01 5.87785252e-01 8.09016994e-01 9.51056516e-01]

fig,ax=plt.subplots()

ax.plot(x,y,'b--*',label='sin')

ax.plot(x,y2,'r--o',label='cos')

ax.legend(loc='best') #自动显示

#ax.legend(loc='upper right') #靠右侧显示

ax.set(title='sin&cos')

plt.show()

————————————————

原文链接:https://blog.csdn.net/ZZQHELLO2018/article/details/125616849