pythonopenpyxl

Chart with X and Y axis as column 1 and column 2


Refer to the pic below:

enter image description here

Using the code below I am getting the 1st graph but what I need is the second graph. Please let me know where I am wrong

import openpyxl

xfile = openpyxl.load_workbook("chart.xlsx")
sheet = xfile["Chart"]
c = openpyxl.chart.LineChart()

c.title = "Graph"
c.style = 1

c.y_axis.title = 'Time'
c.x_axis.title = 'WF'

data = openpyxl.chart.Reference(sheet, min_col=1, min_row=1, max_col=2, max_row=sheet.max_row)
c.add_data(data, titles_from_data=True)

sheet.add_chart(c, "C1")
xfile.save("chart.xlsx")

Solution

  • Your question is not fully clear. I suppose your problem is just regarding the X axis and not about the styling of the chart.

    To obtain the "same" chart you have to set the labels of the X axis selecting those values from the first column.

        import openpyxl
    
        chart_directory = "chart.xlsx"
    
        xfile = openpyxl.load_workbook(chart_directory)
        sheet = xfile["Chart"]
        c = openpyxl.chart.LineChart()
    
        c.title = "Graph"
        c.style = 2
    
        c.y_axis.title = 'Time'
        c.x_axis.title = 'WF'
    
        #Select the lables to set
        labels = openpyxl.chart.Reference(sheet, min_col=1, min_row=2, max_row=sheet.max_row, max_col=1)
        #Select the values to set
        data = openpyxl.chart.Reference(sheet, min_col=2, min_row=1, max_row=sheet.max_row)
    
        #Set the values
        c.add_data(data, titles_from_data=True)
        #Set the labels
        c.set_categories(labels)
    
        sheet.add_chart(c, "C1")
        xfile.save(chart_directory)
    

    In this sample code you can see that I select the labels as column 1 from the row 2 until the last row. After that you can select the values to print as column 2 from the row 1 (so it keeps the legend name of the series) until the last row.

    You have to set the data in the chart, and after that the labels.