Home > Mobile >  Setting ticks every minute with MinuteLocator for pandas.DataFrame.plot gives "OverflowError: i
Setting ticks every minute with MinuteLocator for pandas.DataFrame.plot gives "OverflowError: i

Time:10-02

Setting minute minor ticks for 1-second sampled data raises: OverflowError: int too big to convert

Consider this dataframe with a sample interval of 1 second that spans about 30 minutes:

import matplotlib.pyplot as plt
from matplotlib.dates import MinuteLocator
import pandas as pd

ndex = pd.date_range('2021-08-01 07:07:07', '2021-08-01 07:41:12', freq='1S', name='Time') 
df = pd.DataFrame(data=np.random.randint(1, 100, len(ndex)), index=ndex, columns=['A'])

And now we plot it:

fig, ax = plt.subplots()
df.plot(color='red', marker='x', lw=0, ms=0.2, ax=ax)

Which creates a plot without any complaints: time vs randint

Now I'd like to have minor ticks at every minute.

I've tried this:

ax.xaxis.set_minor_locator(MinuteLocator())

But that fails with OverflowError: int too big to convert

CodePudding user response:

  • enter image description here

    pandas.DataFrame.plot.scatter

    • Also pandas.DataFrame.plot with kind='scatter'
      • ax = df.reset_index().plot(kind='scatter', x='Time', y='A', color='red', marker='x', figsize=(25, 6), rot=90)
    # reset the index so Time will be a column to assign to x
    ax = df.reset_index().plot.scatter(x='Time', y='A', color='red', marker='x', figsize=(25, 6), rot=90)
    ax.xaxis.set_major_locator(mdates.MinuteLocator())
    

    enter image description here


    • Note the difference in the xticks produced by the two methods

    pandas.DataFrame.plot xticks

    ax = df.plot(color='red', marker='x', lw=0, ms=0.2, figsize=(25, 6))
    
    ticks = ax.get_xticks()
    print(ticks)
    [out]:
    array([1627801627, 1627803672], dtype=int64)
    

    matplotlib.pyplot.scatter xticks

    fig, ax = plt.subplots(figsize=(25, 6))
    ax.scatter(x=df.index, y=df.A, color='red', marker='x')
    
    ticks2 = ax.get_xticks()
    print(ticks2)
    
    [out]:
    array([18840.29861111, 18840.30208333, 18840.30555556, 18840.30902778,
           18840.3125    , 18840.31597222, 18840.31944444])
    
  • Related