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

kqlmhetl  于 2023-10-24  发布在  其他
关注(0)|答案(3)|浏览(158)

我正在尝试使用matplotlib创建一个垂直条形图,显示世界上5种语言的使用者百分比。为了更好地突出使用率最高的语言,我改变了条形图的颜色。我还想将相应的x轴刻度标签更改为更深的颜色。一切正常,除了我似乎无法更改x轴刻度标签的颜色。

我的软件:

Windows
Anaconda 4.3.0 x64,包含:

  • IPython 5.1.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()
fzwojiic

fzwojiic1#

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

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

qnakjoqk2#

使用color='grey'调用plt.tick_params将更改颜色设置。
你的print语句不起作用,因为它们发生在你用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')
vs91vp4v

vs91vp4v3#

我认为你也可以通过在plt.setp()中索引你想要的xtick_label来做到这一点:

import matplotlib.pyplot as plt

ax = plt.subplot(111)
ax.bar(x=[1, 2, 3], height=[1, 4, 9])
ax.set_xticks([1, 2, 3])
id_tick_change_colour = 1 
plt.setp(ax.get_xticklabels()[id_tick_change_colour], color='red')

相关问题