Skip to content
Advertisement

Wrong labels when plotting a time series pandas dataframe with matplotlib

I am working with a dataframe containing data of 1 week.

JavaScript

I create a new index by combining the weekday and time i.e.

JavaScript

The plot of this data is the following: Weekly data The plot is correct as the labels reflect the data in the dataframe. However, when zooming in, the labels do not seem correct as they no longer correspond to their original values: Wrong labels when zooming What is causing this behavior?

Here is the code to reproduce this:

JavaScript

Advertisement

Answer

“What is causing this behavior?”

The formatter of an axes of a pandas dates plot is a matplotlib.ticker.FixedFormatter (see e.g. print plt.gca().xaxis.get_major_formatter()). “Fixed” means that it formats the ith tick (if shown) with some constant string.

When zooming or panning, you shift the tick locations, but not the format strings.
In short: A pandas date plot may not be the best choice for interactive plots.

Solution

A solution is usually to use matplotlib formatters directly. This requires the dates to be datetime objects (which can be ensured using df.index.to_pydatetime()).

JavaScript

enter image description here

Advertisement