Sub topic 12
Plotting time series with a datetime index
This chapter assumes you can build a DataFrame, select columns, and call df.plot() with the default line chart. You should also know how the index maps to the x axis. Matplotlib must be installed.
When the index holds dates, plot treats it as a time axis. It formats the tick labels as dates, spaces points by real time, and picks tick positions that suit the span of the data. Getting the index to be a real datetime type is most of the work.
Why the index type matters
A column of strings that look like dates is still text. If you plot it, pandas places the points at equal spacing and prints every label. A column of datetime64 values is different. Pandas places each point at its true position in time.
import pandas as pd
import matplotlib.pyplot as plt
raw = pd.DataFrame({
"date": ["2026-01-01", "2026-01-02", "2026-01-05", "2026-01-06"],
"visits": [100, 120, 90, 150],
})
print(raw["date"].dtype)
raw["date"] = pd.to_datetime(raw["date"])
print(raw["date"].dtype)
raw.set_index("date")["visits"].plot(marker="o")
plt.show()The first print shows object (text). The second shows datetime64[ns]. In the chart, the gap between January 2 and January 5 is wider than the gap between January 5 and January 6, because the x axis follows the calendar. With text labels, all gaps would look the same.
You can also parse dates while loading, for example pd.read_csv("file.csv", parse_dates=["date"], index_col="date"). That gives you a datetime index in one step.
Building a time series from scratch
pd.date_range creates a regular sequence of dates. It is handy for examples and for reindexing.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(1)
idx = pd.date_range("2026-01-01", periods=120, freq="D")
ts = pd.DataFrame(
{
"temp": 10 + np.cumsum(rng.normal(0, 1, 120)),
"baseline": 10.0,
},
index=idx,
)
ts.plot(title="Daily temperature")
plt.show()Both columns share the datetime index. The x axis shows month-level ticks because the data spans about four months. Pandas chooses the tick spacing for you and changes it if you plot a shorter or longer range.
Selecting a time range with slicing
A datetime index supports label slicing with partial date strings. Both ends are included.
ts.loc["2026-02"].plot(title="February only")
ts.loc["2026-02-10":"2026-03-05"].plot(title="Custom window")
plt.show()ts.loc["2026-02"] returns every row in February. Slicing like this requires a sorted index. If your data arrives out of order, call sort_index() first. Otherwise a slice can raise a KeyError or return the wrong rows, and the line will zigzag back and forth across the axis.
Resampling before you plot
Daily data over several years is noisy. resample groups rows into time bins, and you then apply an aggregation such as mean or sum. It is the time-based equivalent of groupby.
weekly = ts["temp"].resample("W").mean()
monthly = ts["temp"].resample("MS").mean()
ax = ts["temp"].plot(alpha=0.4, label="daily")
weekly.plot(ax=ax, label="weekly mean")
monthly.plot(ax=ax, label="monthly mean", marker="o")
ax.legend()
plt.show()This draws three series on one Axes by passing ax=ax to later calls. The label argument sets the legend text for a Series. The common frequency codes are listed below.
| Code | Meaning |
|---|---|
| `D` | Calendar day |
| `W` | Week, ending on Sunday |
| `MS` | Month, labeled by the month start |
| `QS` | Quarter, labeled by the quarter start |
| `YS` | Year, labeled by the year start |
Codes such as ME (month end) and YE (year end) are used in recent pandas versions. Older versions used M and Y. If your pandas version warns that a code is deprecated, switch to the newer spelling. Month start (MS) works in both.
Choose the aggregation to match the data. Use sum for counts and revenue. Use mean for temperatures and rates. Using sum on a rate gives a number with no meaning.
Smoothing with rolling windows
A rolling window averages the last N rows. It smooths a line without changing the number of points.
smooth = ts["temp"].rolling(window=7).mean()
ax = ts["temp"].plot(alpha=0.3, label="daily")
smooth.plot(ax=ax, label="7-day average", color="black")
ax.legend()
plt.show()The first six values of smooth are NaN because a full window is not yet available. Pandas skips those points, so the line starts a week later than the raw data. Pass min_periods=1 to rolling if you want a value from the first row.
Area charts and stacked time series
Area charts suit totals that are built from parts, such as traffic by source. Use kind="area" or .plot.area(). Area charts stack by default, so the top edge shows the total.
visits = pd.DataFrame(
{
"search": rng.integers(50, 100, 60),
"social": rng.integers(20, 60, 60),
"direct": rng.integers(10, 40, 60),
},
index=pd.date_range("2026-01-01", periods=60, freq="D"),
)
visits.plot.area(alpha=0.7, title="Visits by source")
plt.show()Pass stacked=False to overlay the areas instead. Keep alpha below 1 in that case so the lower series stays visible.
Missing dates and gaps
Real data often skips days. If a date is absent from the index, the line connects the neighbors across the gap. That can hide an outage. If a value is NaN, pandas leaves a break in the line instead.
To make missing dates visible, reindex to a full range:
sparse = ts["temp"].iloc[[0, 1, 2, 10, 11, 12]]
full = sparse.reindex(pd.date_range(sparse.index.min(), sparse.index.max(), freq="D"))
sparse.plot(marker="o", label="as stored")
full.plot(marker="x", linestyle="", label="reindexed")
plt.legend()
plt.show()The reindexed series has NaN for each missing day. With a line style you would see a break. To fill the gap instead, use full.interpolate() or full.ffill(), and say so in the chart title or caption so readers know the values are estimates.
Formatting the date axis
Pandas picks readable ticks, but you may want to change them. Use the returned Axes with matplotlib.dates.
import matplotlib.dates as mdates
ax = ts["temp"].plot(figsize=(8, 3))
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
ax.set_xlabel("")
plt.tight_layout()
plt.show()There is one important catch. For regular-frequency data, pandas uses its own tick system, and it can ignore or conflict with matplotlib.dates settings. If your ticks do not change, pass x_compat=True to plot. That tells pandas to use the standard matplotlib date handling.
ax = ts["temp"].plot(x_compat=True, figsize=(8, 3))
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
plt.show()If the date labels overlap, call plt.gcf().autofmt_xdate() to rotate them. You can also pass rot=45 to plot.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Evenly spaced points despite uneven dates | The index is text, not datetime | Use `pd.to_datetime` before `set_index` |
| Line jumps back and forth | The index is not sorted | Call `sort_index()` |
| `KeyError` on a date slice | Unsorted index, or the date is outside the range | Sort, and check `index.min()` and `index.max()` |
| `TypeError: no numeric data to plot` | The columns are strings, or the dates are still a column | Convert values with `pd.to_numeric` and check dtypes |
| Date tick settings have no effect | Pandas is using its own time ticks | Use `x_compat=True` |
| Resample raises `TypeError` | The index is not a `DatetimeIndex` | Convert and set the index first |
Summary of the workflow
- Convert the date column with
pd.to_datetime. - Set it as the index with
set_indexand sort it. - Slice with
locto the range you need. - Resample or roll to reduce noise.
- Plot with
df.plot(), usingax=to layer series. - Adjust ticks through the Axes, with
x_compat=Trueif needed.
Exercise
A DataFrame sales has a text column day with values like "2026-03-01", and a numeric column revenue with one row per day. Write the code that plots the monthly total revenue as a bar-free line with markers, with months labeled by their start date. Which resample code and aggregation do you use, and why?
Show answer
sales["day"] = pd.todatetime(sales["day"]); sales.setindex("day").sort_index()["revenue"].resample("MS").sum().plot(marker="o"). Use "MS" to bin by month with the label at the month start. Use sum because revenue is a total that should add up across days. Mean would give the average daily revenue instead.
Exercise
You call ts.plot() and then set a MonthLocator on the Axes, but the ticks do not change. What do you change?
Show answer
Pass xcompat=True to plot, for example ts.plot(xcompat=True). Pandas otherwise uses its own tick system for regular-frequency data and ignores the matplotlib locator.