gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:08:30 26 4
gpt4 key购买 nike

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

我的软件:

window
Anaconda 4.3.0 x64,包含:
- IPython 5.1.0
- Python 3.6.0
- matplotlib 2.0.0
- 蜘蛛 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()

最佳答案

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

from __future__ import divisionimport matplotlib.pyplot as pltimport numpy as npdef 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')   #Worksplt.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()

关于python - Matplotlib - 更改单个 x 轴刻度标签的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42878462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com