matplotlib与pandas和xlwings绘制图,给出完整实例和完整excel数据
时间: 2024-05-09 07:17:21 浏览: 104
以下是一个完整的实例演示如何使用matplotlib、pandas和xlwings从Excel文件中读取数据并绘制图表。
Excel数据:
日期 | 销售额
----|-----
1/1/2021 | 100
1/2/2021 | 150
1/3/2021 | 200
1/4/2021 | 175
1/5/2021 | 250
1/6/2021 | 300
1/7/2021 | 225
步骤1:导入必要的库
```python
import pandas as pd
import xlwings as xw
import matplotlib.pyplot as plt
```
步骤2:从Excel文件中读取数据
```python
# 打开Excel文件
wb = xw.Book('sales.xlsx')
# 选择工作表
sht = wb.sheets['Sheet1']
# 读取数据
df = sht.range('A1:B8').options(pd.DataFrame, index=False, header=True).value
```
步骤3:绘制图表
```python
# 设置图形大小和标题
plt.figure(figsize=(8,6))
plt.title('Sales')
# 绘制折线图
plt.plot(df['日期'], df['销售额'], marker='o')
# 设置x轴标签和旋转角度
plt.xticks(rotation=45)
plt.xlabel('Date')
# 设置y轴标签
plt.ylabel('Sales')
# 显示图形
plt.show()
```
完整代码:
```python
import pandas as pd
import xlwings as xw
import matplotlib.pyplot as plt
# 打开Excel文件
wb = xw.Book('sales.xlsx')
# 选择工作表
sht = wb.sheets['Sheet1']
# 读取数据
df = sht.range('A1:B8').options(pd.DataFrame, index=False, header=True).value
# 设置图形大小和标题
plt.figure(figsize=(8,6))
plt.title('Sales')
# 绘制折线图
plt.plot(df['日期'], df['销售额'], marker='o')
# 设置x轴标签和旋转角度
plt.xticks(rotation=45)
plt.xlabel('Date')
# 设置y轴标签
plt.ylabel('Sales')
# 显示图形
plt.show()
```
阅读全文
相关推荐

















