# Plotly Express Line Charts with px.line

> Plotly Express line chart guide: px.line with multiple lines, unified hover, markers and line_dash, end-of-line labels, facets, sorting data, connectgaps, and step lines.

Source: https://www.pythoncharts.com/plotly/plotly-express-line-charts/ | Published: 2026-11-26 | Author: Alex Scott | Category: Plotly | Tags: plotly, plotly express, px, line-chart, multiple-lines, time-series, faceting

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

```python
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](https://www.pythoncharts.com/plotly/plotly-express-line-charts/images/plotly-express-line-quick-example.png)

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.

```python
# 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](https://www.pythoncharts.com/pandas/pandas-plotly-backend/).

## 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.

```python
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](https://www.pythoncharts.com/plotly/plotly-express-line-charts/images/plotly-express-line-dash-markers.png)

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.

```python
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](https://www.pythoncharts.com/plotly/plotly-express-line-charts/images/plotly-express-line-end-labels.png)

For arrows and other label options, see [custom annotations in Plotly](https://www.pythoncharts.com/plotly/plotly-add-custom-annotations/).

## 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.

```python
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](https://www.pythoncharts.com/plotly/plotly-express-line-charts/images/plotly-express-line-facets.png)

The `for_each_annotation` line trims panel titles from `site=Office` to `Office`. To combine different chart types or independent axes, use [make_subplots](https://www.pythoncharts.com/plotly/plotly-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.

```python
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](https://www.pythoncharts.com/plotly/plotly-express-line-charts/images/plotly-express-line-order-gaps.png)

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.

```python
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](https://www.pythoncharts.com/plotly/plotly-express-line-charts/images/plotly-express-line-step.png)

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

## Practical Tips

- Add a date range slider with `fig.update_xaxes(rangeslider_visible=True)`. The [range slider and selector post](https://www.pythoncharts.com/plotly/range-slider-selector-time-series/) shows preset buttons too.
- For tens of thousands of points, pass `render_mode="webgl"`. See [speeding up Plotly with WebGL](https://www.pythoncharts.com/plotly/plotly-webgl-performance/).
- Line charts don't need a y-axis that starts at zero, but label the axis so the scale is obvious.
- Prefer Matplotlib for print figures? Read [Matplotlib line plots](https://www.pythoncharts.com/matplotlib/matplotlib-line-plot/).

## Similar Topics

- [Adding Range Sliders and Selectors to a Time Series Plot in Plotly](https://www.pythoncharts.com/plotly/range-slider-selector-time-series/)
- [Plotly Express Bar Charts: Grouped, Stacked, and Labeled](https://www.pythoncharts.com/plotly/plotly-express-bar-charts/)
- [Customize Hover Tooltips in Plotly](https://www.pythoncharts.com/plotly/plotly-customize-hover-tooltips/)
