x=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] ,y=[20, 21, 23, 28, 36, 45, 57, 69, 85, 102, 120, 138, 161, 190, 216, 246, 276, 310, 343, 381, 418, 459, 505, 549, 596, 645, 697, 750, 805, 862]。5.把以上数据写入文件,然后从文件中读取数据,绘制两行数据对应的图
时间: 2023-06-27 15:01:21 浏览: 104
写入数据到文件:
```python
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
y = [20, 21, 23, 28, 36, 45, 57, 69, 85, 102, 120, 138, 161, 190, 216, 246, 276, 310, 343, 381, 418, 459, 505, 549, 596, 645, 697, 750, 805, 862]
with open("data.txt", "w") as f:
for i in range(len(x)):
f.write(f"{x[i]},{y[i]}\n")
```
从文件中读取数据并绘制图:
```python
import matplotlib.pyplot as plt
x = []
y = []
with open("data.txt", "r") as f:
for line in f:
data = line.strip().split(",")
x.append(int(data[0]))
y.append(int(data[1]))
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("y")
plt.show()
```
运行以上代码会弹出一个窗口展示绘制的图形。
阅读全文