xlwings添加chart完整示例代码
时间: 2023-09-02 22:14:15 浏览: 134
以下是使用xlwings创建图表的完整示例代码:
```python
import xlwings as xw
import numpy as np
# 创建一个新的Excel工作簿
wb = xw.Book()
# 在Sheet1中输入一些数据
sht = wb.sheets['Sheet1']
sht.range('A1').value = 'X'
sht.range('B1').value = 'Y'
sht.range('A2').value = np.arange(0, 10, 0.1)
sht.range('B2').value = np.sin(sht.range('A2').value)
# 创建一个图表对象并添加一个图表
chart = sht.charts.add()
chart.name = 'MyChart'
# 添加一个散点图系列
series = chart.series.add(sht.range('A2').expand(), sht.range('B2').expand())
series.name = 'Sin(x)'
series.marker.style = 'Circle'
# 添加一个线图系列
trendline = series.trendlines.add()
trendline.intercept.value = 0.5
trendline.display_equation = True
trendline.display_r_squared = True
# 设置图表标题和坐标轴标签
chart.api.HasTitle = True
chart.api.ChartTitle.Text = 'My Chart'
chart.api.Axes(xlCategory, xlPrimary).HasTitle = True
chart.api.Axes(xlCategory, xlPrimary).AxisTitle.Text = 'X'
chart.api.Axes(xlValue, xlPrimary).HasTitle = True
chart.api.Axes(xlValue, xlPrimary).AxisTitle.Text = 'Y'
# 调整图表大小和位置
chart.api.Parent.Top = 50
chart.api.Parent.Left = 50
chart.api.Parent.Width = 500
chart.api.Parent.Height = 300
# 保存Excel工作簿
wb.save('MyWorkbook.xlsx')
```
阅读全文