Matplotlib-更改单个x轴刻度标签的颜色

Dou*_*g B 4 python matplotlib

我正在尝试使用matplotlib创建世界上5种口语的%说话者的垂直条形图。为了更好地强调最高口头语言,我更改了栏的颜色。我还想将相应的x轴刻度标签更改为较深的颜色。一切正常,除非我似乎无法更改x轴刻度标签的颜色。

我的软件:

Windows
Anaconda 4.3.0 x64,包含:
-IPython 5.1.0
-Python 3.6.0
-matplotlib 2.0.0
-Spyder 3.1.3


我尝试过的问题/故障排除:

我试图解决在格式只选定的刻度标记使用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'
Run Code Online (Sandbox Code Playgroud)

正如注释所证明的那样,x轴刻度标签不会变成红色,但是.get_color()方法确实返回red

Color before change: grey
Color after change: red
Run Code Online (Sandbox Code Playgroud)

我尝试过更改的索引get_xticklabels()[index],但它们似乎都与列出的索引相同。

上面提到的答案并非总是直接索引,因此我通过打印出x轴刻度标签的文本值来完成一些故障排除:

for item in plt.gca().get_xticklabels():
    print("Text: " + item.get_text())
Run Code Online (Sandbox Code Playgroud)

每个项目都变空白:

In [9]: runfile('x')
Text: 
Text: 
Text: 
Text: 
Text: 
Text: 
Text: 
Run Code Online (Sandbox Code Playgroud)

在我看来,这些标签正保存在其他地方,或者可能尚未填充。我试着弄乱get_xmajorticklabels()get_xminorticklabels()得到类似的结果。

我也尝试过将颜色列表直接传递给labelcolor参数:

 label_col_vals = ['grey','grey','black','grey','grey']
 plt.gca().tick_params(axis='x', labelcolor=label_col_vals)
Run Code Online (Sandbox Code Playgroud)

但这仅返回我认为是该图的存储位置的信息:

<matplotlib.figure.Figure at 0x14e297d69b0>
Run Code Online (Sandbox Code Playgroud)

如果尝试使用以下get_xticklabels().set_color()方法更改单个x轴刻度标签颜色,这也会导致错误:

ValueError: could not convert string to float: 'grey'
Run Code Online (Sandbox Code Playgroud)

传递单一颜色值(如下所示)是可行的,但这会将所有x轴刻度标签设置为相同的颜色:

 plt.gca().tick_params(axis='x', labelcolor='grey')
Run Code Online (Sandbox Code Playgroud)


题:

如何更改单个x轴刻度标签的颜色? 将列表传递给工作labelcolorget_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 /sf/ask/2934747441/
'''
# 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()
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 8

勾号标签可能会在脚本过程中发生变化。因此,当不再进行任何更改时,建议在脚本的最后设置它们的颜色。

来自__future__进口部门
导入matplotlib.pyplot作为plt
将numpy导入为np

def AutoLabelBarVals(栏):
    ax = plt.gca()
    (y_bottom,y_top)= ax.get_ylim()
    y_height = y_top-y_bottom
    对于酒吧吧:
        高度= bar.get_height()
        label_position =高度+(y_height * 0.01)
        ax.text(bar.get_x()+ bar.get_width()/ 2。,label_position,
                '%d'%int(高度),
                ha ='center',va ='bottom')
plt.figure()
语言= [“英语”,“印地语”,“普通话”,“西班牙语”,“德语”]
pos = np.arange(len(语言))
percent_spoken = [372 / 6643、260 / 6643、898 / 6643、437 / 6643、76.8 / 6643]
percent_spoken = [x * 100 x中的百分比
bar_colors = ['#BAD3C8'] *(len(语言)-1)
bar_colors.insert(2,'#0C82D3')
条= 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,语言)
plt.title(“使用多种语言的人占世界人口的百分比”)
plt.tick_params(top ='off',bottom ='off',left ='off',right ='off', 
                labelleft ='off',labelbottom ='on',color ='grey')
对于plt.gca()。spines.values()中的脊椎:
    spine.set_visible(False)
AutoLabelBarVals(栏)

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

plt.show()

  • @jimh 这个问题有一个单轴,所以这个解决方案专门使用这个单轴。但总体思路当然适用于任意数量的轴。您需要在所有轴上调用 `.get_xticklabels()[1].set_color('red')`。 (4认同)