Home > Software design >  Remove specific tick markers of a matplotlib plot, how?
Remove specific tick markers of a matplotlib plot, how?

Time:06-01

I have the following problem: I am creating a plot, in which I want to hide only certain x-axis ticks labels which satisfy a condition (supposing ax is defined above):

xticks = ax.xaxis.get_major_ticks()
for x_tick, y_tick in ax.get_lines()[0].get_xydata():
    if y_tick > -0.5:
        xticks[ int(x_tick) ].label1.set_visible( False )

The problem is that in this way I obtain something like this (can't show full plot for privacy, I will put only x-axis screenshot):

enter image description here

Since the number of xticks is really high (more than 1500 more or less). And with the previous code I am able to hide only the labels, but not the markers.

Is there a way to remove specific tick "notches" (I don't know how to call them) or markers in order to remove this horrible black line in the x-axis? Thanks.

CodePudding user response:

You could manually set which x_ticks should be in the plot by explicitly saving the location and the text as following:

xticks = ax.xaxis.get_major_ticks()
visible_xticks_locs = []
visible_xticks_labels = []
for x_tick, y_tick in ax.get_lines()[0].get_xydata():
    if y_tick > -0.5:
        visible_xticks_locs.append(int(x_tick)) 
        visible_xticks_labels.append(xticks[int(x_tick)])
ax.set_xticks(ticks=visible_xticks_locs, labels=visible_xticks_labels)
  • Related