在每个点上绘制指向图中线条的箭头

问题描述 投票:0回答:1

我正在尝试使用 matplotlib 绘制从每个数据点到图中的线的箭头。

我想要箭头代表每个点和线之间的距离。我该怎么做?

这是我的代码:

import matplotlib.pyplot as plt
import numpy as np

# Create a straight line (45-degree angle)
x_line = np.linspace(0, 10, 100)
y_line = x_line

# Add some random points around the line
num_points = 20
x_points = np.linspace(2, 8, num_points)  # Adjust the range as needed
y_points = x_points + np.random.normal(0, 0.5, num_points)  # Add some randomness

# Plot the line
plt.plot(x_line, y_line, label='Line', color='blue')

# Plot the points
plt.scatter(x_points, y_points, label='Points', color='red')

# Set labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Around a Line')

# Show legend
plt.legend()

# Display the plot
plt.show()

我自己尝试这样做但失败了:

代码:

import matplotlib.pyplot as plt
import numpy as np

# Create a straight line (45-degree angle)
x_line = np.linspace(0, 10, 100)
y_line = x_line

# Add some random points around the line
num_points = 20
x_points = np.linspace(2, 8, num_points)  # Adjust the range as needed
y_points = x_points + np.random.normal(0, 0.5, num_points)  # Add some randomness

# Plot the line
plt.plot(x_line, y_line, label='Line', color='blue')

# Plot the points
plt.scatter(x_points, y_points, label='Points', color='red')

# Add arrows from each point to the line
for x, y in zip(x_points, y_points):
    plt.arrow(x, y, 0, y - x, color='black', linestyle='dashed', linewidth=0.5, head_width=0.2)

# Set labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Around a Line')

# Show legend
plt.legend()

# Display the plot
plt.show()

如您所见,数据点发生了移动,箭头指向外侧,而不是向内或指向直线。

python matplotlib machine-learning graph least-squares
1个回答
0
投票

您可以尝试运行此代码吗?它可能会解决您的问题。

import matplotlib.pyplot as plt
import numpy as np

# Create a straight line (45-degree angle)
x_line = np.linspace(0, 10, 100)
y_line = x_line

# Add some random points around the line
num_points = 20
x_points = np.linspace(2, 8, num_points)  # Adjust the range as needed
y_points = x_points + np.random.normal(0, 0.5, num_points)  # Add some randomness

# Plot the line
plt.plot(x_line, y_line, label='Line', color='blue')

# Plot the points
plt.scatter(x_points, y_points, label='Points', color='red')

# Add outward arrows from each point away from the line
for x, y in zip(x_points, y_points):
    plt.arrow(x, y, 0, (x - y) * 0.5, color='black', linestyle='dashed', linewidth=0.5, head_width=0.2)

# Set labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Around a Line')

# Show legend
plt.legend()

# Display the plot
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.