見出し画像

PythonでExcelグラフ作成

今回の記事は久しぶりにPythonのコードを共有していきたいと思います。
勉強をするときの材料にしてください。

下記がコードになります。

from openpyxl import Workbook
from openpyxl.chart import Reference, LineChart

wb = Workbook()
ws = wb.active

values = [
    ('YEAR''A松浦''B戸田''C伊勢崎','D佐世保'),
    (201011914122251211196261100),
    (201511164135132208814255400),
    (202010278140899211850243223),
    (202221521141324213288237913)
] # Excelにデータをセットする。


for v in values:
    ws.append(v)

rmin = ws.min_row
rmax = ws.max_row
cmin = ws.min_column
cmax = ws.max_column

chart = LineChart()
src = Reference(ws, min_col=cmin+1, min_row=rmin, max_col=cmax, max_row=rmax)
chart.add_data(src, titles_from_data=True)
cat = Reference(ws, min_col=cmin, min_row=rmin+1, max_row=rmax)  # 項目名の設定
chart.set_categories(cat)
chart.title = 'Sample Chart'  # グラフタイトル
chart.x_axis.title = 'YEAR'  # 軸ラベル
chart.y_axis.title = 'population'
chart.anchor = 'A8'  # グラフの表示位置
chart.width = 16  # グラフのサイズ
chart.height = 8

ws.add_chart(chart)
wb.save('人口比較.xlsx')

# 線の色を変更する
chart.ser[0].graphicalProperties.line.solidFill = "FF0000"
chart.ser[1].graphicalProperties.line.solidFill = "00FF00"
chart.ser[2].graphicalProperties.line.solidFill = "0000FF"
chart.ser[3].graphicalProperties.line.solidFill = "000F0F"
wb.save('人口比較.xlsx')

# 線種を変更する
# 設定可能な値:'lgDash', 'sysDash', 'dashDot', 'solid', 'sysDashDot',
# 'lgDashDotDot', 'dot', 'sysDot', 'sysDashDotDot', 'dash', 'lgDashDot'
chart.ser[0].graphicalProperties.line.dashStyle = 'sysDashDot'
chart.ser[1].graphicalProperties.line.dashStyle = 'lgDash'
chart.ser[2].graphicalProperties.line.dashStyle = 'sysDashDotDot'
chart.ser[3].graphicalProperties.line.dashStyle = 'lgDashDotDot'
wb.save('人口比較.xlsx')

# 線の太さを変更する
chart.ser[0].graphicalProperties.line.width = 10000
chart.ser[1].graphicalProperties.line.width = 20000
chart.ser[2].graphicalProperties.line.width = 30000
chart.ser[3].graphicalProperties.line.width = 40000
wb.save('人口比較.xlsx')

# 線を滑らかにする
chart.ser[0].smooth = True
wb.save('人口比較.xlsx')

# マーカーを変更する
# 設定可能な値:'x', 'auto', 'picture', 'star', 'diamond', 'plus', 'dot',
# 'square', 'dash', 'triangle', 'circle'
chart.ser[0].marker.symbol = 'x'
chart.ser[1].marker.symbol = 'star'
chart.ser[2].marker.symbol = 'diamond'
chart.ser[3].marker.symbol = 'circle'
wb.save('人口比較.xlsx')

# マーカーの色を変更する
chart.ser[0].marker.graphicalProperties.line.solidFill = "FF0000"
chart.ser[1].marker.graphicalProperties.line.solidFill = "00FF00"
chart.ser[2].marker.graphicalProperties.line.solidFill = "0000FF"
chart.ser[3].marker.graphicalProperties.line.solidFill = "000F0F"
wb.save('人口比較.xlsx')

# グラフの種類を変更する
chart.grouping = 'stacked'  # 積み上げ折れ線グラフ
chart.grouping = 'percentStacked'  # 100%積み上げ折れ線グラフ
chart.grouping = 'standard'  # 折れ線グラフ
wb.save('人口比較.xlsx')

実行した結果

人口比較.xlsxExcelが出来ます。

作成されたExcelファイル

グラフを作成して分かることは自分の出身は人口が少ないが年々増えていることが分かります。

逆にDの佐世保などは徐々に人口が減っています。グラフにすることで一目で人口の増加率が分かります。

これは、データ分析をする上での初歩なのでレベルをもっと上げていきたいです。

以上になります。


この記事が気に入ったらサポートをしてみませんか?