3
7

More than 3 years have passed since last update.

matplotlibのfigureをエクセルにペタペタ貼る

Posted at

背景/目的

画像ファイルがいっぱい出来るのがうざいので、1つのエクセルにペタペタ貼りたい

方針

figureを画像形式でファイルに保存し、xlsxwriterのinsert_imageで画像を貼る
一度書き出すのが無駄に思えるが、これが一番簡単だと思う

サンプルコードと結果イメージ

import matplotlib.pyplot as plt
import numpy as np

# サンプルfigure作成
plt.close(1)  # なくてもいいけど初期化的な気持ち
fig, ax = plt.subplots(1, 1, figsize=(6,3))
ax.barh(y=range(10),width=range(10))
plt.tight_layout()

# 画像を保存
image_file_path = 'tmp.png'
fig.savefig(image_file_path)

# 新規ワークブックを開く、シートを作る
import xlsxwriter
workbook = xlsxwriter.Workbook('tmp.xlsx')
worksheet = workbook.add_worksheet()

# セルに画像を貼る
worksheet.insert_image('A1', image_file_path)
worksheet.insert_image('K1', image_file_path, {'x_scale': 0.7, 'y_scale': 0.7})
worksheet.insert_image(19, 0, image_file_path)
worksheet.insert_image(19, 10, image_file_path)

# ズーム調整
worksheet.set_zoom(50)

# エクセルワークブックを閉じて終わり
workbook.close()

image.png

参考

xlsxwriterの公式ドキュメント。割としっかりしてる。searchが便利。
https://xlsxwriter.readthedocs.io/worksheet.html#insert_image

3
7
2

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
3
7