python - plotly:如何在窗口中制作独立的情节?
问题描述
有什么办法可以像matplotlib一样使用plotly,即让情节出现在弹出窗口中?例如,是否有一个简单的等价物
plt.plot([1,2,3], [2, 3, 2.5])
plt.show()
我尝试了各种功能,但它们似乎都创建了一个 html 文件或一个图像文件。
解决方案
Show in system image viewer
You can open the image that is created by plotly in your default system image viewer, which is kind of a standalone window.
import numpy as np
import plotly.graph_objs as go
fig = go.Figure()
fig.add_scatter(x=np.random.rand(100), y=np.random.rand(100), mode='markers',
marker={'size': 30, 'color': np.random.rand(100), 'opacity': 0.6,
'colorscale': 'Viridis'});
def show(fig):
import io
import plotly.io as pio
from PIL import Image
buf = io.BytesIO()
pio.write_image(fig, buf)
img = Image.open(buf)
img.show()
show(fig)
The drawback of this is of course that you don't have any interaction.
Create browser window
The alternative can be to create a webbrowser window to show the html page generated by plotly. To this end you need to make use of a GUI toolkit that allows to create a browser. PyQt5 would be one.
So the following creates a PyQt5 window with a browser and loads the html page created by plotly inside of it for you to interact with. (This is tested with pyqt 5.9, it may not work with much older versions.)
import numpy as np
import plotly.graph_objs as go
fig = go.Figure()
fig.add_scatter(x=np.random.rand(100), y=np.random.rand(100), mode='markers',
marker={'size': 30, 'color': np.random.rand(100), 'opacity': 0.6,
'colorscale': 'Viridis'});
def show_in_window(fig):
import sys, os
import plotly.offline
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication
plotly.offline.plot(fig, filename='name.html', auto_open=False)
app = QApplication(sys.argv)
web = QWebEngineView()
file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "name.html"))
web.load(QUrl.fromLocalFile(file_path))
web.show()
sys.exit(app.exec_())
show_in_window(fig)
推荐阅读
- coroutine - 什么证明使用协程而不是子例程是合理的?
- javascript - 如何在不更改设置的情况下在 glidejs 中居中项目
- mysql - 子字符串中的一些字符串
- javascript - Vue + axios 在值更改时不更新 DOM
- angular - 一个组件的带有角度的自定义布局
- regex - 有没有更简单的方法来查找字符串的正则表达式?
- vaadin - 默认映射和附加 servlet
- javascript - 处理 nodejs 承诺链中传入的参数
- flutter - 在 Pushing FlutterViewController 时,出现 iOS 启动/启动屏幕
- sql - 删除/删除具有空值的列