介绍
- Matplotlib 是基于 Python 的开源项目,旨在为 Python 提供一个数据绘图包。
绘图原理
- 在 Matplotlib 中,整个图像为一个 Figure 对象,在 Figure 对象中可以包含一个或多个 Axes 对象:
# 理解matplot的画图原理
def matplotlib_theory():
# 创建Figure对象
fig = Figure()
# 将figure放入画布对象,FigureCanvas对象 , 即 canvas 对象,代表真正进行绘图的后端(backend)
canvas = FigureCanvas(fig)
# 在figure对象中添加Axes对象
# 在 Matplotlib 中,整个图像为一个 Figure 对象,在 Figure 对象中可以包含一个或多个 Axes 对象:
# figure的百分比,从figure的(left,bottom)的位置开始绘制, 宽高是figure的(width, height) fig.add_axes([left, bottom, width, height])
ax1 = fig.add_axes([0.1, 0.6, 0.3, 0.3])
ax2 = fig.add_axes([0.6, 0.6, 0.3, 0.3])
ax3 = fig.add_axes([0.1, 0.1, 0.3, 0.3])
ax4 = fig.add_axes([0.6, 0.1, 0.3, 0.3])
# 画直线
line1 = ax1.plot([0, 1], [0, 1])
ax1.set_title("a straight line ")
ax1.set_xlabel("x label")
ax1.set_ylabel("y label")
line2 = ax2.plot([2, 5], [2, 5])
ax2.set_title("a straight line ")
ax2.set_xlabel("x")
ax2.set_ylabel("y")
#将整个画布保存为图片
canvas.print_figure('figure.jpg')
绘图分解
- 设置绘图背景样式 和 常见基本操作
#--设置背景样式
#可以使用命令:plt.style.available查看支持的样式
plt.style.use('bmh') # 将背景颜色改为bmh
# --绘制二次曲线(常见基础操作)
x = np.linspace(0,5,10)
y = x ** 2
plt.plot(x, y, 'r--') #画点 设置颜色和线型
plt.title('title') #标题
plt.xlabel('x') #坐标轴x
plt.ylabel('y') #坐标轴y
plt.text(2, 10, 'y=x*x') #文本
plt.annotate('this is annotate', xy=(3.5, 12), xytext=(2,16), arrowprops={'headwidth':10, 'facecolor':'r'}) #注解
plt.legend(['y=x^2']) #图例
plt.grid(linestyle='--', linewidth=1) #网格
#范围
plt.xlim(left=0, right=5)
plt.ylim(bottom=0, top=25)
- 设置坐标轴显示格式
x = pd.date_range('2020/01/01',periods=30)
y = np.arange(0,30,1)**2
plt.plot(x,y,'r')
plt.gcf().autofmt_xdate()
plt.show()
- 设置双轴
#--双轴 plt.twinx()
x = np.linspace(1, 5, 10)
y = x ** 2
plt.plot(x, y, 'r')
plt.text(3, 10, 'y=x^2')
plt.twinx()
plt.plot(x, np.log(x), 'g')
plt.text(1.5, 0.4, 'y=logx')
- 双图
#--双图
x = np.linspace(1, 5, 10)
y = x ** 2
plt.subplot(1, 2, 1)
plt.plot(x, y, 'r--')
plt.subplot(1, 2, 2)
plt.plot(y, x, 'g*-')
- 嵌入图
#--嵌入图
x = np.linspace(1, 5, 10)
y = x ** 2
fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # insert axes
# 主图
axes1.plot(x, y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')
# 插入的图
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title')
plt.show() #显示
- 显示中文
# 显示中文
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong']
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
plt.plot(x, y, 'r')
plt.title('显示中文标题')
plt.show()
- 绘制动画
# Matplotlib 绘制动画
from matplotlib import animation
from random import randint, random
class Data:
data_count = 32
frames_count = 2
def __init__(self, value):
self.value = value
self.color = (0.5, random(), random()) # rgb
# 造数据
@classmethod
def create(cls):
return [[Data(randint(1, cls.data_count)) for _ in range(cls.data_count)]
for frame_i in range(cls.frames_count)]
#绘制动画:animation.FuncAnimation 函数的回调函数的参数 fi 表示第几帧,注意要调用 axs.cla() 清除上一帧。
def draw_chart():
fig = plt.figure(1, figsize=(16, 9))
axs = fig.add_subplot(111)
axs.set_xticks([])
axs.set_yticks([])
# 生成数据
frames = Data.create()
def animate(fi):
axs.cla() # clear last frame
axs.set_xticks([])
axs.set_yticks([])
return axs.bar(list(range(Data.data_count)), # X
[d.value for d in frames[fi]], # Y
1, # width
color=[d.color for d in frames[fi]] # color
)
# 动画展示
anim = animation.FuncAnimation(fig, animate, frames=len(frames))
plt.show()
版权声明:本文为Mzcc_bbms原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。