1

I'm trying to plot some data from a pandas dataframe with a timedelta index and I want to customize the time ticks and labels in my x-axis. This should be simple but it's proving to be a tough job.

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

## I have a df similar to this
timestamps = pd.date_range(start="2017-05-08", freq="10T", periods=6*6)
timedeltas = timestamps - pd.to_datetime("2017-05-08")
yy = np.random.random((len(timedeltas),10))
df = pd.DataFrame(data=yy, index=timedeltas)  # Ok, this is what I have

## Now I want to plot this but I want detailed control of the plot so I use matplotlib instead of df.plot
fig,axes=plt.subplots()
axes.plot(df.index.values, df.values)
#axes.plot_date(df.index, df.values, '-')

axes.xaxis.set_major_locator(dates.HourLocator(byhour=range(0,24,2)))
axes.xaxis.set_minor_locator(dates.MinuteLocator(byminute=range(0,24*60,10)))
axes.xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))

plt.show()

As you can see, the ticks are not even showing up. How can I add major ticks and labels every two hours and minor ticks every 10 minutes, for example?

Bella
  • 181
  • 2
  • 11

1 Answers1

4

Although I don't know exactly what the root issue is, it seems that it is related to the used package versions. When I run your example with an older python distribution (matplotlib 1.5.1, numpy 1.11.1, pandas 0.18.1 and python 2.7.12), then I get a plot without ticks just as you described.

However I can get a plot with the correct ticks

plot with correct ticks

by running the code below with a recent python distribution (matplot 2.0.1, numpy 1.12.1, pandas 0.19.1 and python 3.6.1).

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

timestamps = pd.date_range(start="2017-05-08", freq="10T", periods=6*6)
timedeltas = timestamps - pd.to_datetime("2017-05-08")
yy = np.random.random((len(timedeltas),10))
df = pd.DataFrame(data=yy, index=timedeltas)

fig,axes=plt.subplots()
axes.plot_date(df.index, df.values, '-')

axes.xaxis.set_major_locator(dates.HourLocator(byhour=range(0,24,2)))
axes.xaxis.set_minor_locator(dates.MinuteLocator(byminute=range(0,24*60,10)))
axes.xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))

plt.show()
Xukrao
  • 8,003
  • 5
  • 26
  • 52
  • Thanks for checking that. Maybe you want to look at this one too: https://stackoverflow.com/questions/43859823/heatmap-in-which-one-of-the-axis-is-of-timedelta-type – Bella May 09 '17 at 12:20
  • 1
    This fails for me with Python 3.6.4 (64 bit), pandas 0.22.0, numpy 1.14.2, and matplotlib 2.2.2 – David Folkner Apr 26 '18 at 16:03