LoginSignup
2
2

More than 3 years have passed since last update.

python xlwingsを用いたExcelグラフ作成

Last updated at Posted at 2020-05-25

コメント

xlwingsを使ったグラフ作成の参考にしてください。
こうする方がベターだよというご指摘あればうれしいです。
apiを使うとvbaのコードが使える→ わからないことはExcelにて「マクロの記録」で調べられる。
test.xlsxは白紙のワークブックです。

環境

python 3.7
xlwings 0.18.0

サンプルコード

import xlwings as xw
from xlwings.constants import AxisType

DATA_NUM = 10
# エクセルワークブックの読み込み
wb = xw.Book('test.xlsx')

# データの挿入
data_x = list(x for x in range(DATA_NUM))
data_y1 = list(x*2 for x in range(DATA_NUM))
data_y2 = list(x*10-50 for x in range(DATA_NUM))

xw.Range('A1').value = 'x'
xw.Range('B1').value = 'y1'
xw.Range('C1').value = 'y2'

cell_x = xw.Range('A2')
cell_y1 = xw.Range('B2')
cell_y2 = xw.Range('C2')
for cnt in range(DATA_NUM):
    cell_x.value = data_x[cnt]
    cell_y1.value = data_y1[cnt]
    cell_y2.value = data_y2[cnt]

    cell_x = cell_x.offset(1, 0)
    cell_y1 = cell_y1.offset(1, 0)
    cell_y2 = cell_y2.offset(1, 0)

# グラフの挿入
chart = xw.Chart()
# グラフ位置・サイズの調整
chart.left = 200
chart.top = 10
chart.width = 300
chart.height = 200
# グラフ種類の設定
chart.chart_type = 'xy_scatter_lines_no_markers'
# データ範囲の設定
chart.set_source_data(xw.Range('A1:C11'))
# x軸の位置を下端に変更(xlminimum=4 ←VBAの定数を読み込む方法わかる方教えてください)
# api[1]の1の意味がわかる方教えてください。とりあえず1にしておけば動作するのですが・・・。
chart.api[1].Axes(AxisType.xlValue).Crosses = 4
# 軸目盛りを内向きに変更(xlInside=2)
chart.api[1].Axes(AxisType.xlCategory).MajorTickMark = 2
chart.api[1].Axes(AxisType.xlValue).MajorTickMark = 2
2
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2