Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

python 3.x - Formatting only selected tick labels

I'm new to matplotlib and trying to find out how can I change formatting only selected x tick labels. For simplicity, I attached below simple code and chart. How can I change font color of only last x tick label(5.0 in this example)?

Code
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4, 5], [50, 40, 60, 70, 50])
plt.show()

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can obtain the xticklabels via ax.get_xticklabels(). This returns a list of matplotlib.text.Text instances. You can then select one of them and use text.set_color("red") to colorize it.

ax.get_xticklabels()[-2].set_color("red")

enter image description here

The problem is that it's not intuitively clear which of the elements would be the one we are looking for. In this case it's the second last, since there is an empty ticklabel at the very end of the list. This may require to test a bit, or print them out before setting them. Also, if the plot is resized, such that more ticklabels appear on the axis, the formatted label might suddenly carry a different number than before. Such cases would require a bit more work to account for.


Of course, appart from the color you can change every attribute of the text instance you like,
ax.get_xticklabels()[-2].set_color("white")
ax.get_xticklabels()[-2].set_fontsize(14)
ax.get_xticklabels()[-2].set_weight("bold")
ax.get_xticklabels()[-2].set_bbox(dict(facecolor="red", alpha=0.9))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...