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()
残念ながら、これは私の状況では機能しませんでした。私は間違った要素を呼んでいるかどうかを見るために指標を変えようとしましたが、まだ運がありません。しかし、提案してくれてありがとう、それは将来の問題で便利になるかもしれない。 –
申し訳ありませんが、これは正しくありませんでした。私はもっと掘り下げています。 – Craig
お探ししています。役立つなら、私はあなたのコードスニペットを望ましい結果で再現することができました。私はそれが問題を引き起こしている私のセットアップではないことを意味していると仮定しています。 –