Customize chart setting using openpyxl in Python

In this tutorial, I will tell you how to customize that line chart using openpyxl in Python.

Customizing chart setting using openpyxl

I have created an Excel sheet, price_chart.xlsx for example. It has three columns and six rows, 'Date', 'Tomato Prices', and 'Potato Prices'.

openpyxl file in Python

After creating the Excel sheet. Load the workbook in your code using the load_workbook() function and pass the file’s name as an argument. Make sure to activate it.

wb = load_workbook('price_chart.xlsx')
ws = wb.active

After creating a line chart, Tomato-Potato Sales using the LineChart() function.  I’ve added the x-axis and y-axis titles along with the legend by using the respective functions.

Code :

values = Reference(ws, min_col=2, min_row=1, max_col=3, max_row=6)
x_values = Reference(ws, range_string="chart!A2:A6")

chart = LineChart()
chart.add_data(values, titles_from_data=True)
chart.set_categories(x_values)

chart.title = "Tomato-Potato Sales"
chart.x_axis.title = "Day"
chart.y_axis.title = "Tomato-Potato Sales (INR)"
chart.legend.position = "b"

Then I’ve added it to my Excel sheet using add_chart() function.
Recommended article: create a line chart using openpyxl in Python.
Code :

ws.add_chart(chart, 'G2')

Output :

Customize chart setting using openpyxl in Python

In Python, we can iterate the series object of the chart.

Code :

tomato = chart.series[0]
potato = chart.series[1]

The series object has a number of attributes like marker, graphicalProperties.line.solidFill, graphicalProperties.line.dashStyle, graphicalProperties.line.width, etc. These attributes help you customize your line chart. The marker attribute helps you add a symbol at every pair of x and y. It also lets you change the size of the marker. graphicalProperties.line.solidFill takes a hex code string for a color. However, graphicalProperties.line.dashStyle takes one of the following strings as its values. As default, it is assigned a value of ‘solid’.

  • ‘sysDashDot’
  • ‘dashDot’
  • ‘sysDash’
  • ‘dash’
  • ‘dot’
  • ‘lgDashDotDot’
  • ‘lgDashDot’
  • ‘sysDot’
  • ‘sysDashDotDot’
  • ‘solid’
  • ‘lgDash’

graphicalProperties.line.noFill takes a boolean value, either true or false, as it makes sure if you want a line with a color or no color. This is mostly used, when one uses marker.symbol to locate every x and y pair.

I’ve customized my line chart accordingly.
Code :

tomato.graphicalProperties.line.solidFill = "000FFF" 
tomato.graphicalProperties.line.dashStyle = "dot" 

potato.marker.symbol = "diamond" 
potato.graphicalProperties.line.solidFill = 'FF0000'

Output :

marker.symbol in openpyxl

There are a number of ways you can customize your line chart. Try taking an Excel sheet plot a chart and customize it as per your wish.

Leave a Reply

Your email address will not be published. Required fields are marked *