读取多个文件并画图
时间: 2023-07-30 09:05:59 浏览: 50
首先,你需要安装 matplotlib 库来绘制图表。可以使用以下命令安装:
```
pip install matplotlib
```
然后,你可以使用 Python 的内置函数 `open()` 来打开文件并读取数据。以下是一个示例代码,它从三个文件中读取数据并绘制折线图:
```python
import matplotlib.pyplot as plt
# 读取文件数据
x_values = []
y1_values = []
y2_values = []
y3_values = []
with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2, open('file3.txt', 'r') as file3:
for line in file1:
x, y1 = map(float, line.split())
x_values.append(x)
y1_values.append(y1)
for line in file2:
_, y2 = map(float, line.split())
y2_values.append(y2)
for line in file3:
_, y3 = map(float, line.split())
y3_values.append(y3)
# 绘制图表
plt.plot(x_values, y1_values, label='File 1')
plt.plot(y2_values, label='File 2')
plt.plot(y3_values, label='File 3')
plt.legend()
plt.show()
```
在上面的代码中,我们使用 `with` 语句打开三个文件,然后逐行读取每个文件的数据。数据被分别存储在 `x_values`,`y1_values`,`y2_values` 和 `y3_values` 列表中。然后,我们使用 `plt.plot()` 函数绘制折线图,并使用 `plt.legend()` 函数添加图例。最后,我们使用 `plt.show()` 函数显示图表。