html嵌入图片编码,matplotlib绘图嵌入html 文件

实现思路

html可以以base64代码的形式内嵌图片。具体形式为 

plt.ylabel(u"纵轴的数据")

plt.legend()  # 让图例生效

# figure 保存为二进制文件

buffer = BytesIO()

plt.savefig(buffer)

plot_data = buffer.getvalue()

#plt.show()  # 显示绘制出的图

# 图像数据转化为 HTML 格式

imb = base64.b64encode(plot_data)

ims = imb.decode()

imd = "data:image/png;base64,"+ims

test_im = """

Demo Figure

  """ + """ %s""" % imd

# lxml 库的 etree 解析字符串为 html 代码,并写入文件

html = etree.HTML(test_im)

tree = etree.ElementTree(html)

tree.write('demo.html')

# 最后使用默认浏览器打开 html 文件

webbrowser.open('demo.html', new=1)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在PyQt5中嵌入Matplotlib可以通过以下步骤实现: 1. 导入所需的模块: ```python from PyQt5 import QtWidgets from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure ``` 2. 创建一个继承自QtWidgets.QMainWindow的主窗口类: ```python class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("PyQt5嵌入Matplotlib") self.setGeometry(100, 100, 800, 600) ``` 3. 在主窗口类的初始化方法中创建一个Matplotlib的画布对象,并将其添加到主窗口中: ```python class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("PyQt5嵌入Matplotlib") self.setGeometry(100, 100, 800, 600) # 创建Matplotlib的画布对象 self.canvas = FigureCanvas(Figure()) # 将画布添加到主窗口中 self.setCentralWidget(self.canvas) ``` 4. 在主窗口类中添加一个绘图方法,用于在Matplotlib画布上绘制图形: ```python class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("PyQt5嵌入Matplotlib") self.setGeometry(100, 100, 800, 600) # 创建Matplotlib的画布对象 self.canvas = FigureCanvas(Figure()) # 将画布添加到主窗口中 self.setCentralWidget(self.canvas) def plot(self): # 在画布上绘制图形 fig = self.canvas.figure ax = fig.add_subplot(111) ax.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25]) # 更新画布 self.canvas.draw() ``` 5. 在主窗口类中重写showEvent方法,用于在窗口显示时调用绘图方法: ```python class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("PyQt5嵌入Matplotlib") self.setGeometry(100, 100, 800, 600) # 创建Matplotlib的画布对象 self.canvas = FigureCanvas(Figure()) # 将画布添加到主窗口中 self.setCentralWidget(self.canvas) def plot(self): # 在画布上绘制图形 fig = self.canvas.figure ax = fig.add_subplot(111) ax.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25]) # 更新画布 self.canvas.draw() def showEvent(self, event): # 在窗口显示时调用绘图方法 self.plot() ``` 6. 创建一个应用程序对象,并显示主窗口: ```python import sys app = QtWidgets.QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) ``` 这样就可以在PyQt5的UI中嵌入Matplotlib了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值