利用numpy和matplotlib画两点的连线,坐标存在numpy中
时间: 2023-11-10 16:29:15 浏览: 76
下面是一段示例代码,其中点的坐标存储在numpy数组中,使用matplotlib中的plot函数绘制出两点的连线:
```python
import numpy as np
import matplotlib.pyplot as plt
# 两个点的坐标
point1 = np.array([1, 2])
point2 = np.array([3, 4])
# 绘制点
plt.plot(point1[0], point1[1], 'bo')
plt.plot(point2[0], point2[1], 'bo')
# 绘制连线
plt.plot([point1[0], point2[0]], [point1[1], point2[1]], 'r-')
# 设置坐标轴范围
plt.xlim([0, 5])
plt.ylim([0, 5])
# 显示图像
plt.show()
```
运行这段代码可以得到如下图像:
![image](https://user-images.githubusercontent.com/2915035/128407662-5b5e5f5c-81d2-4a18-baa0-57b8a3b3f64b.png)
相关问题
numpy画过两点的直线
可以使用numpy中的polyfit函数来获得两点连线的一次多项式系数,然后使用这个系数来绘制直线。具体代码如下:
import numpy as np
import matplotlib.pyplot as plt
# 生成随机坐标
x = np.random.rand(2)
y = np.random.rand(2)
# 用一次多项式拟合
coef = np.polyfit(x, y, 1)
# 生成一些用于绘图的横坐标
x_plot = np.linspace(0, 1, num=100)
# 计算纵坐标
y_plot = x_plot * coef[0] + coef[1]
# 绘制直线和原始点
plt.plot(x_plot, y_plot)
plt.plot(x, y, 'ro')
plt.show()
绘制三维直角坐标系的线性变换的动画python代码
下面是Python代码,使用matplotlib库绘制三维直角坐标系的线性变换动画:
```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation
# 创建三维坐标系
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# 初始的点集
X = np.array([1, 2, 3])
Y = np.array([4, 5, 6])
Z = np.array([7, 8, 9])
orig_pts = np.vstack((X, Y, Z))
# 随机生成一个3x3的变换矩阵
A = np.random.rand(3, 3)
# 定义动画函数
def animate(i):
# 计算变换后的点集
new_pts = np.dot(A, orig_pts)
ax.clear()
ax.set_xlim([-10, 10])
ax.set_ylim([-10, 10])
ax.set_zlim([-10, 10])
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Linear Transformation Animation')
ax.scatter(new_pts[0], new_pts[1], new_pts[2], color='r')
ax.plot(new_pts[0], new_pts[1], new_pts[2], color='b')
return ax
# 创建动画
anim = FuncAnimation(fig, animate, frames=100, interval=50)
# 显示动画
plt.show()
```
这段代码使用numpy库生成一个3x3的随机变换矩阵,并将初始的点集按照这个变换矩阵进行变换。然后使用matplotlib库绘制三维坐标系,并将变换后的点集和连线绘制出来。最后使用FuncAnimation函数创建动画并显示。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)