これは日々の作業を通して学んだことや毎日の生活で気づいたことをを記録しておく備忘録である。
HTML ファイル生成日時: 2023/09/04 07:18:18.947 (台灣標準時)
Matplotlib で図を作る際、図の縦横比を自分で指定したい場合があるでござる。
まずは、特に何も指定せずに以下のように作図してみるでござる。
#!/usr/pkg/bin/python3.9 # # Time-stamp: <2022/05/18 09:05:44 (CST) daisuke> # # importing numpy module import numpy # importing matplotlib module import matplotlib.figure import matplotlib.backends.backend_agg # output file file_output = 'test_00.png' # data data_x = numpy.linspace (0.0, 20.0, 1000) data_y = 0.5 * data_x # making objects "fig" and "ax" fig = matplotlib.figure.Figure () matplotlib.backends.backend_agg.FigureCanvasAgg (fig) ax = fig.add_subplot (111) # axes ax.set_xlabel ("X") ax.set_ylabel ("Y") ax.set_xlim (0.0, 20.0) ax.set_ylim (0.0, 10.0) # plotting data ax.plot (data_x, data_y, '-', label=r'$y=0.5x$') # saving file fig.savefig (file_output, dpi=225)
上のスクリプトを実行すると、以下のような図ができるでござる。 4:3 の縦 横比の横長の長方形の領域全体を使って図が作られるでござる。
![]() |
---|
次に、 set_aspect を使ってみるでござる。以下のようなスクリプトを用意し てみるでござる。
#!/usr/pkg/bin/python3.9 # # Time-stamp: <2022/05/18 09:06:51 (CST) daisuke> # # importing numpy module import numpy # importing matplotlib module import matplotlib.figure import matplotlib.backends.backend_agg # output file file_output = 'test_01.png' # data data_x = numpy.linspace (0.0, 20.0, 1000) data_y = 0.5 * data_x # making objects "fig" and "ax" fig = matplotlib.figure.Figure () matplotlib.backends.backend_agg.FigureCanvasAgg (fig) ax = fig.add_subplot (111) # axes ax.set_xlabel ("X") ax.set_ylabel ("Y") ax.set_xlim (0.0, 20.0) ax.set_ylim (0.0, 10.0) ax.set_aspect ('equal') # plotting data ax.plot (data_x, data_y, '-', label=r'$y=0.5x$') # saving file fig.savefig (file_output, dpi=225)
上のスクリプトを実行してみると、以下のような図ができるでござる。 set_aspect で equal を指定すると、 X 軸と Y 軸のスケールが同じになるで ござる。つまり、 X 軸の 0 から 1 と Y 軸の 0 から 1 が同じ間隔で描かれ るでござる。
![]() |
---|
スケールを同じにしたいのではなく、正方形の図を作りたいという場合もある でござる。それには、以下のようなスクリプトにすればよいようでござる。
#!/usr/pkg/bin/python3.9 # # Time-stamp: <2022/05/18 09:07:40 (CST) daisuke> # # importing numpy module import numpy # importing matplotlib module import matplotlib.figure import matplotlib.backends.backend_agg # output file file_output = 'test_02.png' # data data_x = numpy.linspace (0.0, 20.0, 1000) data_y = 0.5 * data_x # making objects "fig" and "ax" fig = matplotlib.figure.Figure () matplotlib.backends.backend_agg.FigureCanvasAgg (fig) ax = fig.add_subplot (111) # axes ax.set_xlabel ("X") ax.set_ylabel ("Y") ax.set_xlim (0.0, 20.0) ax.set_ylim (0.0, 10.0) ax.set_box_aspect (1) # plotting data ax.plot (data_x, data_y, '-', label=r'$y=0.5x$') # saving file fig.savefig (file_output, dpi=225)
上のスクリプトを実行すると、以下のような図ができるでござる。 X 軸で表 されている範囲と Y 軸で表されている範囲は異なるのでござるが、図自体が 正方形になっているでござる。
![]() |
---|