import matplotlib.pyplot as plt
pyplot模块包含了常用的Matplotlib API函数
1.figure
Matplotlib的图像均位于figure对象中,创建figure对象
fig = plt.figure()
2.Subplot
fig.add_subplot(a,b,c)
返回的是AxesSubplot对象
a,b表示将fig分割成 a*b 的区域
c表示当前选中要操作的区域
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)
import numpy as np
random_arr = np.random.randn(100)
plt.plot(random_arr)
plt.show()
结合scipy函数(plot,hist)
import scipy as sp
from scipy import stats
x = np.linspace(-5,15,50)
#绘制高斯分布
plt.plot(x,sp.stats.norm.pdf(x=x,loc=5,scale=2))
#绘制高斯分布直方图
plt.hist(sp.stats.norm.rvs(loc=5, scale=2, size=200), bins=50, normed=True, color='red', alpha=0.5)
plt.show()
绘制散点图 scatter
x = np.arange(50)
y = x+5*np.random.rand(50)
plt.scatter(x,y)
柱状图 bar
x = np.arange(5)
y1,y2 = np.random.randint(1,25,size = (2,5))
width = 0.25
ax = plt.subplot(1,1,1)
ax.bar(x,y1,width,color='r')
ax.bar(x+width,y2,width,color='g')
ax.set_xticks(x+width)
ax.set_xticklabels(['a', 'b', 'c', 'd', 'e'])
plt.show()
矩阵绘图
# 矩阵绘图
m = np.random.rand(10,10)
print(m)
plt.imshow(m, interpolation='nearest', cmap=plt.cm.ocean)
plt.colorbar()
plt.show()
3.plt.subplots()
同时返回新创建的figure和subplot对象数组‘
fig,subplot_arr = plt.subplot(2,2)
fig,arr = plt.subplot(2,2)
arr[0,0].hist(np.random.randn(100),bins = 10,color='b',alpha=0.3)
arr[0,1].hist(np.random.randn(100),bins = 10,color='b',alpha=0.3)
plt.show()
颜色、标签、线性
fig, axes = plt.subplots(2)
axes[0].plot(np.random.randint(0, 100, 50), 'ro--')
# 等价
axes[1].plot(np.random.randint(0, 100, 50), color='r', linestyle='dashed', marker='o')
刻度、标签、图例
fig, ax = plt.subplots(1)
ax.plot(np.random.randn(1000).cumsum(), label='line0')
# 设置刻度
#plt.xlim([0,500])
ax.set_xlim([0, 800])
# 设置显示的刻度
#plt.xticks([0,500])
ax.set_xticks(range(0,500,100))
# # 设置刻度标签
# ax.set_yticklabels(['Jan', 'Feb', 'Mar'])
# 设置坐标轴标签
ax.set_xlabel('Number')
ax.set_ylabel('Month')
# 设置标题
ax.set_title('Example')
# 图例
ax.plot(np.random.randn(1000).cumsum(), label='line1')
ax.plot(np.random.randn(1000).cumsum(), label='line2')
ax.legend()
ax.legend(loc='best')
plt.legend()