首页 > 解决方案 > plotly:如何在窗口中制作独立的情节?

问题描述

有什么办法可以像matplotlib一样使用plotly,即让情节出现在弹出窗口中?例如,是否有一个简单的等价物

plt.plot([1,2,3], [2, 3, 2.5])
plt.show()

我尝试了各种功能,但它们似乎都创建了一个 html 文件或一个图像文件。

标签: pythonmatplotlibplotly

解决方案


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)

enter image description here


推荐阅读