Search code examples
pythonmatplotlibgraphaxis-labels

How to get the text of the label from the axis ticks using matplotlib?


The fact is that I try to filter the ticks I'm showing on the xaxis by comparing their label to a regular expression. I'm currently "filtering" by taking only one on sixty of them. But, as I'm playing with non periodic functions while willing to emphasize a certain phenomenon, I need to be able to get the label of the tick. In order to do that, I need to be able to put the "value" of the label in a variable. But I don't know how to get the Text. I've tried the get_text() method, but all I get is an empty String. Here is the part of my code which I think is relevant here, ask me if you think you need some precisions :

    for index, label in enumerate(ax.xaxis.get_ticklabels()):
        if index % (2*30) != 0:
            label.set_visible(False)
        else:
            print(label.get_text())
    for index, tick in enumerate(ax.xaxis.get_ticklines()):
        if index % (4*30) != 0:
            tick.set_visible(False)

Here, an example using the Bitcoin value over 2 years, with the x-axis graduated every 60 days. As I can't get the value of the label, I can't focus on the first day of each month for example. Thanks to all the people who will read me, and if you've got an answer, please tell me!!


Solution

  • Well, in fact trying to get the text from the label wasn't this relevant. Because this text is the value of the x-value. So, I was basically trying to get the x-value by another way... This is the code I came up with :

    for index, label in enumerate(ax.xaxis.get_ticklabels()):
        if re.findall(".*-.[13579]-0[2-9]", dateList[index]) or re.findall(".*-.[13579]-[123].", dateList[index]) or re.findall(".*-.[02468]-.*", dateList[index]):
            label.set_visible(False)
    for index, tick in enumerate(ax.xaxis.get_ticklines()):
        if index % (4*30) != 0:
            tick.set_visible(False)
    

    Result, illustrated with the Bitcoin value over 2 years, where the x-axis is graduated every 2 months