2016-05-17 6 views
1

matplotlibを使用して棒グラフをプロットしています。ラベルを変更するために(X軸とY軸の両方に)ラベルにアクセスしようとすると問題が発生しています。特に、このコード:matplotlibのget_yticklabelsに関する問題

fig = plot.figure(figsize=(16,12), dpi=(300)) 
ax1 = fig.add_subplot(111) 
ax1.set_ylabel("simulated quantity") 
ax1.set_xlabel("simulated peptides - from most to least abundant") 

# create the bars, and set a different color for the bars referring to experimental peptides 
barlist = ax1.bar(numpy.arange(len(quantities)), [numpy.log10(x) for x in quantities]) 
for index, peptide in enumerate(peptides) : 
     if peptide in experimentalPeptidesP or peptide in experimentalPeptidesUP : 
       barlist[index].set_color('b') 

labelsY = ax1.get_yticklabels(which='both') 
print "These are the label objects on the Y axis:", labelsY 
print "These are the labels on the Y axis:", [item.get_text() for item in ax1.get_xticklabels( which='both')] 
for label in labelsY : label.set_text("AAAAA") 
ax1.set_yticklabels(labelsY) 

は、次の出力与える:

These are the label objects on the Y axis: <a list of 8 Text yticklabel objects> 
These are the labels on the Y axis: [u'', u'', u'', u'', u'', u''] 

を、要求された結果として得られた図は、Y軸上のすべてのラベルのテキストとして「AAAAA」を持っています。私の問題は、私は正しくラベルを設定することができますが、明らかに私は彼らのテキストを取得することはできません...そして、テキストが存在するはずです。私は "AAAAA"とラベルを置き換えない場合、私は次の図を得る: enter image description here

ご覧のとおり、Y軸にラベルがあり、テキストを取得する必要があります。エラーはどこですか?

ご協力いただきありがとうございます。

EDIT:MikeMüller氏のおかげで、私はそれを動作させることができました。どうやら、私の場合draw()を呼び出すだけでは不十分です。savefig()を使って数値を保存した後に値を取得する必要があります。それはmatplotlibのバージョンに依存するかもしれません、私は1.5.1を実行していて、Mikeは1.5.0を実行しています。以下にtcaswellのようにFuncFormatterを見てみましょう

+0

これらのオブジェクトは、ティッカー/フォーマッタ機械に置き換えられているため。実際に何をしようとしていますか? – tacaswell

+0

自動的に配置されたY軸上のラベル(上記の例では "0.0"、 "0.5"、 "1.0"、...)を読み取り、それらをpow(10、0.0)、pow 0.5)、pow(10、1.0)、... – Alberto

+0

Mplには、このようなことを行うための軸のログスケールがあります。他の賢い使い方FuncFormatter – tacaswell

答えて

2

実際にラベルを取得するには、最初にプロットをレンダリングする必要があります。なければ

plot.draw() 
labelsY = ax1.get_yticklabels(which='both') 

from matplotlib import pyplot as plt 

fig = plt.figure(figsize=(16,12), dpi=(300)) 
ax1 = fig.add_subplot(111) 
p = ax1.bar(range(5), range(5)) 

>>> [item.get_text() for item in ax1.get_yticklabels(which='both')] 
['', '', '', '', '', '', '', '', ''] 

draw()と:draw()作品を追加

from matplotlib import pyplot as plt 

fig = plt.figure(figsize=(16,12), dpi=(300)) 
ax1 = fig.add_subplot(111) 
p = ax1.bar(range(5), range(5)) 
plt.draw() 

>>> [item.get_text() for item in ax1.get_yticklabels(which='both')] 
['0.0', '0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0'] 
+0

こんにちは!私はラベルを収集する前に "plot.draw()"行を追加しようとしましたが、明らかに結果は同じです。私は8つのオブジェクトを取得しますが、テキストを視覚化することはできません。 – Alberto

+0

あなたはどのバージョンを使用していますか? 1.5.0で動作するようになった。 –

+0

1.5.1;あなたのアドバイスのおかげで、私はそれを動作させることができました。どうやら、savefig()を使って数字をSAVE *した後にラベルを取得する必要があります。テキストが表示されます。これは2回保存する必要があることを意味します:-D Weird ...おそらく、 show()? – Alberto