1

I have a set of ticklabels that are strings on my x axis, and I want to be able to get -> modify -> set them. Say for example I have a plot that looks like this:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(1,6), range(5))
plt.xticks(range(1,6), ['a','b','c','d','e']

and I want to change the labels on the x axis to ['(a)','(b)','(c)','(d)','(e)']

what is the simplest/best way to do this? I've tried things like:

labels = ['(%s)' % l for l in ax.xaxis.get_ticklabels()]
ax.xaxis.set_ticklabels(labels)

but ax.xaxis.get_ticklabels() returns matplotlib Text objects as opposed to a list of strings and I'm not sure how to go about modifying them. I also tried using matplotlib.ticker.FuncFormatter but could only get a hold of the numeric positions not the labels themselves. Any would be appreciated.

1 Answer 1

5

One more layer to unpeel:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(1,6), range(5))
plt.xticks(range(1,6), ['a','b','c','d','e'])

labels = ['(%s)' % l.get_text() for l in ax.xaxis.get_ticklabels()]
ax.xaxis.set_ticklabels(labels)

your code but with l.get_text() in the list comp where there was a l.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow I was looking through the Text object methods and completely missed that one... Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.