Python で業務レポートを自動化する際、グラフの種類を目的に合わせて選択すると情報が伝わりやすくなります。本稿では pandas で読み込んだ CSV データを openpyxl へ貼り付け、以下 3 つの代表的なグラフを作成する手順をご説明いたします。
目的 | 推奨グラフ | 本稿の例 |
---|---|---|
構成比を時系列で比較 | 積み上げ棒グラフ | 月別売上高(部門別) |
全体に占める割合を示す | 円グラフ | 部門別売上シェア |
推移やトレンドを把握 | 折れ線グラフ | 商品販売数の月次推移 |
目次
共通ライブラリのインストール
pip install pandas openpyxl
1. 積み上げ棒グラフ(Stacked Bar)
import pandas as pd
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
from openpyxl.utils.dataframe import dataframe_to_rows
# CSV から DataFrame へ読み込み
df_bar = pd.read_csv('monthly_sales.csv', encoding='utf-8')
wb_bar = Workbook()
ws_bar = wb_bar.active
ws_bar.title = 'MonthlySales'
# DataFrame をワークシートへ転記
for r in dataframe_to_rows(df_bar, index=False, header=True):
ws_bar.append(r)
# グラフオブジェクトを作成
chart_bar = BarChart()
chart_bar.type = 'col' # 縦棒
chart_bar.grouping = 'stacked' # 積み上げ
chart_bar.overlap = 100 # 棒同士を重ねる
chart_bar.varyColors = True
# データ系列とラベル
data_ref = Reference(ws_bar, min_col=2, min_row=1,
max_col=7, max_row=ws_bar.max_row)
label_ref = Reference(ws_bar, min_col=1, min_row=2,
max_row=ws_bar.max_row)
chart_bar.add_data(data_ref, titles_from_data=True)
chart_bar.set_categories(label_ref)
# タイトルと軸ラベル
chart_bar.title = 'Monthly Sales by Division'
chart_bar.x_axis.title = 'Month'
chart_bar.y_axis.title = 'Sales (Million JPY)'
# シートへ配置
ws_bar.add_chart(chart_bar, 'I2')
wb_bar.save('monthly_sales_chart.xlsx')
ポイント
grouping='stacked'
で各部門の売上高を積み上げ表示し、全体推移と内訳を同時に把握できます。varyColors=True
を指定すると、系列ごとに自動で異なる色が割り当てられます。
2. 円グラフ(Pie Chart)
import pandas as pd
from openpyxl import Workbook
from openpyxl.chart import PieChart, Reference
from openpyxl.chart.label import DataLabelList
from openpyxl.utils.dataframe import dataframe_to_rows
df_pie = pd.read_csv('division_sales.csv', encoding='utf-8')\
.sort_values(by='CurrentSales', ascending=False)
wb_pie = Workbook()
ws_pie = wb_pie.active
ws_pie.title = 'DivisionSales'
for r in dataframe_to_rows(df_pie, index=False, header=True):
ws_pie.append(r)
pie = PieChart()
pie.style = 37 # Office 既定の落ち着いた配色
data_ref = Reference(ws_pie, min_col=2, min_row=2,
max_row=ws_pie.max_row)
label_ref = Reference(ws_pie, min_col=1, min_row=2,
max_row=ws_pie.max_row)
pie.add_data(data_ref)
pie.set_categories(label_ref)
# 割合表示を有効化
pie.dataLabels = DataLabelList()
pie.dataLabels.showPercent = True
pie.title = 'Sales Share by Division'
ws_pie.add_chart(pie, 'H3')
wb_pie.save('division_sales_pie.xlsx')
ポイント
DataLabelList().showPercent = True
で、扇形の外側にパーセンテージを表示いたします。- 上位部門から順に並べ替えてからグラフ化すると、構成比が視覚的に把握しやすくなります。
3. 折れ線グラフ(Line Chart)
import pandas as pd
from openpyxl import Workbook
from openpyxl.chart import LineChart, Reference
from openpyxl.utils.dataframe import dataframe_to_rows
df_line = pd.read_csv('product_sales.csv', encoding='utf-8')
df_line['SalesQty'] *= 1000 # 単位を合わせるためスケール変換
wb_line = Workbook()
ws_line = wb_line.active
ws_line.title = 'ProductTrend'
for r in dataframe_to_rows(df_line, index=False, header=True):
ws_line.append(r)
line = LineChart()
line.style = 13 # カラフルな線 + マーカー付き
data_ref = Reference(ws_line, min_col=2, min_row=1,
max_row=ws_line.max_row)
label_ref = Reference(ws_line, min_col=1, min_row=2,
max_row=ws_line.max_row)
line.add_data(data_ref, titles_from_data=True)
line.set_categories(label_ref)
line.title = 'Monthly Sales Volume'
line.x_axis.title = 'Month'
line.y_axis.title = 'Quantity'
ws_line.add_chart(line, 'I2')
wb_line.save('product_sales_line.xlsx')
ポイント
style=13
を選択すると、マーカー付き折れ線と落ち着いた配色が自動で適用されます。- 売上数量を 1000 倍してから描画することで、軸の見た目を分かりやすく調整しています。
まとめ
グラフ | 主な利用場面 | キーワード |
---|---|---|
BarChart(stacked) | 複数カテゴリの時系列推移 | grouping='stacked' |
PieChart | 全体に対する割合 | DataLabelList().showPercent |
LineChart | 値の推移・トレンド | style パラメータで視認性向上 |
openpyxl では上記以外にも AreaChart
、RadarChart
、BubbleChart
、DoughnutChart
など多彩なグラフオブジェクトが用意されております。データの性質と訴求ポイントを踏まえて、最適なチャートを選択してください。