gpt4 book ai didi

pyqt - 如何在 PyQt 小部件中渲染 Altair/Vega

转载 作者:行者123 更新时间:2023-12-04 10:35:22 30 4
gpt4 key购买 nike

是否可以让 Altair 或 Vega(-Lite) 渲染到 PyQt 小部件,类似于支持多个后端的 Matplotlib?我知道我可以使用 Qt WebView 小部件来呈现带有 Vega 嵌入的网页,但我想避免必须为此提供服务的开销,即使是在本地也是如此。

最佳答案

使用 Altair 可视化绘图的最佳选择是使用 QWebEngineView,因为 altair what is to create javascript code based on the instructions you set.恕我直言,最好的解决方案是获取图表的 html 并将其设置在 QWebEngineView 中。在下面的示例中,除了启用将图像另存为 svg 或 png 等特性之外,我还展示了如何执行上述操作。

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets

from io import StringIO


class WebEngineView(QtWebEngineWidgets.QWebEngineView):
def __init__(self, parent=None):
super().__init__(parent)
self.page().profile().downloadRequested.connect(self.onDownloadRequested)
self.windows = []

@QtCore.pyqtSlot(QtWebEngineWidgets.QWebEngineDownloadItem)
def onDownloadRequested(self, download):
if (
download.state()
== QtWebEngineWidgets.QWebEngineDownloadItem.DownloadRequested
):
path, _ = QtWidgets.QFileDialog.getSaveFileName(
self, self.tr("Save as"), download.path()
)
if path:
download.setPath(path)
download.accept()

def createWindow(self, type_):
if type_ == QtWebEngineWidgets.QWebEnginePage.WebBrowserTab:
window = QtWidgets.QMainWindow(self)
view = QtWebEngineWidgets.QWebEngineView(window)
window.resize(640, 480)
window.setCentralWidget(view)
window.show()
return view

def updateChart(self, chart, **kwargs):
output = StringIO()
chart.save(output, "html", **kwargs)
self.setHtml(output.getvalue())


if __name__ == "__main__":
import sys

import altair as alt
from vega_datasets import data

app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QMainWindow()

cars = data.cars()

chart = (
alt.Chart(cars)
.mark_bar()
.encode(x=alt.X("Miles_per_Gallon", bin=True), y="count()",)
.properties(title="A bar chart")
.configure_title(anchor="start")
)

view = WebEngineView()
view.updateChart(chart)
w.setCentralWidget(view)
w.resize(640, 480)
w.show()
sys.exit(app.exec_())

关于pyqt - 如何在 PyQt 小部件中渲染 Altair/Vega,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60210035/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com