Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minute and second format for x label of matplotlib

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?

like image 349
Dzung Nguyen Avatar asked Nov 03 '16 06:11

Dzung Nguyen


People also ask

How do you space out the x-axis labels in Python?

To increase the space for X-axis labels in Matplotlib, we can use the spacing variable in subplots_adjust() method's argument.

What does %Matplotlib mean in Python?

What Does Matplotlib Mean? Matplotlib is a plotting library available for the Python programming language as a component of NumPy, a big data numerical handling resource. Matplotlib uses an object oriented API to embed plots in Python applications.


1 Answers

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

like image 120
Martin Evans Avatar answered Oct 13 '22 01:10

Martin Evans