Matplotlib更改单个xaxis tick lab的颜色

2024-05-05 09:55:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用matplotlib创建一个包含世界上5种语言的%speakers的垂直条形图。为了更好地突出最高的口语,我改变了酒吧的颜色。我还想将相应的x轴刻度标签更改为较深的颜色。一切正常,除了我似乎无法改变x轴刻度标签的颜色。

我的软件:

窗口
水蟒4.3.0 x64,含:
-伊普顿5.1.0
-Python 3.6.0
-matplotlib 2.0.0
-Spyder 3.1.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_xmajorticklabels()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()

Tags: thetoget颜色barplt标签change
2条回答

使用color='grey'调用plt.tick_params将覆盖颜色设置。

打印语句不起作用,因为它们发生在使用plt.xticks()设置x tick标签之前。将这两行移到调用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')

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

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()

相关问题 更多 >