見出し画像

空の Figure の作り方(matplotlib )

Axes を含まない空の Figure を作ることもできます。

#"empty_Figure.py"
import matplotlib.pyplot as plt
fig = plt.figure()
plt.show()
empty_Figure.py の結果

note の記事の見出し画像サイズ(1280 x 670 px)の Figure を作成して、ファイルとして出力してみました。Figure の大きさはインチで指定しす。1 インチは 2.54 cm です。dpi(dot per inch、インチあたりの点)を同時に指定すれば、希望のピクセル数の画像ファイルが得られます。

#"empty_Figure2.py"
import matplotlib.pyplot as plt

width_px= 1280
height_px = 670

dpi = 300 #default value: 100

width_inch = width_px / dpi
height_inch = height_px / dpi

fig = plt.figure(figsize = [width_inch, height_inch], dpi=dpi)

fig.savefig("empty_Figure2.png")
empty_Figure2.png

中に直接テキストを表示することもできます。日本語フォントがあれば日本語も使用できます。下の例ではカレントディレクトリに置いたフォントファイルをいちいち読み込んでいますが、システムから元々アクセスできれば fm うんぬんは必要ありません。
他にもいろいろFigureに直接描画できそうですが、プロットを行うには、Axes を追加して利用するのがよいでしょう。

#"Figure_with_text.py"
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

font_files = fm.findSystemFonts(fontpaths="./")
for font_file in font_files:
    fm.fontManager.addfont(font_file)

width_px= 1280
height_px = 670

dpi = 300 #default value: 100

title="""日本語フォントがあれば
日本語テキストも
表示できるよ。"""

width_inch = width_px / dpi
height_inch = height_px / dpi

fig = plt.figure(figsize = [width_inch, height_inch], dpi=dpi, facecolor="#99FFFF")

text = fig.text(0.5, 0.5, title, ha="center",va="center", ma="left", fontsize="26", fontname="IPAexGothic", linespacing=1.8)

fig.savefig("Figure_with_text.png")
Figure_with_text.png

参考URL:
https://matplotlib.org/stable/api/pyplot_summary.html
https://matplotlib.org/stable/api/figure_api.html
https://matplotlib.org/stable/api/font_manager_api.html
https://matplotlib.org/stable/api/text_api.html#matplotlib.text.Text


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