@@ -908,6 +908,79 @@ def axvline(self, x=0, ymin=0, ymax=1, **kwargs):
908
908
self .autoscale_view (scalex = scalex , scaley = False )
909
909
return l
910
910
911
+ @docstring .dedent_interpd
912
+ def axline (self , xy1 , xy2 , ** kwargs ):
913
+ """
914
+ Add an infinitely long straight line that passes through two points.
915
+
916
+ Parameters
917
+ ----------
918
+ xy1, xy2 : (float, float)
919
+ Points for the line to pass through.
920
+
921
+ Returns
922
+ -------
923
+ :class:`~matplotlib.lines.Line2D`
924
+
925
+ Other Parameters
926
+ ----------------
927
+ Valid kwargs are :class:`~matplotlib.lines.Line2D` properties,
928
+ with the exception of 'transform':
929
+
930
+ %(_Line2D_docstr)s
931
+
932
+ Examples
933
+ --------
934
+ * Draw a thick red line passing through (0, 0) with a gradient of 1::
935
+
936
+ >>> axline((0, 0), (1, 1), linewidth=4, color='r')
937
+
938
+
939
+ See Also
940
+ --------
941
+ axhline : for horizontal lines
942
+ axvline : for vertical lines
943
+
944
+ Notes
945
+ -----
946
+ Currently this method does not work properly with non-linear axes.
947
+ """
948
+ if not self .get_xscale () == self .get_yscale () == 'linear' :
949
+ raise NotImplementedError ('axline() is only supported on '
950
+ 'linearly scaled axes' )
951
+
952
+ if "transform" in kwargs :
953
+ raise TypeError ("'transform' is not allowed as a kwarg; "
954
+ "axline generates its own transform." )
955
+
956
+ x1 , y1 = xy1
957
+ x2 , y2 = xy2
958
+ # If x values the same, we have a vertical line
959
+ if np .allclose (x1 , x2 ):
960
+ if np .allclose (y1 , y2 ):
961
+ raise ValueError (
962
+ 'Cannot draw a line through two identical points '
963
+ f'(got x1={ x1 } , x2={ x2 } , y1={ y1 } , y2={ y2 } ).' )
964
+ line = self .axvline (x1 , ** kwargs )
965
+ return line
966
+
967
+ slope = (y2 - y1 ) / (x2 - x1 )
968
+ intercept = y1 - (slope * x1 )
969
+
970
+ xtrans = mtransforms .BboxTransformTo (self .viewLim )
971
+ viewLimT = mtransforms .TransformedBbox (
972
+ self .viewLim ,
973
+ mtransforms .Affine2D ().rotate_deg (90 ).scale (- 1 , 1 ))
974
+ ytrans = (mtransforms .BboxTransformTo (viewLimT ) +
975
+ mtransforms .Affine2D ().scale (slope ).translate (0 , intercept ))
976
+ trans = mtransforms .blended_transform_factory (xtrans , ytrans )
977
+
978
+ line = mlines .Line2D ([0 , 1 ], [0 , 1 ],
979
+ transform = trans + self .transData ,
980
+ ** kwargs )
981
+ self .add_line (line )
982
+ return line
983
+
911
984
@docstring .dedent_interpd
912
985
def axhspan (self , ymin , ymax , xmin = 0 , xmax = 1 , ** kwargs ):
913
986
"""
0 commit comments