Till B
Till B

Reputation: 1328

matplotlib: change axes

I have an array of measurements m, taken every minute. I plot these measurements against time by simply saying

import pylab as pl
pl.plot(range(len(m)), m)

this gives me minutes on the x-axis (just because I have measurements in minutes and range(len(m)) gives me integers). How do I quickly change the labeling of the x-axis into hours? I basically need to take the labeling mod 60, but I would like to have only integer hour values.

So in short I want to relabel every multiple of 60 on the x-axis.

Upvotes: 2

Views: 5626

Answers (2)

GWW
GWW

Reputation: 44093

Sorry rather than xlabels you need to create an axis and us ax.set_xticklabels:

from matplotlib.pyplot import figure
fig = figure()
ax = fig.add_subplot(111)


def mk_labels(vals):
    labels = []
    for i in vals:
        if i % 60 == 0:
            labels.append("Some new special label")
        else:
            labels.append(i)


 ax.set_xticklabels(mk_labels(range(len(m))))
 ax.plot(range(len(m)), m)

or simply:

 ax.set_xticklabels(["{0}h".format(i) if i % 60 == 0 else i for i in range(len(m))])

Either of these methods will work the first one may be easier if you need more complicated formatting.

Upvotes: 3

Dunes
Dunes

Reputation: 40693

pylab.plot(data) # pylab will automatically add an x-axis from 0 to len(data) - 1

# first argument is when ticks should appear on the x-axis
# the second argument is what the label for each tick should be
# same as -> pylab.xticks([0, 60, 120...], [0, 1, 2...])
pylab.xticks(range(0, len(data), 60), range(len(data)/60))

# let the reader know the units
pylab.xlabel("hours")

Upvotes: 2

Related Questions