Search code examples
pythonpandasnumpymatplotlibtimedelta

How to change xticklables from pandas plot with timedelta x-axis?


I am trying to plot this dataframe:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


df = pd.DataFrame({'d': [np.timedelta64(5,'h'), np.timedelta64(7,'h')],
                 'v': [100,200]})

ax = df.set_index('d').plot.bar()

Which looks like this: enter image description here

Here, I would like to remove "days 0 " from the xticklabels.

Here is my attempt:

ax = df.set_index('d').plot.bar()
locs, labels = plt.xticks()

for l in labels:
    print(l)

# gives
Text(0, 0, '0 days 05:00:00')
Text(0, 0, '0 days 07:00:00')

Also,

xlabels = [l for l in ax.get_xticklabels()]
# [Text(0, 0, '0 days 05:00:00'), Text(1, 0, '0 days 07:00:00')]

But when I try to change: xlabels[0][2] = str(xlabels[0][2]).lstrip('days 0 ')

I get following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-2e745c3160f9> in <module>()
----> 1 lst[0][2]

TypeError: 'Text' object does not support indexing

How to fix the error? or as a whole, how to change the xticklables in this plot?


Solution

  • This should work:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib.pyplot import text as TEXT
    
    
    df = pd.DataFrame({'d': [np.timedelta64(5,'h'), np.timedelta64(7,'h')],
                     'v': [100,200]})
    
    
    ax = df.set_index('d').plot.bar()
    xlabels = [l for l in ax.get_xticklabels()]
    
    newlabels = []
    for xlabel in xlabels:
        x,y = xlabel.get_position();
        lbl = xlabel.get_text().lstrip('0 days ');
        text = TEXT(x, y, lbl,visible=False);
        newlabels.append(text)
    
    ax.set_xticklabels(newlabels)
    

    output

    enter image description here