@S_S_K_K

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

MatplotlibでX軸目盛りを上下に表示させたい

解決したいこと

Matplotlibでグラフを書いています。
グラフを書く際に、X軸の目盛りを上下で別に表示したいのですが、上手くいきません。

例)下目盛り -4、0、4
  上目盛り -2、2
のような感じです。

解決方法を教えて下さい。

該当するソースコード

import numpy as np
import matplotlib.pyplot as plt

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

plt.plot(x,y)
plt.show()

0 likes

1Answer

まず、matplotlib.axes.Axes.twinyを使い、解決する方法を紹介します。

matplotlib.axes.Axes.twinyで解決
import numpy as np
import matplotlib.pyplot as plt


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

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

# 1軸目
ax1.plot(x, y)
ax1.set_xticks([-4, 0, 4])

# 2軸目(y軸を共通にして同じグラフを書き、軸の目盛りを変える)
ax2 = ax1.twiny()
ax2.plot(x, y)
ax2.set_xticks([-2, 2])

plt.show()

Unknown-35.png

次に、matplotlib.axes.Axes.secondary_xaxisを使い、解決する方法を紹介します。もう少しスマートに描け一般的だと思います。

matplotlib.axes.Axes.secondary_xaxisで解決
import numpy as np
import matplotlib.pyplot as plt


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

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

# 1軸目
ax1.plot(x, y)
ax1.set_xticks([-4, 0, 4])

# 2軸目(secondary_xaxisで軸を上に追加)
ax2 = ax1.secondary_xaxis('top')
ax2.set_xticks([-2, 2])

plt.show()

良かったら
【matplotlib】x軸を上下に、y軸を左右に表示する2つの方法
【matplotlib】 グラフの任意の位置に、複数の単位の軸を表示する方法
に記事を書いたので読んでみてください。

0Like

Comments

  1. @S_S_K_K

    Questioner

    ご回答ありがとうございます。

    matplotlib.axes.Axes.secondary_xaxisを使った方法を使用したのですが、上の軸の数値が-2,2ではなく、-4,-2,0,2,4になってしまいます。

    これは自分だけでしょうか?
  2. 2番目のコードの"matplotlib.axes.Axes.secondary_xaxisで解決"のコードで実行していますでしょうか?
    また下の軸は、-4,,0,4と表示されていますでしょうか?
  3. @S_S_K_K

    Questioner

    はい。2番目のコードで実行しております。
    下の軸は、-4,,0,4となっています。
  4. ここに同じようにticksが変更できない事例がありました。バグのようです。https://stackoverflow.com/questions/58726507/matplotlib-secondary-xaxis-cant-be-formatted
    https://github.com/matplotlib/matplotlib/issues/15621
    このバグの事例では、Matplotlib version: 3.1.1なので、それ以降のmatplotlibのversionだと解決できるかも知れません。
    私はGoogle Colabで動かしていてmatplotlibのversion、
    import matplotlib
    print(matplotlib.__version__)
    >>3.2.2
    では、正常に上の軸の数値が-2,2と動きました。ただ、私も詳しいことは分かっていないです。回答になっていなくてすみません。
    解決策は、@S_S_K_Kさんの今動いているmatplotlib.axes.Axes.twinyのコードを使うか、今の時点どちらのコードも動くGoogle Colabを使うかでしょうか。
  5. @S_S_K_K

    Questioner

    ご親切な回答ありがとうございます。
    バグということで、Google Colabを使えば正常に動きました。

    Google Colabを使う方法で進めていきたいと思います。
    重ねてお礼申し上げます。

Your answer might help someone💌