blu*_*ote 2 python matplotlib plotly
有没有什么办法可以像matplotlib一样使用plotly,也就是使绘图显示在弹出窗口中?例如,是否有一个简单的等价物
plt.plot([1,2,3], [2, 3, 2.5])
plt.show()
Run Code Online (Sandbox Code Playgroud)
我尝试了各种功能,但是它们似乎都可以创建html文件或图像文件。
mom*_*mba 10
这应该很简单
import plotly.io as pio
pio.renderers.default = "browser"
Run Code Online (Sandbox Code Playgroud)
来源: https: //plotly.com/python/renderers/
您可以在默认的系统图像查看器中打开通过绘图方式创建的图像,这是一种独立的窗口。
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)
Run Code Online (Sandbox Code Playgroud)
这样的缺点当然是您没有任何交互。
另一种方法是创建一个Web浏览器窗口,以显示plotly生成的html页面。为此,您需要使用允许创建浏览器的GUI工具包。PyQt5将是其中之一。
因此,下面的代码使用浏览器创建了一个PyQt5窗口,并加载了在其中绘制的html页面,以便您与之交互。(此版本已使用pyqt 5.9进行了测试,可能无法与较旧的版本一起使用。)
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)
Run Code Online (Sandbox Code Playgroud)
这是一个根据 ImportanceOfBeingErnest 的答案制作的独立类,以防有人需要
import numpy as np
import plotly.graph_objs as go
import plotly.offline
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'});
import os, sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5 import QtWebEngineWidgets
class PlotlyViewer(QtWebEngineWidgets.QWebEngineView):
def __init__(self, fig, exec=True):
# Create a QApplication instance or use the existing one if it exists
self.app = QApplication.instance() if QApplication.instance() else QApplication(sys.argv)
super().__init__()
self.file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp.html"))
plotly.offline.plot(fig, filename=self.file_path, auto_open=False)
self.load(QUrl.fromLocalFile(self.file_path))
self.setWindowTitle("Plotly Viewer")
self.show()
if exec:
self.app.exec_()
def closeEvent(self, event):
os.remove(self.file_path)
win = PlotlyViewer(fig)
Run Code Online (Sandbox Code Playgroud)