How to save plotly express plot into a html or static image file?
Asked Answered
C

7

51

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?

Contradictory answered 20/1, 2020 at 0:53 Comment(0)
B
8

Adding to @vestland 's answer about saving to HTML, another way to do it according to the documentation would be:

import plotly.express as px

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

You can read about it further (controlling size of the HTML file) here: Interactive HTML Export in Python

Blackburn answered 12/7, 2022 at 9:15 Comment(0)
M
65

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:

enter image description here

File as it appears in the foler:

enter image description here

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++

enter image description here

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

enter image description here


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 [email protected] 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.

Misestimate answered 20/1, 2020 at 8:9 Comment(6)
Thank vestland. That is awesome!!! I appreciate it. One more question, if I like to include the plot into powerpoint, is it possible that I could still have the animation like plotly is designed for? For example, using animation_frame='year', to change the plot from different years. ThanksContradictory
Thanks vestland. I just posted a new question.Contradictory
@Contradictory Happy to help! I'm no sure if there's a direct way to do that. I'd suggest you raise that as a new question. I'd like to know the answer to that myself!Misestimate
Great answer @Misestimate . For those who like to save a png file, saving as html and opening this html in the browser gives the option "Download plot as png" (click the photo camera icon in the Plotly menu on the top).Rudd
Every time I click the snapshot button in the toolbar, it just saves a blank white image. Do you know why that might be ?Vhf
Although you get a pdf or an svg extension, zooming into the save images is not crisp.Columbarium
B
8

Adding to @vestland 's answer about saving to HTML, another way to do it according to the documentation would be:

import plotly.express as px

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

You can read about it further (controlling size of the HTML file) here: Interactive HTML Export in Python

Blackburn answered 12/7, 2022 at 9:15 Comment(0)
M
5

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:

Minnich answered 18/11, 2020 at 4:51 Comment(1)
thanks rjd, that is awesome to know. i appreciate it.Contradictory
A
5

Somehow the above solution for .html files did not work, but I found that

from pathlib import Path

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

worked just fine.

Allembracing answered 11/7, 2022 at 8:22 Comment(0)
C
2

I was unable to get kaleido to work and had issues installing npm package orca so I just used playwright to open the plotly generated html and take a screenshot.


import plotly.express as px
import asyncio
import os
from playwright.async_api import async_playwright, Browser

async def make_chart() -> None:
fig = px.scatter(x=range(10), y=range(10))
html_file = os.path.abspath("path/to/file.html")
# Write chart to html file
fig.write_html(html_file)

# Open the html with playwright
# may have to run `playwright install` to download chromium
async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.goto(html_file)
        # Take Screenshot
        await page.screenshot(path="plot.png", full_page=True)

if __name__ == "__main__":
    asyncio.run(make_chart())
Chamber answered 9/1 at 16:28 Comment(0)
L
0

If you want to make sure your notebook

  • Is distributable with its images
  • Works offline
  • Is convertable to formats like PDFs
  • Can be attached as a file
  • Can be read by generic tools that use HTML as input

...you can also set the Plotly itself to ensure every generated image is static, either SVG or PNG, and then embedded in the notebook itself. This is the opposite of Plotly interactive charts. This will also allow you to use HTML generated from notebook elsewhere (documentation) or make it available as a file (PDF for email).

You can set Plotly to offline mode and then force it to use svg output:

         # https://mcmap.net/q/354948/-how-to-plot-using-plotly-with-offline-mode-out-not-in-ipython-notebooks
        from plotly.offline import init_notebook_mode
        init_notebook_mode()

        # https://mcmap.net/q/354949/-exporting-jupyter-notebook-to-pdf-with-offline-plotly-graph-missing-graphs
        import plotly.io as pio
        pio.kaleido.scope.default_format = "svg"

        # https://plotly.com/python/renderers/#overriding-the-default-renderer
        pio.renderers.default = "svg"
        svg_renderer = pio.renderers["svg"] 
        # Have SVGs default 1200 pixel with
        svg_renderer.width = 1200

Now when you run the notebook, all charts are SVGs in the resulting notebook. You can save them individually through web br, or if you are interested multiple images as a whole, you can convert the notebook itself to other formats.

  • HTML with embedded images

  • PDF

Here is how to convert a notebook to a HTML:

    # Latex/Mactex needed 
    # To install on macOS:
    # brew install --cask mactex
    # eval "$(/usr/libexec/path_helper)"
    jupyter nbconvert --to pdf my_notebook.ipynb
Livi answered 7/7, 2023 at 7:30 Comment(0)
E
0

for me fig.write_image('figname.png') did not work for saving the file in png format

However I used plotly.io

import plotly.io as pio

pio.write_image(fig, "figname.png") 
Eutrophic answered 13/11, 2023 at 13:45 Comment(4)
Why did it not work for you? Why does it help to do it in your different way? Are you sure that what you needed to do is also a solution for the, probably different, problem described at the top of this page? Please explain.Buzz
i installed kaleido using both pip and conda again & again i'm getting error to install kaleido even after restarting the kernel. i looked into some tutorial on internet and my method using plotly.io works for meEutrophic
So you do not know why the other solutions did not work for you. You do not know what the differene between your situation and the one in the question is. You do not know what makes your solution work for your situation. You do not know whether it can help for the one in the question. Right? What does then make you think that your solution is a solution for the problem described in the question? I ask because a good solution identifies the problem in the question, proposes a solution, explains the solution and how it works.Buzz
Seems to only work with kaleido==0.1.0.post1Chamber

© 2022 - 2024 — McMap. All rights reserved.