使用如下代碼:
from io import BytesIO
import base64
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(100)
y = np.sin(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
# 寫入內(nèi)存
save_file = BytesIo()
plt.savefig(save_file, format='png')
# 轉(zhuǎn)換base64并以u(píng)tf8格式輸出
save_file_base64 = base64.b64encode(save_file.getvalue()).decode('utf8')
這樣直接輸出save_file_base64即是html中可用的數(shù)據(jù)了。