Plotly: How to save plotly express plot into a html or static image file?

£可爱£侵袭症+ 提交于 2021-02-07 09:02:33

问题


I love plotly and recently plotly.express. However, I feel saving the figure is pretty tricky.

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

Thanks


回答1:


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("<filename>") and `.pdf` are all available,

Filetypes such as .png, .jpeg and .pdf are all 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.




回答2:


Exporting a static image in Python

Short story: pip install kaleido, then fig.write_image(<output_filename>).

I stumbled on this as I am also looking for ways on how to export plotly figures to static images. I realized that installing orca and making it work is not so easy, but good thing is they actually made this package called kaleido that is easier to install. Found it from these links:

  • https://github.com/plotly/orca/issues/194
  • https://plotly.com/python/static-image-export/


来源:https://stackoverflow.com/questions/59815797/plotly-how-to-save-plotly-express-plot-into-a-html-or-static-image-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!