当我将注释添加到条形图时,条形图中会显示很多数字。它在条形图的末尾显示了正确的数字,但我似乎不知道如何删除条形图内的数字。
我认为也许将销售分组到产品会有所帮助,但它仍然显示相同的内容。不幸的是,我无法给出实际数据。
name = group_df['data1']
acw = group_df['data2']
#fig size
fig, ax = plt.subplots(figsize=(16,9))
#horizontal bar
ax.barh(name, acw)
#Remove axes splines
for s in ['top', 'bottom', 'left', 'right']:
ax.spines[s].set_visible(False)
#remove x, y ticks
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
#add padding between axes and labels
ax.xaxis.set_tick_params(pad=5)
ax.yaxis.set_tick_params(pad=10)
#add x, y gridlines
#ax.grid(visible = True, color ='black',
#linestyle ='-.', linewidth = 0.5,
#alpha = 0.2)
#show top values
ax.invert_yaxis()
#add annotation to bars
for i in ax.patches:
plt.text(i.get_width()+0.2, i.get_y()+0.5,
str(round((i.get_width()), 2)),
fontsize = 10, fontweight ='bold',
color ='blue')
#add plot title
ax.set_title('Data',
loc ='left', )
#show plot
plt.show()
使用标准样板代码可以相对直接地实现这一点。
我通常会做这样的事情:
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
# Sample data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [10, 20, 15, 30]
# Create horizontal bar chart
fig, ax = plt.subplots()
ax: Axes
bars = ax.barh(categories, values)
# Add numbers at the end of each bar
for bar in bars:
width = bar.get_width()
ax.text(
width,
bar.get_y() + bar.get_height()/2,
f'{width}',
ha='left',
va='center')
# Display the plot
plt.show()
您可以根据自己的数据进行修改。