Friday 23 July 2021

Matplotlib: make objects ignored by axis autoscaling

Is it possible to create a plot object that is ignored by the Axes autoscaler?

I often need to add vertical lines, or shade a region of a plot to show the desired range of data (as a frame of reference for the viewer), but then I have to set the axes auto-scales x/ylimits back to where they were before - or truncate the lines/shading to the current axis limits, or various other fandangos.

It would be much easier if these shader/vertical lines acted as "background" objects on the plot, ignored by the autoscaler, so only my real data affected the autoscale.

Here's an example: This plot is of real-world data, and I want to see if the data is within desired limits from day to day.

Current image showing vertical lines pushed the auto-scaling outwards

I want to shade the 3rd axis plot from -50 nm ≤ Y ≤ +50 nm. I'd love to simply add a giant translucent rectangle from -50 --> +50nm, but have the autoscale ignore it. Eg. like this (I manually added the red shading in a drawing prog.): Red-shading desired on Ax3, from -50 --> +50nm

Also, you can see I've manually added vertical lines using code like this (I should really just use the vertical gridline locations...):

ax1.set_ylim(ymin, ymax)
ax1.vlines( self.Dates , color="grey", alpha=0.05, ymin=ax1.get_ylim()[0], ymax=ax1.get_ylim()[1] )

You can see in the 2nd & 3rd axes, that the VLines pushed the AutoScaling outwards, so now there's a gap between the VLine and Axis. Currently I'd need to finagle the order of calling fig.tight_layout() and ax2/ax3.plot(), or convert to manually setting the X-Tick locations/gridlines etc. - but it would be even easier if these VLines were not even treated as data, so the autoscale ignored them.

Is this possible, to have autoscale "ignore" certain objects?



from Matplotlib: make objects ignored by axis autoscaling

No comments:

Post a Comment