使用python,生成一个坐标系和15个坐标,计算坐标到原点的距离并按从小到大排序
时间: 2023-06-01 09:02:20 浏览: 209
以下是使用python生成坐标系和15个坐标,并计算距离并排序的代码:
```python
import math
import matplotlib.pyplot as plt
# 生成坐标系
fig, ax = plt.subplots()
# 生成15个坐标
coordinates = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14),
(-1, 2), (-3, 4), (-5, 6), (-7, 8), (-9, 10), (-11, 12), (-13, 14), (0, 0)]
# 计算距离并排序
distances = []
for coord in coordinates:
distance = math.sqrt(coord[0]**2 + coord[1]**2)
distances.append(distance)
sorted_coords = [x for _,x in sorted(zip(distances,coordinates))]
# 绘制坐标
for coord in sorted_coords:
ax.plot(coord[0], coord[1], marker='o')
# 显示坐标系
ax.set_xlim([-15, 15])
ax.set_ylim([-15, 15])
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.show()
```
运行以上代码后会生成一个坐标系和15个坐标,并按照距离从小到大排序,如下图所示:
![image](https://user-images.githubusercontent.com/48306928/123828782-444cdf00-d935-11eb-8d6b-1042b8c6d9b9.png)
阅读全文