matplotlib是基于Python语言的开源项目,旨在为Python提供一个数据绘图包。我将在这篇文章中介绍matplotlib API的核心对象,并介绍如何使用这些对象来实现绘图。实际上,matplotlib的对象体系严谨而有趣,为使用者提供了巨大的发挥空间。用户在熟悉了核心对象之后,可以轻易的定制图像。matplpotlib是基于numpy的,所以需要先安装numpy
pip install numpy #安装numpy
pip install matplotlib #安装matplotlib
pip show matplotlib #查看matplotlib的信息
matplotlib使用numpy进行数组运算,并调用一系列其他的Python库来实现硬件交互。matplotlib的核心是一套由对象构成的绘图API。
- 最简单的显示一条直线
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y = 2*x+1
plt.figure()
plt.plot(x,y)
plt.show()
你将看到
- 同时显示两条线
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y1)
plt.plot(x,y2,color='red',linewidth=1.0,linestyle='--')
plt.show()
你将看到
- 坐标轴取值范围
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y1)
plt.plot(x,y2,color='red',linewidth=1.0,linestyle='--')
plt.xlim((-1,2)) #x轴范围
plt.ylim((-2,3)) #y轴范围
plt.show()
你将看到
- 描述 xlabel ylabel
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y1)
plt.plot(x,y2,color='red',linewidth=1.0,linestyle='--')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
你将看到
- 更换标签
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y1)
plt.plot(x,y2,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,1,3,],['bad','really bad','good','really good',])
plt.show()
你将看到
- 修改坐标轴的位置
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y1)
plt.plot(x,y2,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,1,3,],[r'$bad$','really bad','good','really good',])
ax = plt.gca()
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轴绑定在y轴0处
ax.spines['left'].set_position(('data',0)) #y轴绑定在x轴0处
plt.show()
你将看到
- 图例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y1,label='y1')
plt.plot(x,y2,color='red',linewidth=1.0,linestyle='--',label='y2')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('X')
plt.ylabel('Y')
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
plt.yticks(np.linspace(-1,3,5))
ax = plt.gca()
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轴绑定在y轴0处
ax.spines['left'].set_position(('data',0)) #y轴绑定在x轴0处
plt.legend(loc='best')
plt.show()
你将看到
- 标注
在图片中添加注解
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y1,label='y1')
# plt.plot(x,y2,color='red',linewidth=1.0,linestyle='--',label='y2')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('X')
plt.ylabel('Y')
new_ticks = np.linspace(-1,2,5)
ax = plt.gca()
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轴绑定在y轴0处
ax.spines['left'].set_position(('data',0)) #y轴绑定在x轴0处
plt.legend(loc='best')
x0=0.5
y0=2*x0+1
plt.scatter(x0,y0,c = 'r',marker = 'o')
plt.plot([x0,x0],[0,y0],'k--',lw=2.5) #(x0,0)与(x0,y0)之间的虚线连接
#标注
#方法1
plt.annotate(r'$(0.5,2)$',xy=(x0,y0))
#方法2
plt.text(1,2,u'(0.5,2)')
plt.show()
你将看到
- 坐标轴刻度调整
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x,y1,label='y1',lw=1)
# plt.plot(x,y2,color='red',linewidth=1.0,linestyle='--',label='y2')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('X')
plt.ylabel('Y')
new_ticks = np.linspace(-1,2,5)
ax = plt.gca()
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轴绑定在y轴0处
ax.spines['left'].set_position(('data',0)) #y轴绑定在x轴0处
plt.legend(loc='best')
plt.xticks(new_ticks)
plt.yticks(np.linspace(-1,3,5))
for label in ax.get_xticklabels()+ax.get_yticklabels():
label.set_fontsize(12) #设置字体
label.set_bbox(dict(facecolor='white',edgecolor='None',alpha=0.8)) #alpha表示透明度
plt.show()
你将看到
- 散点数据
import matplotlib.pyplot as plt
import numpy as np
n = 1204
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
T = np.arctan2(Y,X)
plt.scatter(X,Y,s=75,c=T,alpha=0.5)
plt.xlim((-1,1))
plt.ylim((-1,1))
plt.xticks(())
plt.yticks(())
plt.show()
你将看到
- 条形图(bar)
import matplotlib.pyplot as plt
import numpy as np
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='r',edgecolor='w')
plt.bar(X,-Y2,facecolor='b',edgecolor='w')
for x,y in zip(X,Y1):
plt.text(x-0.1,y+0.05,'%.2f'%y,ha='center',va='bottom') #居中对齐
for x,y in zip(X,Y2):
plt.text(x+0.1,-y-0.05,'-%.2f'%y,ha='center',va='top')
plt.xlim((-0.5,n))
plt.ylim((-2,2))
plt.xticks(())
plt.yticks(())
plt.show()
你将看到
- 等高线
import matplotlib.pyplot as plt
import numpy as np
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.75,cmap=plt.cm.hot)
C = plt.contour(X,Y,f(X,Y),8,colors='black',lw=0.5) #等高线分多少部分
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()
你将看到
- 3D
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
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是高度值
Z = np.sin(R)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow')) #stride表示跨度
# ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
# ax.set_zlim(-2,2)
plt.show()
你将看到
- 多个显示
第1种
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
plt.subplot(2,2,1)
plt.plot([0,1],[0,1])
plt.subplot(2,2,2)
plt.plot([0,1],[0,2])
plt.subplot(2,2,3)
plt.plot([0,1],[0,3])
plt.subplot(2,2,4)
plt.plot([0,1],[0,4])
plt.show()
第2种
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)
plt.plot([0,1],[0,2])
plt.subplot(2,3,5)
plt.plot([0,1],[0,3])
plt.subplot(2,3,6)
plt.plot([0,1],[0,4])
plt.show()
参考资料:https://morvanzhou.github.io/tutorials/data-manipulation/plt/