2016-08-17 8 views
0

2番目のx軸をmatplotlibプロットに追加します。2番目のプロットを追加するのではなく、最初の軸にリンクされたラベルを追加します。第2のmatplotlib最初の1つに関連するx軸:間違ったティック位置

次のコードプロット第2の軸として第1のX軸LOG10:

import numpy as np 
import matplotlib.pyplot as plt 

fig = plt.figure(3,figsize = [5,4]) 
ax1 = fig.add_subplot(111) 
ax1.set_xlabel('first axis') 
ax1.set_xlim([0, 120]) 
ax1.grid(True) 

ax2 = ax1.twiny() 
ax2.set_xlim(ax1.get_xlim()) 
# or alternatively : 
# ax2.set_xbound(ax1.get_xbound()) 
second_ticks = np.array([1.,10.,100.]) 
ax2.set_xticks(second_ticks) 
ax2.set_xticklabels(np.log10(second_ticks)) 
ax2.set_xlabel('second axis') 

plt.show() 

何とかこの questionで回答が第2の軸の境界内に問題をアドレスすることができません

それは動作します! は、今度は、今では失敗したax1.set_xlim([20, 120])

enter image description here

ax1.set_xlim([0, 120])を変更することができます。私はax2.set_xbound(ax1.get_xbound())と違いはありませんでした。どういうわけかax2.set_xticksは、右のxの制限に従ってダニを配置できません。

EDIT:

私はそれが再び間違ったこと与えどこでもax2.set_xlim(ax1.get_xlim())ax1.set_xlim([20, 120])を配置しようとした:実際に私はax2.set_xticks()の意味を得ることはありません、それはどこticklabels位置を設定

enter image description here

をいいえ表示されますか?

EDIT:

[OK]を、私たちはそれを得た:x_lim定義ax2.set_xlim(ax1.get_xlim())はダニとticklabel定義の後に来なければなりません。

import numpy as np 
import matplotlib.pyplot as plt 

plt.close('all') 

fig = plt.figure(1,figsize = [5,4]) 
ax1 = fig.add_subplot(111) 
ax1.set_xlabel('first axis') 
ax1.grid(True) 
ax1.set_xlim([10, 120]) 

ax2 = ax1.twiny() 

second_ticks = np.array([1.,10.,100.]) 
ax2.set_xticks(second_ticks) 
ax2.set_xticklabels(np.log10(second_ticks)) 
ax2.set_xlabel('second axis') 
ax2.set_xlim(ax1.get_xlim()) 

fig.tight_layout() 

plt.show() 

enter image description here

ありがとう!

よろしく、

答えて

1

は、私はあなたが何かを事前に定義されるように第2の軸上のx-ティックおよびX-ダニのラベルを強制されているので、あなたが予期しない結果を得ていると信じています。第2軸に何を置いても、常にax2.set_xticklabels(np.log10(second_ticks))というラベルが付けられます。代わりに、あなたが最初の軸、これはあなたの問題を解決してい

import numpy as np 
import matplotlib.pyplot as plt 

fig = plt.figure(3,figsize = [5,4]) 
ax1 = fig.add_subplot(111) 
ax1.set_xlabel('first axis') 
x = np.linspace(0,100,num=200) 
ax1.set_xlim([0, 120]) 
ax1.grid(True) 

ax2 = ax1.twiny() 
ax2.set_xlim(ax1.get_xlim()) 
# or alternatively : 
# ax2.set_xbound(ax1.get_xbound()) 
# second_ticks = np.array([1.,10.,100.]) 
# ax2.set_xticks(second_ticks) 
ax2.set_xlabel('second axis') 

# Set the xlim on axis 1, then update the x-tick-labels on axis 2 
ax1.set_xlim([20, 100]) 
ax2.set_xticklabels(np.log10(ax1.get_xticks())) 
plt.show() 

にそれらを更新した後の第2の軸上のx-ダニラベルを更新しますか? (Ps。コードにいくつかのタイプミスがあります...実行可能ではありません...)

+0

私はタイプミスを修正しました。いいえ、うまくいきません(質問の編集を参照)。私は正確にax2.set_ticks()と何が誤解されていると思うし、matplotlipのヘルプは浅いです。 –

+0

私はそれを得ました。私はあなたが書いたコードに合わないあなたのテキストを間違えました。 'ax2.set_xlim(ax1.get_xlim())'が最後に来なければならない –

関連する問題