Python | Plotting Area charts in excel sheet using XlsxWriter module

Python | Plotting Area charts in excel sheet using XlsxWriter module

To plot area charts in an Excel sheet using Python, you can use the XlsxWriter module, which allows you to create Excel files and add charts to them. First, you'll need to install XlsxWriter if you haven't already:

pip install XlsxWriter 

Once installed, here's how you can create an Excel file, add data to it, and then create an area chart based on that data:

Step-by-Step Example

1. Import XlsxWriter and Create a New Excel File

import xlsxwriter # Create a workbook and add a worksheet workbook = xlsxwriter.Workbook('area_chart.xlsx') worksheet = workbook.add_worksheet() 

2. Add Data to the Worksheet

# Sample data for the chart data = [ ['Category', 'Value1', 'Value2'], ['A', 2, 5], ['B', 3, 6], ['C', 4, 7], ['D', 5, 8] ] # Write the data to the worksheet row = 0 col = 0 for category, value1, value2 in data: worksheet.write(row, col, category) worksheet.write(row, col + 1, value1) worksheet.write(row, col + 2, value2) row += 1 

3. Create an Area Chart

# Create a chart object chart = workbook.add_chart({'type': 'area'}) # Configure the first series chart.add_series({ 'name': '=Sheet1!$B$1', 'categories': '=Sheet1!$A$2:$A$5', 'values': '=Sheet1!$B$2:$B$5', }) # Configure a second series chart.add_series({ 'name': '=Sheet1!$C$1', 'categories': '=Sheet1!$A$2:$A$5', 'values': '=Sheet1!$C$2:$C$5', }) # Add a chart title and x/y-axis labels chart.set_title({'name': 'Area Chart Example'}) chart.set_x_axis({'name': 'Category'}) chart.set_y_axis({'name': 'Values'}) # Insert the chart into the worksheet worksheet.insert_chart('E2', chart) 

4. Close the Workbook

# Close the workbook workbook.close() 

Running the Script

Running the above script will create an Excel file named area_chart.xlsx with an area chart based on the provided data.

Customizing the Chart

XlsxWriter offers various options to customize the chart, such as:

  • Changing the chart type
  • Formatting the chart and data points
  • Adding markers, data labels, or other elements

More Tags

shortest-path using react-native-maps filereader screen criteria google-picker apache2.4 preact relational-algebra

More Programming Guides

Other Guides

More Programming Examples