Pythonとopenpyxlライブラリを使ってExcelの折れ線グラフを作成する方法を紹介します。
まず、openpyxlとpandasライブラリをインストールします。
pip install openpyxl pandas
次に、Excelのデータを読み込みます。
import pandas as pd
from datetime import datetime
import openpyxl as px
filepath = 'sample.xlsx'
df = pd.read_excel(filepath)
df['Date'] = pd.to_datetime(df['Date']).dt.strftime("%Y-%m")
ここで、’Product’ごとにデータを分けて折れ線グラフを作成します。
products = sorted(list(df['Product'].unique()))
areas = sorted(list(df['Area'].unique()))
dates = sorted(list(df['Date'].unique()))
now = datetime.now()
hiduke = now.strftime('%Y-%m-%d')
for product in products:
filtered = df[df['Product'] == f' {product}']
sales = pd.pivot_table(df, index=filtered['Date'], columns='Area', values='Price', aggfunc='sum',fill_value=0)
filepath = f' {hiduke}_ {product}.xlsx'
sales.to_excel(filepath,sheet_name='製品売上',startrow=3)
最後に、作成したグラフをExcelに挿入します。
wb = px.load_workbook(filepath)
ws = wb['製品売上']
ws.cell(row=1, column=1).value = f' {product}_製品売上'
ws.cell(row=1, column=1).font = px.styles.Font(size=18, bold=True)
ws.cell(row=2, column=1).value = '月次レポート'
ws.cell(row=2, column=1).font = px.styles.Font(size=16, bold=True)
chart = px.chart.LineChart()
data = px.chart.Reference(ws, min_col=2, max_col=len(areas)+1, min_row=4, max_row=len(dates)+4)
categories = px.chart.Reference(ws, min_col=1, max_col=1, min_row=5, max_row=len(dates)+4)
chart.add_data(data, titles_from_data=True)
chart.set_categories(categories)
chart.style = 14
chart.title = '製品売上'
chart.y_axis.title = '円'
ws.add_chart(chart, "A10")
wb.save(filepath)
以上がPythonとopenpyxlを使ってExcelの折れ線グラフを作成する方法です。この方法を使えば、Excelのデータを効率的に可視化することができます。.