10000 Refactor validators by bmaranville · Pull Request #5173 · plotly/plotly.py · GitHub
[go: up one dir, main page]

Skip to content

Refactor validators #5173

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from 1 commit
Commits
Show all changes
82 commits
Select commit Hold shift + click to select a range
8a787b5
Add deprecation notice for orca
LiamConnors Mar 25, 2025
9dd3330
Create static-image-generation-migration.md
LiamConnors Mar 25, 2025
97168bf
Add deprecation notice
LiamConnors Mar 25, 2025
ca80cdd
Add info on changes in Plotly.py 6.1
LiamConnors Mar 25, 2025
7c76ee3
Add draft of Kaleido updates
LiamConnors Mar 25, 2025
2e0b441
Add default settings info
LiamConnors Mar 27, 2025
577329d
Make small updates and add back Orca export settings
LiamConnors Mar 27, 2025
02b31f0
Update link
LiamConnors Mar 31, 2025
3281d99
Update static-image-export.md
LiamConnors Mar 31, 2025
2cbd63c
Update migration guide for Kaleido
LiamConnors Mar 31, 2025
9855b6a
remove orca section
LiamConnors Apr 1, 2025
28e7e19
Update static-image-export.md
LiamConnors Apr 1, 2025
e8149ae
Small updates
LiamConnors Apr 1, 2025
e45d56e
Merge branch 'main' into kaleido-docs-updates
LiamConnors Apr 1, 2025
0b79a17
Update static-image-generation-migration.md
LiamConnors Apr 1, 2025
f8cad81
Merge branch 'kaleido-docs-updates' of https://github.com/plotly/plot…
LiamConnors Apr 1, 2025
f5ac772
Update doc/python/static-image-export.md
LiamConnors Apr 2, 2025
10e8f20
Update doc/python/static-image-export.md
LiamConnors Apr 2, 2025
bbac70b
Update doc/python/static-image-export.md
LiamConnors Apr 2, 2025
9ad552e
Update doc/python/static-image-export.md
LiamConnors Apr 2, 2025
c290b5f
Update doc/python/static-image-export.md
LiamConnors Apr 2, 2025
7b8061b
Update static-image-generation-migration.md
LiamConnors Apr 3, 2025
07fd630
Merge branch 'kaleido-docs-updates' of https://github.com/plotly/plot…
LiamConnors Apr 3, 2025
6ba54f3
Update static-image-export.md
LiamConnors Apr 23, 2025
30cc778
Update doc/python/static-image-generation-migration.md
LiamConnors Apr 23, 2025
9b09504
Merge branch 'main' into kaleido-docs-updates
LiamConnors Apr 28, 2025
fded494
Merge branch 'kaleido-docs-updates' of https://github.com/plotly/plot…
LiamConnors Apr 29, 2025
077a356
Add note on browsers
LiamConnors Apr 29, 2025
2821776
Merge branch 'main' into kaleido-docs-updates
LiamConnors Apr 29, 2025
9f9262b
Update doc/python/static-image-generation-migration.md
LiamConnors Apr 30, 2025
551eaa6
update install commands
LiamConnors Apr 30, 2025
b9816bd
Merge branch 'kaleido-docs-updates' of https://github.com/plotly/plot…
LiamConnors Apr 30, 2025
8a8b052
Update doc/python/static-image-export.md
LiamConnors Apr 30, 2025
fc13f1d
Update doc/python/static-image-generation-migration.md
LiamConnors Apr 30, 2025
63229fc
Update doc/python/static-image-export.md
LiamConnors Apr 30, 2025
2eeac47
Update doc/python/static-image-export.md
LiamConnors Apr 30, 2025
b42185e
Update doc/python/static-image-generation-migration.md
LiamConnors Apr 30, 2025
e753b7b
Update doc/python/static-image-generation-migration.md
LiamConnors Apr 30, 2025
9fb73a1
Update doc/python/static-image-generation-migration.md
LiamConnors Apr 30, 2025
0284d5e
Update doc/python/static-image-export.md
LiamConnors Apr 30, 2025
ff62066
Update doc/python/static-image-export.md
LiamConnors Apr 30, 2025
41d72f0
Update doc/python/static-image-export.md
LiamConnors Apr 30, 2025
a27e2a9
Update static-image-export.md
LiamConnors May 1, 2025
8e62339
Update static-image-export.md
LiamConnors May 1, 2025
b8253c4
Update static-image-generation-migration.md
LiamConnors May 1, 2025
ba8ab39
Update static-image-export.md
LiamConnors May 1, 2025
2cc67f3
Update getting-started.md
LiamConnors May 1, 2025
9be1a49
Update static-image-generation-migration.md
LiamConnors May 1, 2025
70984fb
Update _kaleido.py
LiamConnors May 2, 2025
1965279
Merge pull request #5161 from plotly/release-6.1.0rc0
emilykl May 2, 2025
2f66bf1
Update plotly/io/_kaleido.py
LiamConnors May 6, 2025
815d975
Merge pull request #5164 from plotly/docstring-updates
LiamConnors May 6, 2025
d3ba372
Merge branch 'main' into kaleido-docs-updates
LiamConnors May 6, 2025
f70d8bf
Merge pull request #5111 from plotly/kaleido-docs-updates
LiamConnors May 7, 2025
5d29c69
removing old generated validators
bmaranville May 8, 2025
b359323
write single json instead of python files
bmaranville May 8, 2025
71be168
generate validator class instances from json data
bmaranville May 8, 2025
f3b546c
use validators from ValidatorCache
bmaranville May 8, 2025
646b4b6
use validators from ValidatorCache
bmaranville May 8, 2025
03100b4
use DataValidator from ValidatorCache
bmaranville May 8, 2025
0f6040b
trace validator should be instance not class of DataValidator
bmaranville May 8, 2025
2fb4670
use validators from ValidatorCache
bmaranville May 8, 2025
ae2ad4d
use template validator from ValidatorCache
bmaranville May 8, 2025
e92cf30
allow overlaying args on derived classes
bmaranville May 8, 2025
b46cb01
add DataValidator to autogenerated instances provided by ValidatorCac…
bmaranville May 8, 2025
9f20fd9
add DataValidator to autogenerated instances provided by ValidatorCac…
bmaranville May 8, 2025
c4df7e3
add DataValidator to autogenerated instances provided by ValidatorCac…
bmaranville May 8, 2025
bc2118a
use a copy of the DataValidator in BaseFigure, with local set_uid att…
bmaranville May 8, 2025
09e0140
Merge branch 'plotly:main' into refactor-validators
bmaranville May 8, 2025
d48cbe1
update validator params store
bmaranville May 8, 2025
d3c5f92
removing _data.py in validators, DataValidator is generated from Base…
bmaranville May 8, 2025
2f26c48
Merge branch 'refactor-validators' of github.com:bmaranville/plotly.p…
bmaranville May 8, 2025
00a8d1d
DataValidator is an instance already, and is not callable
bmaranville May 8, 2025
5607de0
use heatmap colorscale validator
bmaranville May 8, 2025
a23e0b7
update documentation example to use validator from ValidatorCache
bmaranville May 8, 2025
1b72556
cleanup
bmaranville May 9, 2025
689fa16
black formatting
bmaranville May 9, 2025
d893537
black formatting
bmaranville May 9, 2025
9e033b6
revert this file - it is auto-generated
bmaranville May 9, 2025
809ccc4
cleanup
bmaranville May 9, 2025
c191427
use ValidatorCache for generated Layout validators
bmaranville May 9, 2025
c301c4a
black formatting
bmaranville May 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add draft of Kaleido updates
  • Loading branch information
LiamConnors committed Mar 25, 2025
commit 7c76ee31c0fdbf073267100a0b578a53065a51eb
185 changes: 80 additions & 105 deletions doc/python/static-image-export.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ jupyter:
text_representation:
extension: .md
format_name: markdown
format_version: '1.2'
jupytext_version: 1.6.0
format_version: '1.3'
jupytext_version: 1.16.4
kernelspec:
display_name: Python 3
display_name: Python 3 (ipykernel)
language: python
name: python3
language_info:
Expand All @@ -20,7 +20,7 @@ jupyter:
name: python
nbconvert_exporter: python
pygments_lexer: ipython3
version: 3.7.6
version: 3.11.10
plotly:
description: 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
Expand All @@ -35,167 +35,147 @@ jupyter:
thumbnail: thumbnail/static-image-export.png
---

### 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, JPEG, SVG or PDF or you can [export them to HTML files which can be opened in a browser and remain interactive](/python/interactive-html-export/). This page explains how to do the former.

This page demonstrates how to export interactive Plotly figures to static image formats like PNG, JPEG, SVG, and PDF. If you want to export Plotly figures to HTML to retain interactivity, see the [Interactive HTML Export page](/python/interactive-html-export/)

<!-- #region -->
#### Install Dependencies
## Install Dependencies

### Kaleido

Static image generation requires either [Kaleido](https://github.com/plotly/Kaleido) (recommended, supported as of `plotly` 4.9) or [orca](https://github.com/plotly/orca) (legacy as of `plotly` 4.9). The `kaleido` package can be installed using pip...
Static image generation requires [Kaleido](https://github.com/plotly/Kaleido).
Install Kaleido with pip:
```
$ pip install -U kaleido
```

or conda.
or with conda:
```
$ conda install -c conda-forge python-kaleido
```

While Kaleido is now the recommended approach, image export can also be supported by the legacy [orca](https://github.com/plotly/orca) command line utility. See the [Orca Management](/python/orca-management/) section for instructions on installing, configuring, and troubleshooting orca.

<!-- #endregion -->

### Create a Figure

Now let's create a simple scatter plot with 100 random points of varying color and size.
It's also possible to generate static images using [orca](https://github.com/plotly/orca), though support for orca will be removed after September 2025. See the [Orca Management](/python/orca-management/) page for more details.

```python
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()
```
### Chrome

### Write Image File
Kaleido uses Chrome for static image generation. Versions of Kaleido prior to v1 included Chrome. Kaleido v1 and later uses Chrome that's available on the machine on which it's running. If you need to install Chrome for static image generation, Plotly provides a CLI.

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.
Run `plotly_get_chrome` to install Chrome.

Let's first create an output directory to store our images
You can also install Chrome from within Python using `plotly.io.install_chrome()`

```python
import os
import plotly.io as pio

if not os.path.exists("images"):
os.mkdir("images")
pio.install_chrome()
```
<!-- #endregion -->

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

Plotly figures have a `write_image` method to write a figure to a file. `write_image` supports PNG, JPEG, WebP, SVG, and PDF.

#### Raster Formats: PNG, JPEG, and WebP
To export a figure using `write_image`, call `write_image` on the figure with the filename where you want to save the figure on the figure. The file format is inferred from the extension:


plotly.py can output figures to several raster image formats including **PNG**, ...
### Raster Formats

**PNG**
~~~python
fig.write_image("images/fig1.png")
import plotly.express as px
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')
fig.write_image("fig1.png")
~~~

**JPEG**, ...
**JPEG**

~~~python
...
fig.write_image("images/fig1.jpeg")
~~~

and **WebP**
**WebP**

~~~python
...
fig.write_image("images/fig1.webp")
~~~

#### Vector Formats: SVG and PDF...


plotly.py can also output figures in several vector formats including **SVG**, ...
### Vector Formats

**SVG**
~~~python
...
fig.write_image("images/fig1.svg")
~~~

**PDF**, ...
**PDF**

~~~python
...
fig.write_image("images/fig1.pdf")
~~~

and **EPS** (requires the poppler library)
---

**EPS** (Kaleido<1.0.0)

Kaleido versions earlier than 1.0.0 also support **EPS** (requires the poppler library)

~~~python
...
fig.write_image("images/fig1.eps")
~~~

**Note:** It is important to note that any figures containing WebGL traces (i.e. of type `scattergl`, `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.

**Note:** Figures containing WebGL traces (i.e. of type `scattergl`, `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.

### Image Export in Dash

[Dash](https://plotly.com/dash/) is the best way to build analytical apps in Python using Plotly figures. To run the app below, run `pip install dash`, click "Download" to get the code and run `python app.py`.
### Specifying a Format

Get started with [the official Dash docs](https://dash.plotly.com/installation) and **learn how to effortlessly [style](https://plotly.com/dash/design-kit/) & [deploy](https://plotly.com/dash/app-manager/) apps like this with <a class="plotly-red" href="https://plotly.com/dash/">Dash Enterprise</a>.**
In the earlier example, Plotly inferred the image format from the extension of the filename. You can also specify this with the `format` parameter.

~~~python
import plotly.express as px
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')
fig.write_image("fig1", format="png")
~~~

```python hide_code=true
from IPython.display import IFrame
snippet_url = 'https://python-docs-dash-snippets.herokuapp.com/python-docs-dash-snippets/'
IFrame(snippet_url + 'static-image-export', width='100%', height=1200)
```

### 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.
## Get Image as Bytes

Let convert the figure to a **PNG** bytes object...
As well as exporting to a file, Plotly figures also support conversion to a bytes object.
To convert a figure to a **PNG** bytes object, call the figure's `to_image` method with a `format`

```python
img_bytes = fig.to_image(format="png")
```
import plotly.express as px
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')

and then display the first 20 bytes.

```python
img_bytes[:20]
img_bytes = fig.to_image(format="png")
```

#### Display Bytes as Image Using `IPython.display.Image`
### 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](https://qtconsole.readthedocs.io/en/stable/)!

```python
from IPython.display import Image
Image(img_bytes)
```

### Change Image Dimensions and Scale
## 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.

```python
img_bytes = fig.to_image(format="png", width=600, height=350, scale=2)
Image(img_bytes)
```

<!-- #region -->
### Specify Image Export Engine
## Specify Image Export Engine

> The `engine` parameter is deprecated in Plotly.py 6.1.0 and will be removed after September 2025.

If `kaleido` is installed, it will automatically be used to perform image export. If it is not installed, plotly.py will attempt to use `orca` instead. The `engine` argument to the `to_image` and `write_image` functions can be used to override this default behavior.

Here is an example of specifying that orca should be used:
Expand All @@ -208,31 +188,26 @@ And, here is an example of specifying that Kaleido should be used:
fig.to_image(format="png", engine="kaleido")
~~~

<!-- #endregion -->

<!-- #region -->
### Image Export Settings (Kaleido)
Various image export settings can be configured using the `plotly.io.kaleido.scope` object. For example, the `default_format` property can be used to specify that the default export format should be `svg` instead of `png`
## plotly.io Functions

```python
import plotly.io as pio
pio.kaleido.scope.default_format = "svg"
```
Previous examples on this page access `write_image` and `to_image` as methods on Plotly Figure objects. This functionality is also available via the `plotly.io` subpackage.

Here is a complete listing of the available image export settings:
The following example uses the `write_image` function from `plotly.io`. The function takes the figure or a `dict` representing a figure (as shown in the example) as it's first argument.

- **`default_width`**: The default pixel width to use on image export.
- **`default_height`**: The default pixel height to use on image export.
- **`default_scale`**: The default image scale factor applied on image export.
- **`default_format`**: The default image format used on export. One of `"png"`, `"jpeg"`, `"webp"`, `"svg"`, `"pdf"`, or `"eps"`.
- **`mathjax`**: Location of the MathJax bundle needed to render LaTeX characters. Defaults to a CDN location. If fully offline export is required, set this to a local MathJax bundle.
- **`topojson`**: Location of the topojson files needed to render choropleth traces. Defaults to a CDN location. If fully offline export is required, set this to a local directory containing the [Plotly.js topojson files](https://github.com/plotly/plotly.js/tree/master/dist/topojson).
- **`mapbox_access_token`**: The default Mapbox access token.

<!-- #endregion -->
~~~python
import plotly.io as pio


### Image Export Settings (Orca)
See the [Orca Management](/python/orca-management/) section for information on how to specify image export settings when using orca.
fig = dict({
"data": [{"type": "bar",
"x": [1, 2, 3],
"y": [1, 3, 2]}],
"layout": {"title": {"text": "A Figure Specified By Python Dictionary"}}
})

### Summary
In summary, to export high-quality static images from plotly.py, all you need to do is install the `kaleido` package 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).
pio.write_image(fig, "fig.png")
~~~
<!-- #endregion -->
0