Chapter 6: Visualizing Data with Charts and Graphs
Getting Started: Charting Our Inventory
Creating Your First Chart: A Bar Chart
from openpyxl import load_workbook
from openpyxl.chart import BarChart, Reference, PieChart
wb = load_workbook("inventory_with_formulas.xlsx")
ws = wb.active
# 1. Create a BarChart object
chart1 = BarChart()
chart1.title = "Product Inventory Quantities"
chart1.x_axis.title = "Product"
chart1.y_axis.title = "Quantity"
# 2. Create Reference objects for the data
# NOTE: We subtract 2 from max_row because of the empty row and grand total
last_data_row = ws.max_row - 2
data = Reference(ws, min_col=2, min_row=2, max_row=last_data_row)
cats = Reference(ws, min_col=1, min_row=2, max_row=last_data_row)
# 3. Add the data and labels to the chart
chart1.add_data(data)
chart1.set_categories(cats)
# 4. Add the chart to the worksheet, placing it at cell F2
ws.add_chart(chart1, "F2")
# --- Creating a Pie Chart ---
# 1. Create a PieChart object
chart2 = PieChart()
chart2.title = "Percentage of Total Inventory Value by Product"
# 2. Select data for the pie chart
data = Reference(ws, min_col=4, min_row=2, max_row=last_data_row) # Column D
labels = Reference(ws, min_col=1, min_row=2, max_row=last_data_row)
# 3. Add the data and set the labels
chart2.add_data(data)
chart2.set_categories(labels)
# 4. Add the chart to the worksheet, placing it below the first chart at F18
ws.add_chart(chart2, "F18")
# Save the final dashboard
wb.save("inventory_dashboard.xlsx")
print("Dashboard with both charts saved successfully.")
What You've Accomplished
PreviousChapter 5: Working with Excel FormulasNextChapter 7: Case Study - Automating a Monthly Sales Report
Last updated