Setting the Font, Title, Legend Entries, and Axis Titles in Python

How to set the global font, title, legend-entries, and axis-titles in python.


New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Automatic Labelling with Plotly Express

Plotly Express is the easy-to-use, high-level interface to Plotly, which operates on a variety of types of data and produces easy-to-style figures.

When using Plotly Express, your axes and legend are automatically labelled, and it's easy to override the automation for a customized figure using the labels keyword argument. The title of your figure is up to you though!

Here's a figure with automatic labels and then the same figure with overridden labels. Note the fact that when overriding labels, the axes, legend title and hover labels reflect the specified labels automatically.

In [1]:
import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_length", y="sepal_width", color="species",
                title="Automatic Labels Based on Data Frame Column Names")
fig.show()
In [2]:
import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_length", y="sepal_width", color="species",
                 labels={
                     "sepal_length": "Sepal Length (cm)",
                     "sepal_width": "Sepal Width (cm)",
                     "species": "Species of Iris"
                 },
                title="Manually Specified Labels")
fig.show()

Global and Local Font Specification

You can set the figure-wide font with the layout.font attribute, which will apply to all titles and tick labels, but this can be overridden for specific plot items like individual axes and legend titles etc. In the following figure, we set the figure-wide font to Courier New in blue, and then override this for certain parts of the figure.

In [3]:
import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_length", y="sepal_width", color="species",
                title="Playing with Fonts")
fig.update_layout(
    font_family="Courier New",
    font_color="blue",
    title_font_family="Times New Roman",
    title_font_color="red",
    legend_title_font_color="green"
)
fig.update_xaxes(title_font_family="Arial")
fig.show()

Set Automargin on the Plot Title

New in 5.14

Set automargin=True to allow the title to push the figure margins. With yref set to paper, automargin=True expands the margins to make the title visible, but doesn't push outside the container. With yref set to container, automargin=True expands the margins, but the title doesn't overlap with the plot area, tick labels, and axis titles.

In [4]:
import plotly.express as px

df = px.data.gapminder().query("continent == 'Oceania'")
fig = px.line(df, x="year", y="gdpPercap", color="country")

fig.update_layout(
    title=dict(text="GDP-per-capita", font=dict(size=50), automargin=True, yref='paper')
)

fig.show()

Fonts and Labels in Dash

Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash dash-daq, click "Download" to get the code and run python app.py.

Get started with the official Dash docs and learn how to effortlessly style & deploy apps like this with Dash Enterprise.

Out[5]:

Sign up for Dash Club → Free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture. Join now.

Manual Labelling with Graph Objects

When using graph objects rather than Plotly Express, you will need to explicitly label traces and axes:

In [6]:
import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    y=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    name="Name of Trace 1"       # this sets its legend entry
))


fig.add_trace(go.Scatter(
    x=[0, 1, 2, 3, 4, 5, 6, 7, 8],
    y=[1, 0, 3, 2, 5, 4, 7, 6, 8],
    name="Name of Trace 2"
))

fig.update_layout(
    title="Plot Title",
    xaxis_title="X Axis Title",
    yaxis_title="Y Axis Title",
    legend_title="Legend Title",
    font=dict(
        family="Courier New, monospace",
        size=18,
        color="RebeccaPurple"
    )
)

fig.show()

The configuration of the legend is discussed in detail in the Legends page.

Align Plot Title

The following example shows how to align the plot title in layout.title. x sets the x position with respect to xref from "0" (left) to "1" (right), and y sets the y position with respect to yref from "0" (bottom) to "1" (top). Moreover, you can define xanchor to left,right, or center for setting the title's horizontal alignment with respect to its x position, and/or yanchor to top, bottom, or middle for setting the title's vertical alignment with respect to its y position.

In [7]:
import plotly.graph_objects as go

fig = go.Figure(go.Scatter(
    y=[3, 1, 4],
    x=["Mon", "Tue", "Wed"]))

fig.update_layout(
    title={
        'text': "Plot Title",
        'y':0.9,
        'x':0.5,
        'xanchor': 'center',
        'yanchor': 'top'})

fig.show()

Reference

See https://plotly.com/python/reference/layout/ for more information!

What About Dash?

Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash at https://dash.plot.ly/installation.

Everywhere in this page that you see fig.show(), you can display the same figure in a Dash application by passing it to the figure argument of the Graph component from the built-in dash_core_components package like this:

import plotly.graph_objects as go # or plotly.express as px
fig = go.Figure() # or any Plotly Express function e.g. px.bar(...)
# fig.add_trace( ... )
# fig.update_layout( ... )

from dash import Dash, dcc, html

app = Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

app.run_server(debug=True, use_reloader=False)  # Turn off reloader if inside Jupyter