Menu

Customizing Charts with Plotly Graph Objects

Customizing Charts with Plotly Graph Objects

Plotly Express is convenient for quickly creating charts. However, when you need precise control over traces, axes, annotations, or layout, Plotly Graph Objects is often more suitable.

Creating a Chart with Graph Objects

import plotly.graph_objects as go

months = ["Jan", "Feb", "Mar", "Apr", "May"]

revenue = [12000, 15000, 13500, 18000, 22000]

fig = go.Figure()

fig.add_trace(

go.Scatter(

x=months,

y=revenue,

mode="lines+markers",

name="Revenue"

)

)

fig.update_layout(

title="Monthly Revenue",

xaxis_title="Month",

yaxis_title="Revenue",

template="plotly_white"

)

fig.show()

The Figure object stores the chart configuration, and add_trace() adds a data series. The update_layout() method controls chart-level properties.

Adding Multiple Data Series

import plotly.graph_objects as go

months = ["Jan", "Feb", "Mar", "Apr"]

fig = go.Figure()

fig.add_trace(

go.Scatter(

x=months,

y=[10000, 12000, 15000, 17000],

mode="lines+markers",

name="2025"

)

)

fig.add_trace(

go.Scatter(

x=months,

y=[12000, 14000, 16000, 20000],

mode="lines+markers",

name="2026"

)

)

fig.update_layout(

title="Year-over-Year Sales Comparison",

xaxis_title="Month",

yaxis_title="Sales",

hovermode="x unified"

)

fig.show()

The two traces allow users to compare monthly sales across years. The unified hover mode presents values for the same horizontal position together, making comparisons more convenient.

Adding Annotations

Annotations highlight important points in a chart.

fig.add_annotation(

x="Apr",

y=20000,

text="Highest sales",

showarrow=True,

arrowhead=2

)

fig.show()

This annotation can be added to the year-over-year chart above to highlight a specific observation. Use annotations sparingly so that they clarify rather than clutter the visualization.


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details