I know how to add collective bar labels to a chart (lots of information for that). My problem is discerning how to modify the label on a single bar I'm calling attention to.
For this example, I want the value label on Daniel to be a few points larger and the same color as the bar.
This is what I have so far:
# 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();
CodePudding user response:
It is possible to modify this property directly by accessing the barlabel object. To do this, when you create the barlabel you store it in a variable (which is a list). Then you access the element of the list corresponding to the label you want to modify and change its properties.
The code with the modifications:
# 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();