Black Lives Matter. Please consider donating to Black Girls Code today.

Plotly 4.8, template not adding image layout when applied

I am building a plotly template to reduce work in “prettifying” R&D visualizations for use in presentations.

When trying to add a logo to plots through templating I have encountered something annoying.

Adding a logo image to the template is simple enough. When the template is later applied, in this case through pandas plot with the plotly backend, the image is not added. The image layout exists within the figure template, and can be retrieved and assigned to the figure’s layout.images, revealing the image.

The code snippet requires plotly 4.8 or greater.

import plotly.graph_objs as go
import as pio
import pandas as pd
import as px

pd.options.plotting.backend = "plotly"

# Add a test image to the template layout
pio.templates['test_template'] = go.layout.Template({'layout': {
     'images': [{'sizex': 0.5, 'sizey': 0.5,
                 'source': (''),
                 'x': 0.5, 'xanchor': 'center', 'xref': 'paper',
                 'y': 0, 'yanchor': 'bottom', 'yref': 'paper'}],

# apply template when plotting mock data, does not display test logo image.
fig = pd.DataFrame(dict(a=[1, 2, 3], b = [3, 2, 1])) = "test_template")

# Retrieving the image layout from within the figure template makes the image appear

I found the same behaviour when using fig.update_layout with templating. When applying the layout part of the template through go.Figure(layout=template.layout) the image is shown.

Is there something I’m missing here?

Ah, sorry about the cryptic docs here, but there is another attribute name you need to set in your layout image to get it to actually appear in the figures that use the template:

This is set up this way so that charts using templates can “conditionally consume” template attributes i.e. you set up the image part of the template so that the logo is always in the same place, but the logo only appears if the URL is set in a figure, allowing one template to be used for figures with various logos, say.

1 Like