Python读取CSV文件并绘图
时间: 2024-03-28 11:17:06 浏览: 24
好的,下面是代码示例:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 读取CSV文件
df = pd.read_csv("filename.csv")
# 绘制柱状图
df.plot(kind="bar", x="x_column_name", y="y_column_name")
# 显示图形
plt.show()
```
其中,"filename.csv" 是你想要读取的CSV文件名,"x_column_name" 和 "y_column_name" 分别是CSV文件中需要绘制的列的列名。
你可以根据需要进行修改,例如可以使用其他类型的图表,或者调整图表的样式等。
相关问题
python读取csv文件并绘图 保存
你的代码中有一些问题,可能导致你的图形无法正确绘制。首先,你需要将文件路径中的反斜杠转义,即将"D:\test"改为"D:\\test"。其次,你的筛选条件可能有问题,因为你使用了">"而不是">=",应该将">="改为">="。最后,你需要在绘图之后添加保存图像的代码,例如使用plt.savefig()函数。下面是修改后的代码:
```
import pandas as pd
import glob
import os
import matplotlib.pyplot as plt
file_path = 'D:\\test'
files = glob.glob(os.path.join(file_path, "*.csv"))
for file in files:
df = pd.concat(map(pd.read_csv, file))
df = df[df['battery_percent'] >= 50]
df = df[df['path_select_state'] == "ServerSendPath"]
df = df[['robot_id', 'linear_velocity', 'linear_acceleration', 'battery_percent', 'path_select_state', 'left_wheel_current', 'right_wheel_current']]
df.plot(x="linear_velocity", y="left_wheel_current")
plt.title("Speed reducer", fontsize=16)
plt.xlabel("linear_velocity", fontsize=16)
plt.ylabel("left_wheel_current", fontsize=16)
plt.savefig(file[:-4] + ".png")
plt.show()
```
这段代码将会读取文件夹"D:\\test"下的所有csv文件,筛选出电池电量大于等于50且路径选择状态为"Server***文件中。
python读取csv文件并画图详细代码例子
以下是一个读取 CSV 文件并画图的 Python 代码示例:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 读取 CSV 文件
df = pd.read_csv('data.csv')
# 绘制折线图
plt.plot(df['x'], df['y'])
# 添加标题和坐标轴标签
plt.title('Title')
plt.xlabel('X Label')
plt.ylabel('Y Label')
# 显示图形
plt.show()
```
在这个示例中,我们使用 Pandas 库的 `read_csv()` 函数读取名为 `data.csv` 的 CSV 文件,并将其存储在名为 `df` 的 DataFrame 中。然后,我们使用 Matplotlib 库的 `plot()` 函数绘制了 `df` 中的 `x` 和 `y` 列之间的折线图。最后,我们使用 `title()`、`xlabel()` 和 `ylabel()` 函数添加了标题和坐标轴标签,并使用 `show()` 函数显示了图形。
需要注意的是,这只是一个简单的示例代码。在实际应用中,您可能需要根据数据集的特点和绘图需求进行一些调整。
相关推荐
![csv](https://img-home.csdnimg.cn/images/20210720083646.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)