如何将情节表达图保存到 html 或静态图像文件中?如何将、静态、图像文件、情节

2023-09-06 06:58:18 作者:Amnesia(失忆)

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

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

解决方案 视频批量剪辑 如何在视频里添加静态图片作为背景

更新答案:

使用较新版本的 plotly,

文件夹中显示的文件:

从这里您可以在任何浏览器或任何其他您想要的方式中打开文件.

这是使用 Notepad++

显示的内容

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

静态图片的旧答案:

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

如果您愿意,请查看 Static Image Export in Pythonhtml.

我喜欢使用包括 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 export 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.