Matplotlib介绍
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
X=np.linspace(0,2*np.pi,100)
Y=np.sin(X)
Y1=np.cos(X)
plt.plot(X,Y)
plt.plot(X,Y1)
plt.show()
plt.subplot(211)
plt.plot(X,Y)
plt.subplot(212)
plt.plot(X,np.cos(X),color = "r")
柱状图
data = [5,25,50,20]
plt.bar(range(len(data)),data)
plt.bar(range(len(data)),data)
data=[[5,25,50,20],[4,23,51,17],[6,22,52,9]]
X=np.arange(4)
plt.bar(X+0.00,data[0],color = "b",width = 0.25,label = 'A')
plt.bar(X+0.25,data[1],color = "g",width = 0.25,label = 'B')
plt.bar(X+0.50,data[2],color = "r",width = 0.25,label = 'C')
plt.legend()
plt.bar(X,data[0],color = "b",width = 0.25,label = 'A')
plt.bar(X,data[1],color = "g",width = 0.25,bottom=data[0],label = 'B')
plt.bar(X,data[2],color = "r",width = 0.25,bottom=data[0]+np.array(data[1]),label = 'C')
散点图
N=50
X=np.random.rand(N)
Y=np.random.rand(N)
colors = np.random.randn(N)
area = np.pi*(20*np.random.rand(N))**2
plt.scatter(X,Y,c=colors,alpha=0.5,s=area )
直方图
a=np.random.randn(10000)
plt.hist(a,bins = 200)
plt.ylim(0,150)
plt.title('A')
箱型图
x=np.random.randint(20,100,size=(10,3))
plt.boxplot(x)
plt.ylim(0,120)
plt.xticks([1,2,3],['A','B','C'])
颜色
plt.subplots(facecolor="teal")
文字
plt.xlabel('Group')
plt.ylabel('Number')
plt.text(0.5,38,"Text")
Subplots绘制子图
将画布划分成均等的几个部分,分别添加元素,绘制图像
np.random.seed(90)
n_bins=10
x=np.random.randn(1000,3)
fig,axes = plt.subplots(nrows=2,ncols=2,facecolor='darkslategray')
ax0,ax1,ax2,ax3=axes.flatten()
colors=['red','tan','lime']
ax0.hist(x,n_bins,normed=1,histtype='bar',color=colors,label=colors)
ax0.legend(prop={
'size':10})
ax0.set_title('bars with legend')
ax1.hist(x,n_bins,normed=1,histtype='bar',stacked=True)
ax1.set_title('stacked bar')
ax2.hist(x,n_bins,histtype='step',stacked=True,fill=False)
ax2.set_title('stack step(unfilled)')
x_multi =[np.random.randn(n) for n in [10000,5000,2000]]
ax3.hist(x_multi,n_bins,histtype='bar')
ax3.set_title('different sample sizes')
fig.tight_layout()
共享x轴、y轴
np.random.rand(4,3,2)
np.random.rand(1,3,2) 相当于 np.random.rand(3,2)
np.random.seed(90)
N_points=100000
n_bins =20
a=np.random.randn(N_points)
b=1.4*np.random.randn(100000)+5
fig,axs = plt.subplots(1,2,sharey=True,tight_layout=True)
axs[0].hist(a,bins=n_bins)
axs[1].hist(b,bins=n_bins)