Formatting only selected tick labels

后端 未结 1 435
日久生厌
日久生厌 2020-12-10 07:13

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 chan

相关标签:
1条回答
  • 2020-12-10 07:48

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

    0 讨论(0)
提交回复
热议问题