如何在Matplotlib barh()中修改单个条形上的bar_label?

siv3szwd  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(135)

我知道如何在图表中添加集合条形标签(这方面的信息很多),但我的问题是如何修改要引起注意的单个条形上的标签。
在本例中,我希望丹尼尔上的值标签比条形图大几点,并且颜色与条形图相同。
这是我目前所掌握的情况:

# Create example data
data = pd.DataFrame.from_dict({'a': 30, 'b': 25, 'c': 35, 'd': 75}, orient = 'index').T

# Plot results
colors_barh = ['#E34234' if i == 'd' else '#2d3047' for i in data.columns]
fig, ax = plt.subplots()
plt.barh(data.columns, data.iloc[0], color = colors_barh)
ax.set_title('Daniel has a lot of Socks', fontsize = 20).set_color('#171819')
ax.tick_params(axis='y', which='both', right=False,
                left=False, colors = '#101010')
ax.tick_params(axis='x', which='both', bottom=False, colors = '#101010')
for pos in ['right', 'top', 'left', 'bottom']:
   plt.gca().spines[pos].set_visible(False)
plt.xticks([])
ax.set_xlabel('Socks per Person', fontsize = 14).set_color('#393d3f')
plt.yticks(['a', 'b', 'c', 'd'], ['Amber', 'Brad', 'Carlie', 'Daniel'])
ax.bar_label(ax.containers[0], padding = 5, size = 15, color = '#2d3047')
plt.show();

i1icjdpr

i1icjdpr1#

可以通过访问barlabel对象直接修改该属性。为此,当你创建barlabel时,你将它存储在一个变量(一个列表)中。然后你访问列表中与你想修改的标签相对应的元素,并修改它的属性。
修改后的代码:

# Create example data
data = pd.DataFrame.from_dict({'a': 30, 'b': 25, 'c': 35, 'd': 75}, orient = 'index').T

# Plot results
colors_barh = ['#E34234' if i == 'd' else '#2d3047' for i in data.columns]
fig, ax = plt.subplots()
plt.barh(data.columns, data.iloc[0], color = colors_barh)
ax.set_title('Daniel has a lot of Socks', fontsize = 20).set_color('#171819')
ax.tick_params(axis='y', which='both', right=False,
                left=False, colors = '#101010')
ax.tick_params(axis='x', which='both', bottom=False, colors = '#101010')
for pos in ['right', 'top', 'left', 'bottom']:
   plt.gca().spines[pos].set_visible(False)
plt.xticks([])
ax.set_xlabel('Socks per Person', fontsize = 14).set_color('#393d3f')
plt.yticks(['a', 'b', 'c', 'd'], ['Amber', 'Brad', 'Carlie', 'Daniel'])

# save reference to added barlabels
barlabels = ax.bar_label(ax.containers[0], padding = 5, size = 15, color = '#2d3047')
# access Daniel's label and change properties
barlabels[-1].set_font_properties({'size': 30})
barlabels[-1].set_color('#E34234')

plt.show();

相关问题