Skip to content
Advertisement

Avoid annotations and tick y_tick labels overlapping

I went through several questions but none seem to address the problem of annotations overlapping with y tick labels. I found a nice code that prevents annotations overlapping among themselves, but nothing with tick labels.

My problem is quite simple actually. I use the following lines to create the graph I paste just below them. I use annotate to show what the last value for both lines is. I set the position of the annotation based on the ratio of the last value to the total range of the y axis. It works pretty well except when the annotation overlaps the tick label. It is not that big a deal but it does not look nice when including the graph in a report.

Here is the code — I ommit the lines that manipulate the data:

JavaScript

Here is the graph. Highlighted in yellow what I would like to fix: enter image description here

As noted in the comment below, I would like the red label to either be above (preferably since it’s a higher number) or below the tick label). I know how to take it far to the right or to the left. I also know how to move it manually up or down. Is there a way to have Matplotlib check if it overlaps with the tick label and automatically move it up or down?

Advertisement

Answer

I thought it would be a good idea to complete the post with the solution I found thanks to the above comments. I went for the third option in Jody Klymak’s comment.

I added a few lines to find what the y_ticks are, remove any ticks within a specific range around the last value, and finally set new y_ticks.

Updated code:

JavaScript

Updated chart:

enter image description here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement