Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 57 ยท Working with Data

Dates and Time Series Charts

Plot dates on the x axis with datetime and pandas, format ticks with mdates, add rolling averages, shade date ranges and handle gaps.

Time is the most common x axis in the real world: sales per day, temperature per hour, users per month. Matplotlib can draw dates, but dates are not plain numbers, so you need to know how it turns them into positions and how to control the tick labels. Without that knowledge you get either overlapping labels or an axis that says "2026" a dozen times in a row.

This lesson covers plotting datetime objects and pandas timestamps, choosing tick locations and formats with matplotlib.dates, rotating labels, smoothing with rolling averages, shading ranges such as weekends or campaigns, plotting resampled data and handling gaps and irregular timestamps. A first look at dates is in Plotting NumPy and pandas Data.

Dates on an axis

Plot dates Pass datetime or Timestamp as x.
Locators Decide where the ticks go.
Formatters Decide how the ticks read.

Matplotlib converts dates to numbers behind the scenes.

1 / 2

Plotting dates

Pass Python datetime objects, NumPy datetime64 values or pandas Timestamp values as x, and Matplotlib detects them and installs a date axis. Under the hood a date becomes a float: the number of days since 1970-01-01. You rarely need that number, but it explains why date axes accept the same set_xlim calls as any other axis, as long as you give them dates.

Python Dates on the x axis

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Matplotlib picks a locator and formatter automatically (the "concise" converter, if you ask for it, is even tighter). The automatic choice is good, so start with it and only override what bothers you.

Locators and formatters from mdates

matplotlib.dates provides the tools. A locator decides where ticks go; a formatter decides what each tick label says. Both attach to an axis with set_major_locator and set_major_formatter. The most useful ones:

Locator Tick every
mdates.DayLocator(interval=7) 7 days
mdates.WeekdayLocator(byweekday=mdates.MO) every Monday
mdates.MonthLocator() first of each month
mdates.YearLocator() start of each year
mdates.AutoDateLocator() whatever fits (the default)

A formatter takes a strftime pattern: mdates.DateFormatter("%b %d") gives Mar 09, "%Y-%m" gives 2026-03, "%a" gives the weekday name.

Python Mondays as major ticks, days as minor ticks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Major ticks carry labels and a visible grid; minor ticks mark every day without text. For a multi-year chart, use YearLocator() for majors and MonthLocator() for minors with a "%Y" formatter. See Ticks, Locators and Formatters for the same ideas on number axes.

Rotating and shortening labels

Long dates collide. You have three fixes, in order of preference:

  1. Fewer ticks. Use a coarser locator, such as weekly rather than daily.
  2. Shorter format. "%b %d" is much shorter than "%Y-%m-%d %H:%M".
  3. Rotation. ax.tick_params(axis="x", rotation=45) or fig.autofmt_xdate(), which rotates and right-aligns for you.

There is also mdates.ConciseDateFormatter, which shows the year or month only once where it changes and keeps the rest short. It is a good default for time series with unknown ranges.

Python ConciseDateFormatter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the labels: hours show as 06:00, and the day appears only at midnight, so nothing repeats. Constrained layout reserves room for the labels without calling autofmt_xdate.

Rolling averages

Raw daily data is jagged. A rolling average replaces each value with the mean of a window of neighbors. With pandas it is one line: series.rolling(7).mean(). Plot the raw data faintly and the average strongly so readers see both noise and trend. center=True aligns the average with the middle of the window rather than its end, which matters when you compare peaks to events.

Python Raw values and rolling means

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line prints NaN at the edges: 27: a centered window of 28 cannot be computed for the first 14 and last 13 points, so those points are simply not drawn. Bigger windows smooth more but react later and lose the edges.

Shading ranges

ax.axvspan(start, end) fills a vertical band between two dates, and ax.axvline(date) draws a single line. Use them to show weekends, campaigns, outages or forecasts. Put the shading behind the data with a low alpha and zorder=0.

Python Shaded weekends and an event

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Weekend bands run Saturday midnight to Monday midnight. Because x-values are dates, the width of a band is a Timedelta, not a number.

Resampled plots

Often the question is "per month?" not "per day?". Pandas resample groups a datetime-indexed series into regular buckets ("W" weekly, "MS" month start, "QS" quarter start) and applies an aggregate such as sum or mean. Plot daily data as a light step or line and the aggregate as bars in front of it.

Python Daily data resampled to months

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When you plot bars against dates, width is measured in days, so width=20 fits a month. Pass align="center" to put each bar at its month start, or shift them by 15 days if you prefer to center on the month. For averages use .mean(); for totals use .sum(). Compare partial months carefully, since an incomplete month looks like a drop.

Gaps and irregular series

Real data has holes: sensors fail, shops close. If you plot such data, Matplotlib connects neighboring points with a straight line and hides the fact that anything is missing. Two techniques keep the chart honest.

  • NaN values break the line. Insert np.nan where data is missing (or use series.asfreq("D"), which adds the missing days as NaN) and Matplotlib draws a gap.
  • Irregular timestamps are fine. Dates are real numbers on the axis, so unevenly spaced points sit at the right distance apart. Markers make irregular sampling visible.
Python Missing data and uneven sampling

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first print shows rows kept: 33 (7 days dropped) and the second missing after asfreq: 7. The dotted line draws a confident bridge across the missing week, while the solid line stops and restarts, which tells the truth. If you must interpolate, say so in the title or a note.

Time zones and other gotchas

  • Mixing timezone-aware and naive datetimes raises an error; convert first with pandas tz_localize and tz_convert.
  • Strings are not dates. A column of "2026-03-01" strings plots as categories in order of appearance. Convert with pd.to_datetime(...) before plotting.
  • set_xlim needs dates, not numbers, on a date axis. A common mistake is set_xlim(0, 30), which puts you in 1970.
  • Matplotlib date numbers count days from 1970-01-01 in current versions; if you ever see tiny numbers on a date axis, the data was not recognized as dates.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which locator puts a major tick on every Monday?

    WeekdayLocator with byweekday=mdates.MO places ticks on Mondays only.
  2. 2. Which formatter produces labels like "Mar 09"?

    %b is the abbreviated month name and %d the day of the month, so the pattern %b %d gives Mar 09. A locator never formats labels.
  3. 3. What happens to a plotted line where the data contains NaN?

    Matplotlib skips NaN values, so the line stops and restarts, which honestly shows missing data.
  4. 4. Why is a column of date strings such as "2026-03-01" a problem for a time axis?

    Strings become evenly spaced categories in order of appearance. Convert them with pd.to_datetime so spacing follows real time.
  5. 5. What does center=True do in series.rolling(7, center=True).mean()?

    With center=True the result at a date uses values before and after it, so smoothed peaks line up with real events rather than lagging behind them.

Summary

  • Pass datetime, datetime64 or pandas Timestamp values as x and Matplotlib builds a date axis.
  • Locators (DayLocator, WeekdayLocator, MonthLocator, YearLocator) choose tick positions; DateFormatter and ConciseDateFormatter choose labels.
  • Fix crowded labels with fewer ticks, shorter formats, rotation or fig.autofmt_xdate().
  • Plot raw data faintly and a rolling mean boldly; windows leave NaN at the edges.
  • axvspan and axvline shade ranges and mark events using dates.
  • resample aggregates to weeks or months; bar width on a date axis is in days.
  • Missing data should show as gaps (NaN), and irregular timestamps keep their true spacing.

Next: Seaborn-Style Recipes in Pure Matplotlib