LoginSignup
1
0

More than 1 year has passed since last update.

matplotlibでアスペクト比設定がうまくいかない

Last updated at Posted at 2021-09-22

※2022/09/18にコメントでいただいた情報を記事に反映

経緯

Pythonで動かして学ぶ!あたらしい数学の教科書という書籍で演習問題を解いていたのだが自分が実装する箇所以外のところのコードが期待通りの処理を行えておらず、タイトル通りの状況となっていた。

環境

Python 3.9.7 64bit
matplotlib 3.4.3

元々のコード(抜粋)

plt.xlim()
plt.ylim()
plt.xlabel()
plt.ylabel()
plt.grid()
plt.axes().set_aspect("equal")
plt.show()

元々のコードの結果

スクリーンショット 2021-09-22 14.08.40.png

修正後のコード(抜粋)

plot = plt.subplot()
plot.set_xlim([-3, 3])
plot.set_ylim([-3, 3])
plot.set_xlabel("x", size=14)
plot.set_ylabel("y", size=14)
plot.grid()
plot.set_aspect('equal')

修正後のコードの結果

スクリーンショット 2021-09-22 14.10.10.png

やっていること

修正前はmatplotlibを直接呼び続けているんですが、修正後は一度変数にsubplotを呼ぶようにしてそちらを使うようにしました。

おわりに

subplotを呼ばなくてもできるんじゃないかという気はするんですが、調べていて見つかったのがこの方法だったのでひとまずはこれで解決としました。
元々のコードに近いやり方があればコメントいただければと思います。

補足

コメントにて著者サイドで期待する修正内容を共有いただいたので更新。
@kog14 さんありがとうございます!
修正後のコード

plt.xlim()
plt.ylim()
plt.xlabel()
plt.ylabel()
plt.grid()
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
1
0
1

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
1
0