仅格式化选定的刻度标签

仅格式化选定的刻度标签

本文介绍了仅格式化选定的刻度标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 matplotlib 的新手,并试图找出如何仅更改选定的 x 刻度标签的格式.为简单起见,我在下面附上了简单的代码和图表.如何更改仅最后一个x刻度标签的字体颜色(在此示例中为5.0)?

 代码导入matplotlib.pyplot作为plt无花果,ax = plt.subplots()ax.plot([1, 2, 3, 4, 5], [50, 40, 60, 70, 50])plt.show()
解决方案

您可以通过 ax.get_xticklabels()获得xticklabel.这将返回

问题在于,直觉上不清楚哪个元素是我们要寻找的元素.在这种情况下,它是倒数第二个,因为列表的末尾有一个空的ticklabel.这可能需要测试一下,或在设置它们之前将其打印出来.同样,如果调整图的大小,使更多的刻度标签出现在轴上,则格式化的标签可能突然带有与以前不同的数字.这种情况需要做更多的工作来解决.

当然,从颜色上来说,appart可以更改您喜欢的 text 实例的每个属性

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))

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()
解决方案

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")

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))

这篇关于仅格式化选定的刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:57