Interactive Line Charts
When to reach for a line chart
Section titled “When to reach for a line chart”A line chart is the go-to shape for change over an ordered axis — almost always time (days, months, years). The line itself draws attention to trend: is the metric rising, falling, or flat? Markers on top of the line let you also read off exact points without losing the trend shape.
Basic interactive line
Section titled “Basic interactive line”import pandas as pd
import plotly.express as px
df = pd.DataFrame({
"date": pd.date_range("2025-01-01", periods=7, freq="D"),
"orders": [120, 140, 130, 160, 155, 170, 180],
})
fig = px.line(df, x="date", y="orders", markers=True, title="Daily orders")
fig.show()Because this is Plotly (not Matplotlib), the rendered chart already lets you hover each marker for its exact date/value, drag to zoom into a date range, and double-click to reset.
Multiple lines (color)
Section titled “Multiple lines (color)”import pandas as pd
import plotly.express as px
df = pd.DataFrame({
"date": list(pd.date_range("2025-01-01", periods=5, freq="D")) * 2,
"orders": [120, 140, 130, 160, 155, 100, 110, 120, 125, 140],
"product": ["A"] * 5 + ["B"] * 5,
})
fig = px.line(df, x="date", y="orders", color="product", markers=True, title="Orders by product")
fig.show()Passing color="product" does two things at once: it splits the data into one line per group, and it adds a legend you can click to hide/show a series.
- Use
hover_data=[...]to show extra fields (e.g. region, channel) in the tooltip. - Use
fig.update_layout(...)for axis labels, margins, and legend position. - Sort your DataFrame by the x-axis column first — Plotly draws points in row order, so an unsorted date column produces a zig-zag line.
flowchart TD A["Is the x-axis ordered
and continuous (time, sequence)?"] -->|"Yes"| B["Does trend/direction
matter most?"] A -->|"No, unordered categories"| C["Use a bar chart instead"] B -->|"Yes"| D["px.line(...)
add markers=True for exact points"] B -->|"No, comparing totals"| C
Continue to: Interactive Bar Charts for comparing categories.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Draw a Line Chart
Section titled “Exercise 1 – Draw a Line Chart”Exercise 2 – Show the Markers
Section titled “Exercise 2 – Show the Markers”Exercise 3 – One Line per Group
Section titled “Exercise 3 – One Line per Group”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading