概述
axline
函数作用是绘制一条无限长的直线。与 axvline/axhline
相比,axline
函数绘制的直线长度是无限的,直线可以是任意角度的直线。
axline
函数的签名为:
matplotlib.pyplot.axline(xy1, xy2=None, *, slope=None, **kwargs)
其中:
xy1
:直线贯穿的点的坐标。浮点数二元组(float, float)
。xy2
:直线贯穿的点的坐标。浮点数二元组(float, float)
。默认值为None
。xy2
和slope
同时只能有一个值有效。两者既不能同时为None
,也不能同时为非空值。slope
:直线的斜率。浮点数,默认值为None
。**kwargs
:除'transform'
之外的Line2D
属性。
axline
函数有两种应用模式:
axline(xy1, xy2)
axline(xy1, slope)
axline
函数的返回值为Line2D
对象。
案例:演示axline
函数
import matplotlib.pyplot as plt
plt.figure(figsize=(12,3.5))
# 演示参数xy1, xy2
plt.subplot(131)
plt.axline((0, 0), (1, 1))
plt.subplot(132)
# 演示参数xy1, slope
plt.axline((0, 0), slope=1)
plt.subplot(133)
# 演示**kwargs参数
plt.axline((0, 0), (1, 1), linewidth=2, color="r",marker='o')
plt.show()
xy2
和slope
参数关系解析
根据axline()
源码可知,_to_points(xy1, xy2, slope)
函数首先检查参数的组合情况,xy2
和slope
同时为None
或非None
值,抛出错误。如果xy2
为None
,则根据slope
参数生成xy2
参数。
def _to_points(xy1, xy2, slope):
"""
Check for a valid combination of input parameters and convert
to two points, if necessary.
"""
if (xy2 is None and slope is None or
xy2 is not None and slope is not None):
raise TypeError(
"Exactly one of 'xy2' and 'slope' must be given")
if xy2 is None:
x1, y1 = xy1
xy2 = (x1, y1 + 1) if np.isinf(slope) else (x1 + 1, y1 + slope)
return xy1, xy2
axline
函数用于坐标轴非线性缩放
根据axline()
源码可知,slope
参数对于坐标轴非线性缩放无效。
if slope is not None and (self.get_xscale() != 'linear' or
self.get_yscale() != 'linear'):
raise TypeError("'slope' cannot be used with non-linear scales")
import matplotlib.pyplot as plt
# 默认为线性缩放(linear)
plt.subplot(221)
plt.axline((0, 0), (1, 1))
plt.subplot(222)
# 对数缩放('log')
plt.axline((0, 0), (1, 1))
plt.yscale('log')
plt.subplot(223)
# 对称对数缩放('symlog')
plt.axline((0, 0), (1, 1))
plt.yscale('symlog')
plt.subplot(224)
# slope参数不支持非线性缩放
plt.axline((0, 0), slope=1)
plt.yscale('log')
plt.show()