2017-03-18 25 views
1

matplotlibを使用して、5つの言語の%スピーカーの縦棒グラフを作成しようとしています。最高の話し言葉をより際立たせるために、私はバーの色を変更しました。私はまた、対応するx軸目盛ラベルをより暗い色に変更したい。私はx軸目盛ラベルの色を変更することができないことを除いて、すべてうまく動作します。

マイソフトウェア:Matplotlib - 単一のx軸目盛りラベルの色を変更する

のWindows
アナコンダ含む4.3.0 x64の、:
- IPython 5.1.0
- matplotlibの2.0.0
- - スパイダー3.1 3.6.0
パイソン.3


私が試したこと/トラブルシューティング:

Formatting only selected tick labelsでソリューションを試したところ、plt.gca().get_xticklabels().set_color()を使用しています。これは、まさに私が望んでいるようです。残念ながら、これは色の値を変更すると思われるにもかかわらず、x軸の目盛りラベルの色を変更しません:

#Does not change label color, but does show red when called 
print("Color before change: " + plt.gca().get_xticklabels()[-3].get_color()) 
plt.gca().get_xticklabels()[-3].set_color('red') #Does not change the label 
print("Color after change: " + plt.gca().get_xticklabels()[-3].get_color()) #Does show the value as 'red' 

コメントが証明したように、x軸の目盛りラベルが赤色に点灯しますが、しません。 get_color()メソッドは、redを返すん:

Color before change: grey 
Color after change: red 

私はget_xticklabels()[index]のインデックスを変える試みているが、それらのすべてが記載されていると同じことをしているようです。

上記の答えは、インデックスを述べまっすぐ進む常にではないので、私はx軸の目盛りラベルのテキスト値をプリントアウトすることにより、いくつかのトラブルシューティングを行ってきた:

for item in plt.gca().get_xticklabels(): 
    print("Text: " + item.get_text()) 

各項目は空欄戻ってきます。

In [9]: runfile('x') 
Text: 
Text: 
Text: 
Text: 
Text: 
Text: 
Text: 

私にはラベルがどこか別の場所に保持されているように見えるか、まだ入力されていないようです。私はとget_xminorticklabels()でおしゃぶりしてみましたが、同様の結果が出ました。

私もまっすぐlabelcolorパラメータに色のリストを渡して試してみました:

label_col_vals = ['grey','grey','black','grey','grey'] 
plt.gca().tick_params(axis='x', labelcolor=label_col_vals) 

しかし、これが唯一の私はフィギュアのメモリ・ロケーションであることを前提とするものを返します。

<matplotlib.figure.Figure at 0x14e297d69b0> 

このget_xticklabels().set_color()メソッドを使用して単一のx軸目盛りラベルの色を変更しようとすると、エラーが発生します。

ValueError: could not convert string to float: 'grey' 

(以下に示すように)動作する単一のカラー値を渡すが、これはx軸目盛ラベルの全てが同じ色に設定します

plt.gca().tick_params(axis='x', labelcolor='grey') 


質問:

単一のx軸目盛ラベルの色を変更するにはどうすればよいですか? labelcolorにリストを渡すか、get_xticklabels().set_color()を有効にする方が望ましいでしょうが、別の方法もいいでしょう。


コード:

''' 
@brief autoprint height labels for each bar 
@detailed The function determines if labels need to be on the inside or outside 
of the bar. The label will always be centered with respect to he width of the 
bar 

@param bars the object holding the matplotlib.pyplot.bar objects 
''' 
def AutoLabelBarVals(bars): 
    import matplotlib.pyplot as plt 

    ax=plt.gca() 

    # Get y-axis height to calculate label position from. 
    (y_bottom, y_top) = ax.get_ylim() 
    y_height = y_top - y_bottom 

    # Add the text to each bar 
    for bar in bars: 
     height = bar.get_height() 
     label_position = height + (y_height * 0.01) 

     ax.text(bar.get_x() + bar.get_width()/2., label_position, 
       '%d' % int(height), 
       ha='center', va='bottom') 

import matplotlib.pyplot as plt 
import numpy as np 

plt.figure() 

''' 
@note data from https://www.ethnologue.com/statistics/size 
''' 
languages =['English','Hindi','Mandarin','Spanish','German'] 
pos = np.arange(len(languages)) 
percent_spoken = [372/6643, 260/6643, 898/6643, 437/6643, 76.8/6643] 
percent_spoken = [x*100 for x in percent_spoken] 

''' 
@brief change ba colors, accentuate Mandarin 
''' 
bar_colors = ['#BAD3C8']*(len(languages)-1) 
bar_colors.insert(2,'#0C82D3') 

bars = plt.bar(pos, percent_spoken, align='center', color=bar_colors) 

''' 
@brief Soften the other bars to highlight Mandarin 
''' 
plt.gca().yaxis.label.set_color('grey') 
label_colors = ['grey','grey','black','grey','grey'] 
#plt.gca().tick_params(axis='x', labelcolor=label_colors) #Does not work 
plt.gca().tick_params(axis='x', labelcolor='grey') #Works 


''' 
@brief Try to change colors as in https://stackoverflow.com/questions/41924963/formatting-only-selected-tick-labels 
''' 
# Try to output values of text to pinpoint which one needs changed 
for item in plt.gca().get_xticklabels(): 
    print("Text: " + item.get_text()) 

print(plt.gca().get_xticklabels()[0].get_text()) 

''' 
@warning If trying to set the x-axis tick labels via list, this code block will fail 
''' 
print("Color before change: " + plt.gca().get_xticklabels()[1].get_color()) 
plt.gca().get_xticklabels()[1].set_color('red') #Does not change the label 
print("Color after change: " + plt.gca().get_xticklabels()[1].get_color()) #Does show the value as 'red' 
''' 
@warning If trying to set the x-axis tick labels via list, this code block will fail 
''' 


plt.xticks(pos, languages) 
plt.title('Speakers of Select Languages as % of World Population') 

# remove all the ticks (both axes), and tick labels on the Y axis 
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on', color='grey') 

''' 
@brief remove the frame of the chart 
''' 
for spine in plt.gca().spines.values(): 
    spine.set_visible(False) 

# Show % values on bars 
AutoLabelBarVals(bars) 

plt.show() 

答えて

2

スクリプトの経過とともにティックラベルが変化することがあります。そのため、スクリプトの最後に色を設定することをお勧めします。

from __future__ import division 
import matplotlib.pyplot as plt 
import numpy as np 

def AutoLabelBarVals(bars): 
    ax=plt.gca() 
    (y_bottom, y_top) = ax.get_ylim() 
    y_height = y_top - y_bottom 
    for bar in bars: 
     height = bar.get_height() 
     label_position = height + (y_height * 0.01) 
     ax.text(bar.get_x() + bar.get_width()/2., label_position, 
       '%d' % int(height), 
       ha='center', va='bottom') 
plt.figure() 
languages =['English','Hindi','Mandarin','Spanish','German'] 
pos = np.arange(len(languages)) 
percent_spoken = [372/6643, 260/6643, 898/6643, 437/6643, 76.8/6643] 
percent_spoken = [x*100 for x in percent_spoken] 
bar_colors = ['#BAD3C8']*(len(languages)-1) 
bar_colors.insert(2,'#0C82D3') 
bars = plt.bar(pos, percent_spoken, align='center', color=bar_colors) 
plt.gca().yaxis.label.set_color('grey') 
plt.gca().tick_params(axis='x', labelcolor='grey') #Works 
plt.xticks(pos, languages) 
plt.title('Speakers of Select Languages as % of World Population') 
plt.tick_params(top='off', bottom='off', left='off', right='off', 
       labelleft='off', labelbottom='on', color='grey') 
for spine in plt.gca().spines.values(): 
    spine.set_visible(False) 
AutoLabelBarVals(bars) 

plt.gca().get_xticklabels()[1].set_color('red') 

plt.show()
1

color='grey'plt.tick_paramsへの呼び出しは、色の設定を上書きしています。

x目盛りラベルをplt.xticks()に設定する前に、印刷ステートメントが実行されていないため、印刷ステートメントが機能しません。 plt.barsの呼び出しの直後に両方の行を移動すると、コードが機能するはずです。

bars = plt.bar(pos, percent_spoken, align='center', color=bar_colors) 

plt.xticks(pos, languages) 
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on', color='grey') 
+0

残念ながら、これは私の状況では機能しませんでした。私は間違った要素を呼んでいるかどうかを見るために指標を変えようとしましたが、まだ運がありません。しかし、提案してくれてありがとう、それは将来の問題で便利になるかもしれない。 –

+0

申し訳ありませんが、これは正しくありませんでした。私はもっ​​と掘り下げています。 – Craig

+0

お探ししています。役立つなら、私はあなたのコードスニペットを望ましい結果で再現することができました。私はそれが問題を引き起こしている私のセットアップではないことを意味していると仮定しています。 –

関連する問題