plotly

Plotly.io.to_json

JavaScript Object Notation or JSON for short, is a popular and useful data interchange format. It is supported by a wide range of applications and languages. This makes it very useful for near-universal data exchange.

In this tutorial, we will learn how to convert Plotly figures or graph_objects into JSON strings.

Let’s get started.

Plotly.io.to_json()

The plotly.io.to_json() function allows us to convert a figure into a JSON string. The function syntax is as shown below:

plotly.io.to_json(fig, validate=True, pretty=False, remove_uids=True, engine=None)

The parameters are as shown:

  1. Fig – specifies the figure or object to convert into a JSON string.
  2. Validate – a Boolean value that determines if a figure should be validated before converting to JSON.
  3. Pretty – if true, the JSON string is pretty-printed otherwise, the JSON string is returned in a compact format.
  4. Remove_uids – if true, it allows plotly to remove the trace UIDs from the JSON representation.
  5. Engine – specifies the JSON encoding engine. Accepted values include:
    1. ‘json’ – uses the Python’s built-in JSON module.
    2. ‘orjson’ – specifies the orjson engine. Much faster but requires installation.
    3. ‘auto’ – automatically select the engine depending on the available package.

The function will then return the input figure as a JSON representation as a string type.

Convert Plotly Express Figure to JSON

We can convert a figure into a JSON string using the to_string function as shown in the example below:

import plotly.express as px
import plotly.io as io
df = px.data.stocks()
fig = px.line(df, x='date', y='FB')
io.to_json(fig)

In the example above, we use the stock data from Plotly express and plot a simple line graph.

We then use the to_json() string to convert the figure into a JSON string.

The code above should return:

To create more readable data, we can use the pretty parameter as shown:

io.to_json(fig, pretty=True)

To change the engine:

io.to_json(fig, pretty=True, engine="orjson")

The above code requires the orjson package to be installed on your system. You can do so by running pip as:

$ pip install orjson

To remove UIDs, set the parameter to True as shown:

io.to_json(fig, pretty=True, engine="orjson", remove_uids=True)

Closing

This short article shows how to convert a figure into JSON string using the to_json() function.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list