Set the graph when outputting an Excel file with Python.
① Import the sample_graph.xlsx file ② Set the graph ③ Output to sample_graph2.xlsx file
graph_create.py
import openpyxl
from openpyxl.chart import PieChart, Reference
from openpyxl.chart.series import DataPoint
#Get excel file
wb = openpyxl.load_workbook("./data/sample_graph.xlsx")
#Get sheet "Name: Sheet1"
ws = wb["Sheet1"]
#Set graph data
data = Reference(ws, min_col=2, max_col=2, min_row=1, max_row=ws.max_row)
#Set graph label
labels = Reference(ws, min_col=1, min_row=2, max_row=ws.max_row)
#Make a graph!
chart = PieChart() #Get a pie chart object * This is the graph type (BarChart for bar charts)
chart.title = "Sales by category" #Pie chart title settings
chart.add_data(data, titles_from_data=True) #Pie chart data settings
chart.set_categories(labels) #Pie chart category settings
#Output pie chart to Excel sheet ws, position D3 cell
ws.add_chart(chart, "D3")
#Output file
wb.save("./data/sample_graph2.xlsx")
A pie chart was created like this. After that, it feels like fine-tuning and changing the settings of other types (bar graphs, etc.).
That's it (*'▽')
Recommended Posts