Plotly Express Line Charts with px.line

Draw line charts with px.line, plot multiple lines from long or wide data, add markers and dashes, label line ends, facet into small multiples, and fix zigzags and gaps.

Create a line chart in Plotly with px.line(df, x="date", y="value"). For multiple lines, add color="column" when your data is in long form, or pass a list of column names to y when each series has its own column.

Quick Example

import numpy as np
import pandas as pd
import plotly.express as px

rng = np.random.default_rng(90)
dates = pd.date_range("2026-01-05", periods=40, freq="W-MON")
traffic = pd.DataFrame({"week": dates})
for channel, start, slope in [("Search", 4200, 85), ("Social", 3100, 20), ("Email", 1500, 55)]:
    traffic[channel] = (start + slope * np.arange(40) + rng.normal(0, 180, 40).cumsum() * 0.5
                        + rng.normal(0, 90, 40)).round()
visits = traffic.melt(id_vars="week", var_name="channel", value_name="visits")

fig = px.line(visits, x="week", y="visits", color="channel",
              title="Weekly site visits by channel",
              color_discrete_sequence=["#2563eb", "#db2777", "#059669"],
              labels={"week": "Week", "visits": "Visits", "channel": "Channel"})
fig.update_layout(hovermode="x unified")
fig.show()

Plotly Express line chart of weekly website visits for search, social, and email channels over 40 weeks

Search leads throughout, growing from about 4,300 to 7,900 weekly visits, and Email moves ahead of Social at the end of August. hovermode="x unified" shows all three values for a week in one tooltip. The code targets Plotly 6.x.

Long Data vs Wide Data

traffic above is wide: one column per channel. visits is long: one row per week and channel. px.line handles both.

# long form: one column names the series
px.line(visits, x="week", y="visits", color="channel")

# wide form: list the series columns
px.line(traffic, x="week", y=["Search", "Social", "Email"])

Long form is more flexible, because the other columns can drive line_dash, symbol, or facets. With wide form, Plotly names the legend variable and the y-axis value; rename them with labels={"variable": "Channel", "value": "Visits"}. If you prefer df.plot() syntax, switch the pandas plotting backend to Plotly.

Add Markers and Line Dashes

markers=True shows each data point. line_dash maps a column to dash patterns, so two variables can be encoded at once: color for region, dash for actual vs target.

quarters = ["Q1", "Q2", "Q3", "Q4"]
plan = pd.DataFrame({
    "quarter": quarters * 4,
    "region": ["North"] * 8 + ["South"] * 8,
    "kind": (["Actual"] * 4 + ["Target"] * 4) * 2,
    "revenue": [212, 238, 251, 290, 220, 235, 255, 275,
                168, 171, 196, 214, 160, 180, 200, 225],
})
fig = px.line(plan, x="quarter", y="revenue", color="region", line_dash="kind",
              markers=True, title="Revenue vs target ($k)",
              color_discrete_map={"North": "#7c3aed", "South": "#ea580c"},
              line_dash_map={"Actual": "solid", "Target": "dot"})
fig.update_traces(line_width=3, marker_size=9)
fig.show()

Line chart with solid lines for actual revenue and dotted lines for targets in two regions: North in purple ends above target and South in orange ends below

North finishes Q4 at $290k against a $275k target, while South lands at $214k against $225k. The allowed dash names are "solid", "dot", "dash", "longdash", "dashdot", and "longdashdot", or a pixel pattern such as "5px 2px".

Label the End of Each Line

Loop over fig.data and add one annotation at the last point of each trace, using the trace's own color.

fig = px.line(visits, x="week", y="visits", color="channel",
              title="Direct labels at the end of each line",
              color_discrete_sequence=["#2563eb", "#db2777", "#059669"])
for trace in fig.data:
    fig.add_annotation(x=trace.x[-1], y=trace.y[-1], text=trace.name, showarrow=False,
                       xanchor="left", xshift=6, font=dict(color=trace.line.color, size=14))
fig.update_layout(showlegend=False, margin_r=80, xaxis_title=None)
fig.show()

Weekly visits line chart with Search, Social, and Email written next to the end of each line instead of a legend

For arrows and other label options, see custom annotations in Plotly.

Small Multiples with facet_col

When lines overlap too much, give each group its own panel. facet_col_wrap sets the number of columns, and the axes are shared, so panels compare directly.

hours = np.arange(24)
load = pd.DataFrame(
    [(site, day, h, base + amp * scale * np.exp(-((h - peak) ** 2) / 18) + rng.normal(0, 4))
     for site, base, amp in [("Warehouse", 60, 90), ("Office", 25, 120),
                             ("Store", 40, 70), ("Data center", 150, 15)]
     for day, scale, peak in [("Weekday", 1.0, 13), ("Weekend", 0.45, 15)]
     for h in hours],
    columns=["site", "day", "hour", "kw"],
)
fig = px.line(load, x="hour", y="kw", color="day", facet_col="site", facet_col_wrap=2,
              title="Power draw by hour (kW)",
              color_discrete_map={"Weekday": "#0f172a", "Weekend": "#f97316"})
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.show()

Four panels of hourly power draw for a warehouse, office, store, and data center, comparing weekday and weekend lines; the data center is high and flat

The for_each_annotation line trims panel titles from site=Office to Office. To combine different chart types or independent axes, use make_subplots instead.

Why Is My Line Chart Zigzagging?

px.line connects points in row order, not x order. If the rows are shuffled, the line jumps back and forth. Sort by the x column first.

temp = pd.DataFrame({"day": np.arange(1, 31),
                     "temp": 12 + 6 * np.sin(np.arange(30) / 5) + rng.normal(0, 0.6, 30)})
temp.loc[10:14, "temp"] = np.nan
shuffled = temp.sample(frac=1, random_state=3)

px.line(shuffled, x="day", y="temp").show()                    # zigzags
fig = px.line(shuffled.sort_values("day"), x="day", y="temp")  # fixed
fig.show()
fig.update_traces(connectgaps=True)                            # bridge missing values
fig.show()

Three small line charts: unsorted data drawn as a tangle, sorted data with a gap where values are missing, and the gap bridged with connectgaps

Missing values leave a break by default. connectgaps=True draws straight across it. Also check the column type: convert date strings with pd.to_datetime so that sorting follows the calendar and not the alphabet.

Step Lines and Smoothed Lines

line_shape="hv" draws steps that hold each value until the next change, which suits rates, prices, and inventory levels.

price = pd.DataFrame({"month": np.arange(1, 13),
                      "rate": [4.0, 4.0, 4.25, 4.5, 4.5, 4.5, 4.75, 4.5, 4.25, 4.25, 4.0, 3.75]})
fig = px.line(price, x="month", y="rate", line_shape="hv", markers=True,
              title='Interest rate with line_shape="hv"',
              color_discrete_sequence=["#0369a1"])
fig.show()

Step line chart of an interest rate holding flat between changes over twelve months

line_shape="spline" smooths the line instead. A spline can overshoot above or below your real values, so use it with care.

Practical Tips

Similar Topics