我正在尝试使用for循环为xlsx文件中的图表添加序列,但出现一个奇怪的错误。
这是我的代码。
这部分显示我已经对DF进行了排序并重新索引,以便于将DF索引解释为excel索引,以供excel单元格参考。
# Sort dataframe and reindex
pivDF = pivDF.sort_values(by=['Vg'])
pivDF = pivDF.reset_index(drop=True) # reindex dropping previous index instead of adding it as a new column
# Add the following as a sheet in a excel file:
# data, chart
## Create workbook
workbook = xlsxwriter.Workbook(dirPath + file_name + '.xlsx') # Creates workbook object
## Add a worksheet to hold the data.
writer = pd.ExcelWriter(dirPath+"//"+file_name+".xlsx", engine = 'xlsxwriter')
pivDF.to_excel(writer,sheet_name = 'Data')
writer.save()
## Add plot
### Create a new line chart.
chartsheet = workbook.add_chartsheet() # creates chartsheet objec
chart = workbook.add_chart({'type': 'line'}) # creates chart object
以下内容添加了该系列,也是我遇到问题的地方。
### Configure the chart
#### Configure series.
##### Get unique Vg
Vglist = pivDF.Vg.unique()
C1 = 'D'
C2 = 'F'
for Vg in Vglist:
# Get min and max row excel index for current Vg
indexList = list(pivDF.loc[(pivDF.Vg == Vglist[0])].index.values) # gets list of index at Vg value
r1 = min(indexList) + 2
r2 = max(indexList) + 2
chart.add_series({
'name': 'Vg ' + Vg + 'V',
'categories': '=Sheet1!$'+ C1 +'$'+ r1 +':$'+ C1 +'$'+ r2, # Vd data
'values': '=Sheet1!$'+ C2 +'$'+ r1 +':$'+ C2 +'$'+ r2, # Id normalized data
})
提前谢谢!
答案 0 :(得分:1)
以编程方式设置XlsxWriter图表范围的最佳方法是避免使用Sheet1!D1:D12
样式范围语法,而使用docs中所示的替代list
语法。
类似的东西:
C1 = 3
C2 = 5
for Vg in Vglist:
indexList = list(pivDF.loc[(pivDF.Vg == Vglist[0])].index.values)
r1 = min(indexList) + 1
r2 = max(indexList) + 1
chart.add_series({
'name': 'Vg %sV' % Vg,
'categories': ['Sheet1', r1, C1, r2, C1],
'values': ['Sheet1', r1, C2, r2, C2],
})
答案 1 :(得分:0)
我在https://riptutorial.com/python/example/17392/create-excel-charts-with-xlsxwriter
找到了答案代码应如下所示:
C1 = 'D'
C2 = 'F'
for Vg in Vglist:
# Get min and max row excel index for current Vg
indexList = list(pivDF.loc[(pivDF.Vg == Vglist[0])].index.values) # gets list of index at Vg value
r1 = min(indexList) + 2
r2 = max(indexList) + 2
chart.add_series({
'name': 'Vg %sV' % Vg,
'categories': '=Sheet1!$%s$%s:$%s$%s' % (C1, r1, C1, r2), # Vd data
'values': '=Sheet1!$%s$%s:$%s$%s' % (C2, r1, C2, r2), # Id normalized data
})