簡體   English   中英

如何將情節表達圖保存到 html 或靜態圖像文件中?

[英]How to save plotly express plot into a html or static image file?

但是,我覺得用 plotly.express 保存這個數字非常棘手。

如何將 plotly.express 或 plotly plot 保存到單獨的 html 或靜態圖像文件中? 任何人都可以幫忙嗎?

更新的答案:

使用較新版本的 plotly, Python 中的靜態圖像導出變得輕而易舉。 只需確保使用以下命令安裝 kaleido:

pip install -U kaleido

或者,對於 Anaconda:

conda install -c conda-forge python-kaleido

然后運行

fig.write_image("yourfile.png") 

.jpeg.pdf等文件類型也是可用的選項。

生成一個單獨的 html 文件仍然很容易:

只需使用plotly.offline.plot(fig, filename='C:/plotlyplots/canada_offline.html')

這將為您提供所需文件夾中名為lifeExp的 plotly express 條形圖的 html 文件。 記住import plotly而不僅僅是import plotly.express as px

完整代碼:

# 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')

陰謀:

在此處輸入圖像描述

文件中出現的文件:

在此處輸入圖像描述

從這里您可以在任何瀏覽器或任何其他您想要的方式中打開文件。

這是使用Notepad++顯示的內容

在此處輸入圖像描述

如果您不介意一些體力勞動,您可以使用工具欄保存.png版本:

在此處輸入圖像描述


靜態圖像的舊答案:

自動生成靜態圖像有點棘手。

如果您更喜歡 html,請查看Python 中的靜態圖像導出

我喜歡使用包括orca在內的可以生成各種圖像文件的方法。 除了使用與node.js一起安裝的npm之外,我還沒有找到任何其他方法來安裝它:

npm install -g electron@1.8.4 orca

pip install psutil requests

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

在 Python 中導出靜態圖像

短篇小說: pip install kaleido ,然后fig.write_image(<output_filename>)

我偶然發現了這一點,因為我也在尋找如何將圖形導出到靜態圖像的方法。 我意識到安裝 orca 並使其工作並不是那么容易,但好在他們實際上制作了這個名為kaleido的軟件包,它更易於安裝。 從這些鏈接中找到它:

不知何故,上述 .html 文件的解決方案不起作用,但我發現

from pathlib import Path

with Path("myfile.html").open("w") as f:
    f.write(fig.to_html())

工作得很好。

添加到 @vestland 關於保存到 HTML 的答案中,根據文檔的另一種方法是:

import plotly.express as px

# a sample scatter plot figure created
fig = px.scatter(x=range(10), y=range(10))
fig.write_html("paht/to/file.html")

您可以在此處進一步了解它(控制 HTML 文件的大小): Python 中的交互式 HTML 導出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM