Formatting a Plotly Figure With Matplotlib Style

Becky O’Toole
The Startup
Published in
2 min readJul 16, 2020

For most of my doctoral work, I’ve been using Matplotlib to analyze data and make publication-ready figures. However, I recently switched to Plotly and am glad I took the time to learn the Python library, as the ability to easily make interactive plots is extremely helpful when analyzing new data.

Still, the default Plotly formatting is not exactly publication-ready, so I now reformat my Plotly figures to look more like Matplotlib figures using just a few lines of code!

Here, I’ve created a Plotly graph_object from data stored in a Pandas DataFrame.

import pandas as pd
import plotly.graph_objects as go
import numpy as np
# create a pandas dataframe
x=np.linspace(0,20,100)
y=np.sin(x)
df = pd.DataFrame(data={'x': x, 'y':y})
# create a plotly figure
fig=go.Figure()
# plot the data
fig.add_trace(go.Scatter(x=df['x'],y=df['y']))
fig.show()

Leading to the following figure:

At this point, the formatting could be improved to make the figure look more professional.

First, we’ll choose the font, set the background color, and update the figure layout to be more standardized by setting the figure width, height, and margin. We’ll place the following code before the fig.show() command:

# choose the figure font
font_dict=dict(family='Arial',
size=26,
color='black'
)
# general figure formatting
fig.update_layout(font=font_dict, # font formatting
plot_bgcolor='white', # background color
width=850, # figure width
height=700, # figure height
margin=dict(r=20,t=20,b=10) # remove white space
)

Updating the figure to:

Next, we need to format the axes by setting the font and adding a black border and tick marks, by placing the following code before fig.show().

# x and y-axis formatting
fig.update_yaxes(title_text='Y-axis', # axis label
showline=True, # add line at x=0
linecolor='black', # line color
linewidth=2.4, # line size
ticks='outside', # ticks outside axis
tickfont=font_dict, # tick label font
mirror='allticks', # add ticks to top/right axes
tickwidth=2.4, # tick width
tickcolor='black', # tick color
)
fig.update_xaxes(title_text='X-axis',
showline=True,
showticklabels=True,
linecolor='black',
linewidth=2.4,
ticks='outside',
tickfont=font_dict,
mirror='allticks',
tickwidth=2.4,
tickcolor='black',
)

Leading to:

And now we have a nicely formatted Plotly figure!

--

--

Becky O’Toole
The Startup

A PhD student, writing articles about analyzing scientific data.