如何将 plotly 表达图保存到 html 或静态图像文件中? [英] How to save plotly express plot into a html or static image file?

查看:111
本文介绍了如何将 plotly 表达图保存到 html 或静态图像文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

但是,我觉得用 plotly.express 保存图形非常棘手.

如何将 plotly.express 或 plotly plot 保存到单独的 html 或静态图像文件中?有人可以帮忙吗?

解决方案

更新答案:

使用较新版本的 plotly,

显示在文件夹中的文件:

从这里您可以使用任何浏览器或任何其他方式打开文件.

这是使用 Notepad++

显示的内容

如果您不介意一些体力劳动,您可以使用工具栏保存一个 .png 版本:


静态图像的旧答案:

自动生成静态图像有点有点棘手.

如果您更喜欢 html,请查看 Python 中的静态图像导出.

我喜欢使用包括 orca 在内的方法,它可以生成各种图像文件.除了使用与 npm 之外,我还没有找到任何其他方法来安装它>node.js 如果您按顺序完成,则只需运行以下命令即可启动并运行(我使用的是 Windows):

npm install -g electron@1.8.4 orcapip install psutil 请求

然后您可以使用 fig.write_image("C:/plotlyplots/lifeExp.png") 更改上面代码段中的最后一行以生成 .png文件.

However, I feel saving the figure with plotly.express is pretty tricky.

How to save plotly.express or plotly plot into a individual html or static image file? Anyone can help?

解决方案

Updated answer:

With newer versions of plotly, static Image pxport in Python is a breeze. Just make sure to install kaleido using:

pip install -U kaleido

or, for Anaconda:

conda install -c conda-forge python-kaleido

And then run

fig.write_image("yourfile.png") 

Filetypes such as .jpeg and .pdf are also available options.

Producing an individual html file is still very easy:

Just use plotly.offline.plot(fig, filename='C:/plotlyplots/canada_offline.html')

This will give you a html file of a plotly express bar chart with the name lifeExp in a desired folder. Remember import plotly and not only import plotly.express as px.

Complete code:

# imports
import plotly
import plotly.express as px

# data
df = px.data.gapminder().query("continent=='Oceania'")

# plotly express bar chart
fig = px.line(df, x="year", y="lifeExp", color='country')

# html file
plotly.offline.plot(fig, filename='C:/plotlyplots/lifeExp.html')

Plot:

File as it appears in the foler:

From here you can open the file in any browser or any other way you want.

Here's the content as it is displayed using Notepad++

If you don't mind a bit of manual labor, you dan save a .png version using the toolbar:


Old answer for static images:

Producing a static image automatically is a bit mote tricky.

Take a look at Static Image Export in Python if you prefer that to html.

I like to use the approach including orca that can produce a variety of image files. I haven't found any other way to install it other than using npm which is installed with node.js If you get that in order, you only have to go run the following to get it up and running (I'm on Windows):

npm install -g electron@1.8.4 orca

pip install psutil requests

Then you can change the last line in the snippet above with fig.write_image("C:/plotlyplots/lifeExp.png") to produce a .png file.

这篇关于如何将 plotly 表达图保存到 html 或静态图像文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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