利用python进行数据分析——matplotlib学习笔记(1)

时间:2022-12-21 23:43:41

matplotlib是一个用于创建出版质量图表的绘图包(主要是2D方面);

目的是为python构建一个Matlab式的绘图接口;

pyplot模块包含了常用的matplotlib API函数,其通常的引入约定为 import matplotlib.pyplot as plt

figure, Matplotlib的图像均位于figure对象中,不能通过一个空的Figure绘图;

subplot,figure.add_subplot(a,b,c),a、b表示分割成a*b的区域,c表示当前选中要操作的区域(从1开始编号);

eg:

import matplotlib.pyplot as plt

#创建一个新的figure
fig=plt.figure()

#创建subplot
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax4=fig.add_subplot(2,2,4)
#在subplot上作图
from numpy.random import randn
plt.plot(randn(50),'k--')  #'k--'是一个线性选项,黑虚线
plt.show()
上面那些由fig.add_subplot所返回的对象是AxesSubplot对象
使用以上命令,matplotlib就会在最后一个用过的subplot上进行绘制,如下图所示:

利用python进行数据分析——matplotlib学习笔记(1)
subplot 绘制直方图 hist

import matplotlib.pyplot as plt
from numpy.random import randn

plt.hist(randn(100),bins=20,color='b',alpha=0.3)
plt.show()

参数:np.random.randn(100)生成随机100个数据,bins分成20组,color颜色为blue蓝色,alpha为透明度

利用python进行数据分析——matplotlib学习笔记(1)
subplot 生成散点图 scatter
import matplotlib.pyplot as plt
import numpy as np
plt.scatter(np.arange(30),np.arange(30)+3*randn(30))
plt.show()
plt.subplots()

它可以创建一个新的Figure,并返回一个含有已创建的subplot对象的NumPy数组:

利用python进行数据分析——matplotlib学习笔记(1)

 
可以看出axes是一个数组,可以对其进行索引,像二维数组一样。
 
import matplotlib.pyplot as plt 
import numpy as np

fig,axes=plt.subplots(2,2)
axes[0,0].hist(np.random.randn(100), bins=10, color='b', alpha=0.3)
plt.show()

利用python进行数据分析——matplotlib学习笔记(1)