matplotlib的基本使用
初识matplotlib
Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。
它也可以和图形工具包一起使用,如 PyQt 和 wxPython。
引入matplotlib模块
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Series线性数据
#Series线性数据
data = pd.Series(np.random.randn(1000),index=np.arange(1000))
data = data.cumsum() #累加
data.plot()
plt.show()
DataFrame矩阵数据
#DataFrame矩阵数据
data = pd.DataFrame(np.random.randn(1000,4),index=np.arange(1000),columns=list("abcd"))
data = data.cumsum()
data.plot()
plt.show()
scatter散点数据
#scatter散点数据
data = pd.DataFrame(np.random.randn(1000,4),index=np.arange(1000),columns=list("abcd"))
data = data.cumsum()
ax = data.plot.scatter(x='a',y='b',color='DarkBlue',label='class 1')
data.plot.scatter(x='a',y='c',color='DarkGreen',label='class 2',ax=ax)
plt.show()
matplotlib基本用法
x = np.linspace(-1,1,50) #-1到1 平分50份
y = 2*x+1
plt.plot(x,y)
plt.show()
matplotlib的figure图像
#一个figure下放2个图
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
# plt.figure() #第一张
# plt.plot(x,y1)
plt.figure(num=3,figsize=(8,5)) #第二张
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.show()
matplotlib设置坐标轴1
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure(num=3,figsize=(8,5)) #第二张
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.xlim((-1,2)) #x轴范围
plt.ylim((-2,3))
plt.xlabel('X') #x轴的表示
plt.ylabel('Y')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],
[r'$really\ bad$','bad','normal','good','really good'])
plt.show()
matplotlib设置坐标轴2
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure(num=3,figsize=(8,5)) #第二张
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('X')
plt.ylabel('Y')
new_ticks = np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],
['really bad','bad','normal','good','really good'])
ax = plt.gca() #gca='get current axis'
ax.spines['right'].set_color('none') #取消右边框
ax.spines['top'].set_color('none') #取消上边框
ax.xaxis.set_ticks_position('bottom') #左边框设置为x轴
ax.yaxis.set_ticks_position('left') #下边框设置为y轴
ax.spines['bottom'].set_position(('data',0)) #x轴在纵坐标的0上
ax.spines['left'].set_position(('data',0)) #y轴在纵坐标的0上
plt.show()
matplotlib设置legend图例
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure(num=3,figsize=(8,5))
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('X')
plt.ylabel('Y')
new_ticks = np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],
['really bad','bad','normal','good','really good'])
plt.plot(x,y2,label='up') #label:表示图例
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='down')
plt.legend(loc='best') #图例
plt.show()
matplotlib设置annotation标注
x = np.linspace(-3,3,50)
y1 = 2*x+1
plt.figure(num=3,figsize=(8,5)) #第二张
plt.plot(x,y1,color='red',linewidth=1.0)
plt.xlim((-4,4))
plt.ylim((-8,8))
ax = plt.gca()
ax.spines['right'].set_color('none') #取消右边框
ax.spines['top'].set_color('none') #取消上边框
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
x0 = 1
y0 = 2*x0+1
plt.scatter(x0,y0,s=20,color='b') #画点
plt.plot([x0,x0],[y0,0],'k--',lw=2.5) #画线
plt.annotate(r'$2+1=%s$'%y0,xy=(x0,y0),
xycoords='data',xytext=(+30,-30),textcoords='offset points')
plt.show()
scatter散点图
n=1024
X=np.random.normal(0,1,n)
Y=np.random.normal(0,1,n)
T=np.arctan2(Y,X) #设置颜色
plt.scatter(X,Y,s=5,c=T,alpha=1) # s:表示大小,alpha:表示透明度
plt.ylim((-1.5,1.5))
plt.xlim((-1.5,1.5))
plt.show()
bar柱状图
n=12
X=np.arange(n)
Y1=(1-X/float(n))*np.random.uniform(0.5,1.0,n)
Y2=(1-X/float(n))*np.random.uniform(0.5,1.0,n)
plt.bar(X,+Y1,facecolor='#9999ff',edgecolor='white')
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')
for x,y in zip(X,Y1):
plt.text(x+0.04,y+0.05,'%.2f'%y,ha='center',va='bottom') #ha:横向,va:纵向
for x,y in zip(X,Y2):
plt.text(x+0.04,-y-0.05,'%.2f'%y,ha='center',va='top')
plt.ylim((-1.25,1.25))
plt.xlim((-.5,n))
plt.show()
countours等高线图
def f(x,y):
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n=256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y) #底图网格化
plt.contourf(X,Y,f(X,Y),8,alpha=0.95,cmap=plt.cm.hot) #cmap:colormap
C = plt.contour(X,Y,f(X,Y),8,colors='black',linewidth=.5) #设置等高线
plt.clabel(C,inline=True,fontsize=6) #等高线上的数字
plt.show()
3D数据图
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure() #fig 就是一个窗口
ax = Axes3D(fig) #3D的窗口
X = np.arange(-4,4,0.25)
Y = np.arange(-4,4,0.25)
X,Y = np.meshgrid(X,Y)
R = np.sqrt(X**2+Y**2)
Z = np.sin(R)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,
cmap=plt.get_cmap('rainbow'),edgecolor='black')
#rstride横过来的跨度, camp颜色
ax.contourf(X,Y,Z,zdir='z',offset=-4,cmap='rainbow')
ax.set_zlim(-2,2)
plt.show()
次坐标轴
x = np.arange(0,10,0.1)
y1 = 0.05*x**2
y2 = -y1
fig,ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x,y1,'g-')
ax2.plot(x,y2,'b-')
plt.show()