Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Matplotlib Datetime Axis with Log Scale and Secondary Axis

Convert Python datetimes to numeric values with `matplotlib.dates.date2num`, plot them on a log scale, and use a secondary axis for readable date labels. Includes examples for a secondary y-axis and common pitfalls.

~3 min readPython
#matplotlib#datetime#log scale#secondary axis
A matplotlib plot with a datetime x-axis on a log scale and a secondary axis on the right showing a second series.

Matplotlib converts datetime objects to numeric values internally when it builds a date axis. A log scale requires numeric axis data, so the reliable way to combine a datetime axis with a log scale is to convert datetime objects to numbers yourself with matplotlib.dates.date2num, plot those numbers, and add a secondary axis when you want readable date labels.

Convert datetime values to numbers for a log scale

date2num returns a floating-point number of days since 0001-01-01 UTC. For ordinary datetime values these numbers are positive, so they can be used with a log scale.

python
import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime dates = [datetime(2023, 1, 1), datetime(2023, 2, 1), datetime(2023, 3, 1)] values = [10, 100, 1000] # Convert dates to numeric values numeric_dates = mdates.date2num(dates) fig, ax = plt.subplots() ax.plot(numeric_dates, values) ax.set_xscale('log') plt.show()

This plot has a log-scaled x-axis, but the tick labels are numeric day counts rather than dates. The next section restores date labels.

Add a secondary x-axis for date labels

A secondary x-axis can carry the date labels while the primary axis keeps the numeric log scale. This separates the numeric transformation from the display formatting.

python
import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime dates = [datetime(2023, 1, 1), datetime(2023, 2, 1), datetime(2023, 3, 1)] values = [10, 100, 1000] numeric_dates = mdates.date2num(dates) fig, ax = plt.subplots() ax.plot(numeric_dates, values) ax.set_xscale('log') # Create a secondary x-axis for date labels secax = ax.secondary_xaxis('top') secax.set_xlim(ax.get_xlim()) secax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) secax.xaxis.set_major_locator(mdates.MonthLocator()) plt.show()

The secondary axis draws date labels above the plot, aligned with the same numeric positions. Use a MonthLocator() when your data points are months apart; adjust the locator for your own date spacing.

Add a secondary y-axis for a second data series

A secondary y-axis is independent of the log-scale issue, but it can be combined with the same setup. Use twinx() when a second series has a different range or unit.

python
import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime dates = [datetime(2023, 1, 1), datetime(2023, 2, 1), datetime(2023, 3, 1)] values1 = [10, 100, 1000] values2 = [0.5, 0.2, 0.1] numeric_dates = mdates.date2num(dates) fig, ax1 = plt.subplots() ax1.plot(numeric_dates, values1, color='blue') ax1.set_xscale('log') ax1.set_ylabel('Primary series') ax2 = ax1.twinx() ax2.plot(numeric_dates, values2, color='orange') ax2.set_ylabel('Secondary series') secax = ax1.secondary_xaxis('top') secax.set_xlim(ax1.get_xlim()) secax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) secax.xaxis.set_major_locator(mdates.MonthLocator()) plt.show()

Here the x-axis is numeric and log-scaled, a secondary x-axis supplies date labels, and twinx() gives the second series its own y-axis.

Common pitfalls

  • Zero or negative numeric dates. A log scale cannot handle zero or negative values. date2num is positive for datetime values in the Common Era. If you use another numeric representation, such as Unix epoch seconds, dates before 1970 are negative and log scaling will fail.
  • Date formatter without a date locator. Applying a DateFormatter directly to a log-scaled axis can format the log locator's arbitrary numeric ticks as odd dates. Set an explicit locator or use a secondary axis.
  • Misaligned labels. If you create a secondary x-axis, keep its limits synchronized with the primary axis. If the limits drift, the date labels will no longer line up with the data.

Use a secondary axis or a custom formatter?

A secondary x-axis is the cleanest approach when you need deliberate date labels on a log-scaled plot. It keeps the numeric log axis and the date formatting independent. A custom formatter is simpler, but it depends on the log locator choosing ticks that happen to fall on meaningful dates.

ApproachProsCons
Secondary x-axisIndependent tick placement and formattingRequires another axis and synchronized limits
Custom formatterLess code, no extra axisTick positions may not match dates

Practical considerations for production plots

A log scale emphasizes multiplicative changes, not equal time spans. This can be misleading for time series data, so label the axis clearly or explain the scale in a figure caption.

When you use date2num, the values are days since 0001-01-01. If you switch to a different numeric representation, make sure all values are positive before applying a log scale.

If you change the primary axis limits after creating the secondary axis, update the secondary axis limits too. You can automate this by connecting to the xlim_changed event with ax.callbacks.connect.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.