如何循环数据框并基于单列或多列创建多个Excel图表?

时间:2017-06-14 15:54:23

标签: python loops charts

我的数据框包含多个具有多个子类别的类别。我根据子类别圈出我的df并为每个子类别创建图表,但我需要按类别循环并将子类别系列放在图表中。 我的df:

Date    Purchased  Fruit_orange Fruit_apple Vegetables  Meats_chicken  Meats_beef
5/11/2015   23          67                                                  4
5/18/2015   87                         53           2            9         10
5/25/2015   96                                      
6/1/2015    45          34      
6/8/2015    88                         11           5            3
6/15/2015   12           2      

如何在图表中循环显示df并绘制包含橙子和苹果作为系列的水果类别,然后继续循环并让它将蔬菜识别为单个列图表,然后再次绘制包含鸡肉/牛肉的肉类图表在图表中。

我在每列中循环的代码分别为每列创建一个图表。

for c in range(3,maxcol+1):

    ChartTitle = sheet.cell(row=1, column=c).value
    LeftLegend = sheet.cell(row=3, column=2).value
    RightLegend = sheet.cell(row=3, column=c).value

    LeftAxis = sheet.cell(row=3, column=2).value
    #RightAxis = sheet.cell(row=3, column=c).value



    #date range
    refObj1 = openpyxl.chart.Reference(sheet, min_col=1, min_row=4, max_col=1, max_row=maxrow)  

    #trend kpi column to repeat across charts
    refObj2 = openpyxl.chart.Reference(sheet, min_col=2, min_row=4, max_col=2, max_row=maxrow)  
    seriesObj2 = openpyxl.chart.Series(refObj2, title=LeftLegend)

    #loop thru 2dary data
    refObj3 = openpyxl.chart.Reference(sheet, min_col=c, min_row=4, max_col=c, max_row=maxrow)    
    seriesObj3 = openpyxl.chart.Series(refObj3, title=RightLegend)

    #create chart and add data, titles
    chartObj = openpyxl.chart.LineChart()
    chartObj.title = ChartTitle
    chartObj.append(seriesObj2)
    chartObj.append(seriesObj3)
    chartObj.set_categories(refObj1)
    chartObj.x_axis.title = "Date"
    chartObj.y_axis.title = LeftAxis
    #chartObj.y_axis.title = RightAxis


    sheet.add_chart(chartObj, 'c5')

0 个答案:

没有答案