Open In Colab

Chapter 8 - Tie Up Loose Ends

8.1 Themes & Templates

Plotly visualization supports multiple themes represented by templates.

We can set a default template up front which will be applied to all visualizations generated afterward by setting the variable pio.templates.default.

Each viualization can also specify a template by using a property template in the Figure object.

# As of this writing, the Google Colab has Plotly version 4.4.1 pre-installed
# We need to upgrade it to the latest version

!pip install --upgrade plotly
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: plotly in /home/codespace/.local/lib/python3.8/site-packages (5.3.1)
Requirement already satisfied: tenacity>=6.2.0 in /home/codespace/.local/lib/python3.8/site-packages (from plotly) (8.0.1)
Requirement already satisfied: six in /usr/lib/python3/dist-packages (from plotly) (1.14.0)
import numpy as np                  # We use numpy to generate some sample data for ploting
import plotly.graph_objects as go   # graph_opjects package is the core of plotly
import plotly.io as pio

import plotly
plotly.__version__
'5.3.1'
# This shows the default template is "plotly"
# This also lists all supported templates. 

print(pio.templates)
Templates configuration
-----------------------
    Default template: 'plotly'
    Available templates:
        ['ggplot2', 'seaborn', 'simple_white', 'plotly',
         'plotly_white', 'plotly_dark', 'presentation', 'xgridoff',
         'ygridoff', 'gridon', 'none']
# Change the default template from plotly to plotly_dark

pio.templates.default = "plotly_dark"

8.2 Export Figures

There are several ways to export a Plotly visualization.

8.2.1 Ouptut JSON Data

As mentioned in 1.2.3, we can use Python print() function to print the content of a figre including its Data component and the Layout component. Here, the output of print() shows the figure has two traces along with properties of the layout.

print(fig)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/tmp/ipykernel_19373/4108367019.py in <module>
----> 1 print(fig)

NameError: name 'fig' is not defined

8.2.2 Output as Static Images

Plotly visualizations can be downloade as a static image by clicking on download icon. The icon is on the far left of the tool bar which appears on the upper right of the visualization when you move the mouse over that area.

We can also write code to export a visualization to a static image file in a varieties of format including PNG, JPG, and PDF. Since generated image files are static, the interactivity is lost.

In order to generate static images from Plotly visualizations, a ancilary Python library kaleido must be installed first.

!pip install kaleido
Requirement already satisfied: kaleido in /usr/local/lib/python3.7/dist-packages (0.2.1)
fig.write_image("boxplot.png")
fig.write_image("boxplot.pdf")

8.2.3 Output to HTML Files

Plotly visualizations can be exported to HTML files which can be opened using a web browser for display and interaction.

The parameter include_plotlyjs has two options that result in different size of the generated file.

When the option is True, the Plotly.js Java Script library is included in the file which adds about 3MB to the size of the file.

When the option is set to “cnd” (content delivery network), the Plotly.js library is not included in the file but referenced from the website https://cdn.plot.ly. This makes the resulting file much smaller.

fig.write_html("boxplot_include_js.html", include_plotlyjs=True)

fig.write_html("boxplot_cdn.html", include_plotlyjs="cdn")

8.3 Python Flexibility

Plotly Python is flexible and provide multiple ways to achieve the same things.

8.3.1 Different Ways to Create a Figure

We can create an empty Figure object and then add traces and update layout properties like this:

trace_0 = go.Box(   
    x=male_ages,    
    name="Male"   
)

fig = go.Figure()
fig.add_trace(trace_0)
fig.update_layout(title="A Boxplot")

Alternatively, we can create traces and add them to the Data object and create a Layout object with some specified properties and then create the figure using the Data object and Layout object as inputs:

trace_0 = go.Box(   
    x=male_ages,    
    name="Male"   
)

my_layout = go.Layout(title="A Boxplot")
fig = go.Figure(data=[trace_0], layout=my_layout)

8.3.2 Different Ways to Create a Trace

We can use a specifc method of the Graph object. Here we use Box() method to create a Boxplot. This method creates a Python dictionary object to represent a Boxplot.

trace_0 = go.Box(
    x=[10, 3, -5, -35, 23, 8, 78, -65, 13,31, 82],  
    name="Trace Name"                   
)

Alternatively, we can use a Python dictionary object to represent a trace:

trace_0 = {                         
    "x":[10, 3, -5, -35, 23, 8, 78, -65, 13,31, 82],  
    "type":"box",
    "name":"Trace Name"                   
}

8.3.3 Different Ways to Specify a Layout Property

For example, to specify the title of the X axis, the following three methods work the same:

  • fig.update_layout(xaxis={"title":"Age"})

  • fig.update_layout(xaxis_title="Age")

  • fig.layout.xaxis.title = "Age"

Python is a flexible language and offers alternative ways to achieve the same outcome. In some cases, there are industry best practices. For example, the commonly used indentation is four spaces. In other cases, it is up to your personal preference. In the latter, you should try to pick one and use it consistently.

8.4 Plotly Chart Studio

8.5 Dash for Dashboard and Data Apps