plotly:如何在窗口中制作独立图? [英] plotly: how to make a standalone plot in a window?

查看:521
本文介绍了plotly:如何在窗口中制作独立图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法可以像matplotlib一样使用plotly,也就是使绘图显示在弹出窗口中?例如,是否有一个简单的等价物

Is there any way to use plotly just like matplotlib, that is, making the plot appear in a pop up window? Eg, is there an simple equivalent of

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

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

I've tried various functions, but all of them seem to either create an html file or an image file.

推荐答案

在系统映像查看器中显示

您可以在默认的系统图像查看器中打开由plotly创建的图像,这是一种独立的窗口.

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.

另一种选择是创建一个Web浏览器窗口,以显示plotly生成的html页面.为此,您需要使用允许创建浏览器的GUI工具箱. PyQt5就是一个.

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.

因此,以下代码使用浏览器创建了一个PyQt5窗口,并加载了在其中内部绘制的html页面,供您与之交互. (此版本已在pyqt 5.9上进行了测试,可能无法在较旧的版本上使用.)

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)

这篇关于plotly:如何在窗口中制作独立图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆