matplotlib之pyplot模块——绘制一条无限长的直线(axline())

概述

axline函数作用是绘制一条无限长的直线。与 axvline/axhline相比,axline函数绘制的直线长度是无限的,直线可以是任意角度的直线。

axline函数的签名为:
matplotlib.pyplot.axline(xy1, xy2=None, *, slope=None, **kwargs)
其中:

  • xy1:直线贯穿的点的坐标。浮点数二元组(float, float)
  • xy2:直线贯穿的点的坐标。浮点数二元组(float, float)。默认值为Nonexy2slope同时只能有一个值有效。两者既不能同时为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()

xy2slope参数关系解析

根据axline()源码可知,_to_points(xy1, xy2, slope)函数首先检查参数的组合情况,xy2slope同时为None或非None值,抛出错误。如果xy2None,则根据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()

猜你喜欢

转载自blog.csdn.net/mighty13/article/details/114332670