Matplotlib: Add strings as custom x-ticks but also keep existing (numeric) tick labels? Alternatives to matplotlib.pyplot.annotate?


Question

I am trying to produce a graph and I am having some issues annotating it.

My graph has a log scale on the x-axis, showing time. What I want to be able to do is keep the existing (but not predictable) numeric tick labels at 100 units, 1000 units, 10000 units, etc but also add custom tick labels to the x-axis that make it clear where more "human readable" time intervals occur---for instance I want to be able to label 'one week', 'one month', '6 months', etc.

I can use matplotlib.pyplot.annotate() to mark the points but it doesn't really do what I want. I don't really want text and arrows on top of my graph, I just want to add a few extra custom tick marks. Any ideas?

1
18
6/23/2012 10:38:55 PM

Accepted Answer

If you really want to add extra ticks, you can get the existing ones using axis.xaxis.get_majorticklocs(), add whatever you want to add, and then set the ticks using axis.xaxis.set_ticks(<your updated array>).

An alternative would be to add vertical lines using axvline. The advantage is that you don't have to worry about inserting your custom tick into the existing array, but you'll have to annotate the lines manually.

Yet another alternative would be to add a linked axis with your custom ticks.

16
8/22/2015 6:32:10 AM

From http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks:

# return locs, labels where locs is an array of tick locations and
# labels is an array of tick labels.
locs, labels = xticks()

So all you should need to do is obtain the locs and labels and then modify labels to your liking (dummy example):

labels = ['{0} (1 day)','{0} (1 weak)', '{0} (1 year)']
new_labels = [x.format(locs[i]) for i,x  in enumerate(labels)]

and then run:

xticks(locs, new_labels)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon