根据padans画柱状图并保存
时间: 2023-07-11 13:25:39 浏览: 110
要保存Pandas和Matplotlib绘制的柱状图,可以使用Matplotlib的`savefig`函数。以下是一个示例代码,展示如何使用Pandas从CSV文件中读取数据,然后使用Matplotlib绘制柱状图并将其保存为PNG文件:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 从CSV文件中读取数据
data = pd.read_csv('data.csv')
# 绘制柱状图
ax = data.plot(kind='bar', x='name', y='value', legend=False)
ax.set_xlabel("Name")
ax.set_ylabel("Value")
# 保存图表为PNG文件
plt.savefig('bar_chart.png')
```
在上面的代码中,我们使用Pandas的`read_csv`函数从CSV文件中读取数据,并将其存储在一个DataFrame对象中。然后,我们使用`plot`函数绘制柱状图,其中参数`kind='bar'`指定柱状图类型,`x='name'`和`y='value'`指定要在X轴和Y轴上显示的列。最后,我们使用Matplotlib的`savefig`函数将图表保存为PNG文件。
请注意,在保存图表之前,需要确保指定的文件夹已存在。如果指定的文件夹不存在,Matplotlib将会报错。你可以使用以下代码创建一个新文件夹:
```python
import os
if not os.path.exists('output'):
os.makedirs('output')
```
这将创建一个名为“output”的新文件夹,如果该文件夹不存在。然后,你可以使用以下代码将图表保存到该文件夹中:
```python
plt.savefig('output/bar_chart.png')
```
阅读全文
相关推荐



















