如何检索用matplotlib绘制的线的信息?

k2fxgqgv  于 2023-06-30  发布在  其他
关注(0)|答案(2)|浏览(88)

我想用for循环分析已经在图上绘制的线。我尝试使用ax.get_lines()[0].get_data()函数,但无论我画什么样的线(它通过哪些点),它都会返回([0, 1], [0, 1])作为数据。

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 7.00]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([0, 100])
ax.set_ylim([0, 100])

point1 = [-8,4]
point2 = [10,15]
plt.axline(point1,point2) # drawing the line

lines = ax.get_lines()
print(lines[0].get_data()) # retrieving data

plt.show()
ddrv8njm

ddrv8njm1#

我查看了各种资源中get_lines()的用法,它似乎被用来获取行数(在文献中)。就像这样:

lines = ax.get_lines()
print('number of lines', len(lines))

如果你想得到两点之间(* 直线 )的描述( 大概是斜率和截距 *),你可以做一个像这样的简单函数来实现结果:

def get_slope_and_intercept(point1, point2):
    """
    Gets the slope and intercept of the line given point1 and point2 as two lists.

    Args:
        point1: The first point, as a list of two numbers.
        point2: The second point, as a list of two numbers.

    Returns:
        A tuple of the slope and intercept of the line.
    """

    x1, y1 = point1
    x2, y2 = point2

    slope = (y2 - y1) / (x2 - x1)
    intercept = y1 - slope * x1

    return slope, intercept

if __name__ == "__main__":

    slope, intercept = get_slope_and_intercept(point1, point2)

    print("The slope is:", slope)
    print("The intercept is:", intercept)

根据问题中给出的要点,它将产生以下结果:

The slope is: 0.6111111111111112
The intercept is: 8.88888888888889
zlwx9yxi

zlwx9yxi2#

使用axline时,提供的坐标存储在line._xy1line._xy2中(类似地,斜率数据存储在line._slope中,但如果不使用此参数,则将存储在None中)。

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

point1 = [-8,4]
point2 = [10,15]
ax.axline(point1, point2)

lines = ax.get_lines()
print(lines[0]._xy1, lines[0]._xy2)    # [-8, 4] [10, 15]

这与使用普通plot函数生成的行不同,在普通plot函数中,可以使用line.get_xydata()获取数据。我不完全确定为什么要使用[0,1],但它被硬编码到source code中(请看_AxLine类,其中super.__init__被调用用于Line2D类,[0,1]被传递用于xy数据)。

相关问题