LoginSignup
3
0

More than 1 year has passed since last update.

【matplotlib】x軸を上下に、y軸を左右に表示する2つの方法

Last updated at Posted at 2022-01-01

概要

matplotlibでグラフのx軸を上下に、y軸を左右に表示する2つの方法を紹介します。Google Colabで作成したコードは、こちらにあります。

方法

  1. twinxtwinyを使い表示する方法
  2. secondary_xaxissecondary_yaxisを使い表示する方法

注意 matplotlib.axes.Axes.secondary_xaxis、matplotlib.axes.Axes.secondary_yaxisは、matplotlibのversion3.1では、バグがある可能性があります。 バグの事例の1つに、https://github.com/matplotlib/matplotlib/issues/15621があります。

1. twinx、twinyを使い表示する方法

twinx、twinyを使い表示する方法
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)

x = np.arange(0, 5, 0.1)
y = np.sin(x)

# 1軸目
ax1.plot(x, y)
ax1.set_xlabel('x')
ax1.set_ylabel('y')

# 2軸目(twinyを使い、y軸を共通にして同じグラフを書く)
ax2 = ax1.twiny()
ax2.plot(x, y)
ax2.set_xlabel('x')

# 2軸目(twinxを使い、x軸を共通にして同じグラフを書く)
ax3 = ax1.twinx()
ax3.plot(x, y)
ax3.set_ylabel('y')

plt.show()

出力結果
Unknown-40.png

2. secondary_xaxis、secondary_yaxisを使い表示する方法

secondary_xaxis、secondary_yaxisを使い表示する方法
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)

x = np.arange(0, 5, 0.1)
y = np.sin(x)

# 1軸目
ax1.plot(x, y)
ax1.set_xlabel('x')
ax1.set_ylabel('y')

# 2軸目(secondary_xaxisでx軸を上に追加)
ax2 = ax1.secondary_xaxis('top')
ax2.set_xlabel('x')

# 3軸目(secondary_yaxisでy軸を右に追加)
ax3 = ax1.secondary_yaxis('right')
ax3.set_ylabel('y')

plt.show()

出力結果
Unknown-41.png

補足

一般的な使い方は、twinx、twinyは、別々のグラフを表示するときに使うと思います。
secondary_xaxis、secondary_yaxisは、別々の単位をグラフに表示するときに使うと思います。また、任意の位置に複数の単位の軸を置くこともできます。詳しくは、私の記事で恐縮ですが、【matplotlib】 グラフの任意の位置に、複数の単位の軸を表示する方法を参照してください。

まとめ

x軸を上下に、y軸を左右に表示したい場合は、基本的にはsecondary_xaxis、secondary_yaxisを使うと良いと思います。

参考資料

3
0
0

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
0