Using Annotations

Annotations are text elements that can be placed on a graph to highlight specific data points, provide explanatory notes, or label important features such as trends, thresholds, or outliers. Unlike standard labels or titles, annotations can be positioned anywhere on the chart, offering greater flexibility for emphasizing key insights. For instance, when analyzing stock prices, annotations can mark significant events like earnings releases or market crashes directly on the time series chart. This contextual information can help viewers better understand the story behind the data.

Annotations in Plotly Express are a versatile way to enhance visualizations by adding context, clarity, and emphasis to charts. In Plotly Express, annotations are added using through add_hline or add_vline to add a horizontal or vertical line. Annotation boxes are created with add_vrect. A single annotation can be added with the update_layout method, where users define the annotation's text, position, and styling attributes such as font size, color, and alignment. They can also include arrows to point to specific locations, making it easier to connect annotations to the corresponding data points.

import plotly.express as px

# Download the stock data
df = px.data.stocks() 

# Visualize the line charts
fig = px.line(df, x='date', y='NFLX')

# Add a horizontal line 
fig.add_hline(y=1, line_dash="dot",
              annotation_text="Jan 1, 2018 baseline",
              annotation_position="bottom right")

# Add a vertical rectangle 
fig.add_vrect(x0="2018-09-24", x1="2018-12-18", col=1,
              annotation_text="decline", annotation_position="top left",
              fillcolor="green", opacity=0.25, line_width=0)
 
# Show the visualization                          
fig.show()

One of the strengths of Plotly's annotations is their interactivity, as they integrate seamlessly with hover effects and tooltips, ensuring that the chart remains both informative and dynamic. Annotations are particularly useful in creating dashboards or reports, where they can provide additional guidance or commentary for the audience, enabling more effective communication of insights.

Last updated