6

How do I show mm:ss instead of sample numbers in the following diagram?

enter image description here

I tried:

def formatMS(miliseconds):
    return time.strftime('%M:%S', time.gmtime(miliseconds//1000))

fig, ax = plt.subplots()
plt.plot(segtime, segStrength)
labels = [formatMS(t) for t in segtime]
print labels
ax.set_xticklabels(labels)

But now it is showing all 00:00. How do I fix this problem?

Dzung Nguyen
  • 3,794
  • 9
  • 48
  • 86
  • You are creating labels for each of your data points. So you end up with let's say 10000 labels, but your x-axis only shows nine ticks. What matplotlib does is assigning the first nine entries of your list of labels to these ticks. You could either set the labels amnuallay or (probably a better solution) try converting your time axis to `datetime.datetime`, then matplotlib will handle the ticks. See also here: http://stackoverflow.com/questions/19079143/how-to-plot-time-series-in-python – Sven Rusch Nov 03 '16 at 08:40

1 Answers1

12

As an alternative to setting the labels, you could use a tick formatter as follows:

import matplotlib
import matplotlib.pyplot as plt
import time


segtime = [1000, 2000, 3000, 3500, 7000]
segStrength = [10000, 30000, 15000, 20000, 22000]    

fig, ax = plt.subplots()
plt.plot(segtime, segStrength)

formatter = matplotlib.ticker.FuncFormatter(lambda ms, x: time.strftime('%M:%S', time.gmtime(ms // 1000)))
ax.xaxis.set_major_formatter(formatter)

plt.show()

This will then convert a tick into the format you need, giving you:

tick conversion

Martin Evans
  • 45,791
  • 17
  • 81
  • 97