Static Image Export in Python

Plotly allows you to save static images of your plots. Save the image to your local computer, or embed it inside your Jupyter notebooks as a static image.


New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Interactive vs Static Export

Plotly figures are interactive when viewed in a web browser: you can hover over data points, pan and zoom axes, and show and hide traces by clicking or double-clicking on the legend. You can export figures either to static image file formats like PNG, JEPG, SVG or PDF or you can export them to HTML files which can be opened in a browser and remain interactive. This page explains how to do the former.

Install Dependencies

Static image generation requires the orca commandline utility and the psutil and requests Python libraries. There are 3 general approach to installing these dependencies.

conda

Using the conda package manager, you can install these dependencies in a single command:

$ conda install -c plotly plotly-orca==1.2.1 psutil requests

Note: Even if you do not want to use conda to manage your Python dependencies, it is still useful as a cross platform tool for managing native libraries and command-line utilities (e.g. git, wget, graphviz, boost, gcc, nodejs, cairo, etc.). For this use-case, start with Miniconda (~60MB) and tell the installer to add itself to your system PATH. Then run conda install plotly-orca==1.2.1 and the orca executable will be available system wide.

npm + pip

You can use the npm package manager to install orca (and its electron dependency), and then use pip to install psutil:

$ npm install -g electron@1.8.4 orca
$ pip install psutil requests
Standalone Binaries + pip

If you are unable to install conda or npm, you can install orca as a precompiled binary for your operating system. Follow the instructions in the orca README to install orca and add it to your system PATH. Then use pip to install psutil.

$ pip install psutil requests

Create a Figure

Now let's create a simple scatter plot with 100 random points of variying color and size.

In [1]:
import plotly.graph_objects as go
import numpy as np
np.random.seed(1)

N = 100
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
sz = np.random.rand(N) * 30

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=x,
    y=y,
    mode="markers",
    marker=go.scatter.Marker(
        size=sz,
        color=colors,
        opacity=0.6,
        colorscale="Viridis"
    )
))

fig.show()

Write Image File

The plotly.io.write_image function is used to write an image to a file or file-like python object. You can also use the .write_image graph object figure method.

Let's first create an output directory to store our images

In [2]:
import os

if not os.path.exists("images"):
    os.mkdir("images")

If you are running this notebook live, click to open the output directory so you can examine the images as they are written.

Raster Formats: PNG, JPEG, and WebP

Orca can output figures to several raster image formats including PNG, ...

In [3]:
fig.write_image("images/fig1.png")

JPEG, ...

In [4]:
fig.write_image("images/fig1.jpeg")

and WebP

In [5]:
fig.write_image("images/fig1.webp")

Vector Formats: SVG and PDF...

Orca can also output figures in several vector formats including SVG, ...

In [6]:
fig.write_image("images/fig1.svg")

PDF, ...

In [7]:
fig.write_image("images/fig1.pdf")

and EPS (requires the poppler library)

In [8]:
fig.write_image("images/fig1.eps")

Note: It is important to note that any figures containing WebGL traces (i.e. of type scattergl, heatmapgl, contourgl, scatter3d, surface, mesh3d, scatterpolargl, cone, streamtube, splom, or parcoords) that are exported in a vector format will include encapsulated rasters, instead of vectors, for some parts of the image.

Install orca on Google Colab

!pip install plotly>=4.7.1
!wget https://github.com/plotly/orca/releases/download/v1.2.1/orca-1.2.1-x86_64.AppImage -O /usr/local/bin/orca
!chmod +x /usr/local/bin/orca
!apt-get install xvfb libgtk2.0-0 libgconf-2-4

Once this is done you can use this code to make, show and export a figure:

import plotly.graph_objects as go
fig = go.Figure( go.Scatter(x=[1,2,3], y=[1,3,2] ) )
fig.write_image("fig1.svg")
fig.write_image("fig1.png")

The files can then be downloaded with:

from google.colab import files
files.download('fig1.svg')
files.download('fig1.png')

Get Image as Bytes

The plotly.io.to_image function is used to return an image as a bytes object. You can also use the .to_image graph object figure method.

Let convert the figure to a PNG bytes object...

In [9]:
img_bytes = fig.to_image(format="png")

and then display the first 20 bytes.

In [10]:
img_bytes[:20]
Out[10]:
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x02\xbc'

Display Bytes as Image Using IPython.display.Image

A bytes object representing a PNG image can be displayed directly in the notebook using the IPython.display.Image class. This also works in the Qt Console for Jupyter!

In [11]:
from IPython.display import Image
Image(img_bytes)
Out[11]:

Change Image Dimensions and Scale

In addition to the image format, the to_image and write_image functions provide arguments to specify the image width and height in logical pixels. They also provide a scale parameter that can be used to increase (scale > 1) or decrease (scale < 1) the physical resolution of the resulting image.

In [12]:
img_bytes = fig.to_image(format="png", width=600, height=350, scale=2)
Image(img_bytes)
Out[12]:

Summary

In summary, to export high-quality static images from plotly.py, all you need to do is install orca, psutil, and requests and then use the plotly.io.write_image and plotly.io.to_image functions (or the .write_image and .to_image graph object figure methods).

If you want to know more about how the orca integration works, or if you need to troubleshoot an issue, please check out the Orca Management section.

What About Dash?

Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash at https://dash.plot.ly/installation.

Everywhere in this page that you see fig.show(), you can display the same figure in a Dash application by passing it to the figure argument of the Graph component from the built-in dash_core_components package like this:

import plotly.graph_objects as go # or plotly.express as px
fig = go.Figure() # or any Plotly Express function e.g. px.bar(...)
# fig.add_trace( ... )
# fig.update_layout( ... )

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

app.run_server(debug=True, use_reloader=False)  # Turn off reloader if inside Jupyter