Skip to content
Advertisement

Matplotlib axline is vertical when it should be at an angle…until I change the dates/times for the chart

I’m trying to draw an angled line on a chart with Matplotlib, but there are times when it just draws a vertical line, incorrectly. It appears to be a problem with the dates/times. It’s like there’s a minimum time required between points before it will plot correctly. Can anyone shed any light on this?

JavaScript

Advertisement

Answer

The reason why this happens is quite tricky to get without digging a bit deeper. When converted using date2num, timestamps become decimal numbers like 19126.661111111112.

When drawing lines, matplotlib checks whether the points are “close” in the coordinate space with respect to their magnitude using the np.allclose() function. If they are close, the slope of the line is automatically set to np.inf and a vertical line is drawn. Now, in your case you can indeed see that under your threshold difference of 16526 seconds, the points are considered “close”:

JavaScript

If you test with bigger differences, this will print False. The solution in your case is to use a single point and the slope parameter and calculate the correct slope yourself:

JavaScript

And the line will be plotted correctly:

enter image description here

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