使用matplotlib、numpy、pandas、xlwings绘制图,给出完整实例和注释以及完整excel数据
时间: 2023-11-16 09:04:21 浏览: 148
本实例我们将使用matplotlib、numpy、pandas、xlwings这四个库来绘制一个简单的折线图。
1. 准备数据
首先我们需要准备数据,我们在excel中准备了以下数据:

2. 导入数据
我们使用pandas来读取excel数据:
```python
import pandas as pd
# 读取excel数据
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
# 打印数据
print(df)
```
输出结果:
```
日期 销售量
0 2022/1/1 100
1 2022/1/2 120
2 2022/1/3 130
3 2022/1/4 110
4 2022/1/5 140
5 2022/1/6 150
6 2022/1/7 130
```
3. 绘制折线图
接下来我们使用matplotlib来绘制折线图:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成x轴数据
x = np.arange(len(df))
# 绘制折线图
plt.plot(x, df['销售量'], 'o-')
# 设置x轴标签
plt.xlabel('日期')
# 设置y轴标签
plt.ylabel('销售量')
# 显示图形
plt.show()
```
输出结果:

4. 导出图表
最后我们使用xlwings将图表导出到excel中:
```python
import xlwings as xw
# 打开excel
wb = xw.Book('data.xlsx')
# 获取Sheet1
sht = wb.sheets['Sheet1']
# 将图表插入到Sheet1的B2单元格
sht.pictures.add(plt, name='销售量图表', update=True, left=sht.range('B2').left, top=sht.range('B2').top)
# 保存excel
wb.save()
# 关闭excel
wb.close()
```
输出结果:

完整代码如下:
```python
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import xlwings as xw
# 读取excel数据
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
# 打印数据
print(df)
# 生成x轴数据
x = np.arange(len(df))
# 绘制折线图
plt.plot(x, df['销售量'], 'o-')
# 设置x轴标签
plt.xlabel('日期')
# 设置y轴标签
plt.ylabel('销售量')
# 显示图形
plt.show()
# 打开excel
wb = xw.Book('data.xlsx')
# 获取Sheet1
sht = wb.sheets['Sheet1']
# 将图表插入到Sheet1的B2单元格
sht.pictures.add(plt, name='销售量图表', update=True, left=sht.range('B2').left, top=sht.range('B2').top)
# 保存excel
wb.save()
# 关闭excel
wb.close()
```
完整excel数据:

阅读全文
相关推荐









