python在excel中画图
时间: 2023-10-18 16:32:01 浏览: 70
在 Python 中,可以使用多个库来在 Excel 中进行绘图,其中比较常用的库包括 openpyxl、xlsxwriter 和 pandas。
使用 openpyxl 库绘制图表的基本步骤如下:
1. 导入 openpyxl 库和相关模块:
```python
import openpyxl
from openpyxl.chart import BarChart, Reference
```
2. 打开 Excel 文件并选择要进行绘图的工作表:
```python
workbook = openpyxl.load_workbook('filename.xlsx')
worksheet = workbook['sheetname']
```
3. 准备数据并设定图表范围:
```python
data = Reference(worksheet,
min_row=1,
max_row=worksheet.max_row,
min_col=1,
max_col=2)
```
4. 创建图表对象,并将数据添加到图表中:
```python
chart = BarChart()
chart.add_data(data)
```
5. 设置图表的标题和坐标轴标签等属性:
```python
chart.title = "Chart Title"
chart.x_axis.title = "X Axis Title"
chart.y_axis.title = "Y Axis Title"
```
6. 将图表插入到指定单元格:
```python
worksheet.add_chart(chart, 'D2')
```
7. 保存 Excel 文件:
```python
workbook.save('filename.xlsx')
```
使用其他库也可以实现在 Excel 中绘制图表,具体步骤会有所不同,但基本原理相似。