Steve Lorimer
Steve Lorimer

Reputation: 28659

pandas/matplotlib datetime tick labels

I have a pandas dataframe with datetime values including microseconds:

                            column1    column2  
time                                                                        
1900-01-01 10:39:52.887916  19363.876  19362.7575   
1900-01-01 10:39:53.257916  19363.876  19362.7575   
1900-01-01 10:39:53.808007  19363.876  19362.7575   
1900-01-01 10:39:53.827894  19363.876  19362.7575   
1900-01-01 10:39:54.277931  19363.876  19362.7575   

I plot the dataframe as follows:

def plot(df):
    ax = df.plot(y='column1', figsize=(20, 8))
    df.plot(y='column2', ax=ax)

    ax.get_yaxis().get_major_formatter().set_useOffset(False)

    mpl.pyplot.show()

Notice on the image below that the microseconds are displayed as %f rather than their actual value.

That is, instead of 10:39:52.887916 it displays 10:39:52.%f

How can I display the actual microseconds in the tick labels (even if it's only a few significant digits)?

enter image description here

Upvotes: 0

Views: 2571

Answers (1)

CT Zhu
CT Zhu

Reputation: 54330

You should be able to set the major ticks to the format you want, using set_major_formatter:

In [14]:

import matplotlib as mpl
import matplotlib.dates
df = pd.DataFrame({'column1': [1,2,3,4],
                   'column2': [2,3,4,5]},
                   index =pd.to_datetime([1e8,2e8,3e8,4e8]))
def plot(df):
    ax = df.plot(y='column1', figsize=(20, 8))
    df.plot(y='column2', ax=ax)

    ax.get_yaxis().get_major_formatter().set_useOffset(False)
    ax.get_xaxis().set_major_formatter(matplotlib.dates.DateFormatter('%H:%M:%S.%f'))

    #mpl.pyplot.show()
    return ax

print df
                            column1  column2
1970-01-01 00:00:00.100000        1        2
1970-01-01 00:00:00.200000        2        3
1970-01-01 00:00:00.300000        3        4
1970-01-01 00:00:00.400000        4        5

enter image description here

If the problem do go away, then I think somewhere in the code the formatter format is specified incorrectly, namely %%f instead of %f, which returns a literal '%' character.

Upvotes: 2

Related Questions